file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
list
attention_mask
list
labels
list
pragma solidity ^0.4.24; 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); } library SafeMath { int256 constant private INT256_MIN = -2**255; /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; 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 Multiplies two signed integers, reverts on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below int256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold 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); // Solidity only automatically asserts when dividing by 0 require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow int256 c = a / b; return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev 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)); return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev 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)); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return 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) { _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&#39;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) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } /** * @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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _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 * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { 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; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender&#39;s allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string name, string symbol, uint8 decimals) public { _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; } } contract ERC20Burnable is ERC20 { /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The 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 { _burnFrom(from, value); } } contract Stasia is ERC20, ERC20Detailed, ERC20Burnable { uint256 public constant INITIAL_SUPPLY = 10000000000 * 10**18; /** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor () public ERC20Detailed("STASIA", "STASIA", 18) { _mint(msg.sender, INITIAL_SUPPLY); } }
* @dev Constructor that gives msg.sender all of existing tokens./
constructor () public ERC20Detailed("STASIA", "STASIA", 18) { _mint(msg.sender, INITIAL_SUPPLY); }
2,269,328
[ 1, 6293, 716, 14758, 1234, 18, 15330, 777, 434, 2062, 2430, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1832, 1071, 4232, 39, 3462, 40, 6372, 2932, 882, 37, 2320, 37, 3113, 315, 882, 37, 2320, 37, 3113, 6549, 13, 288, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 28226, 67, 13272, 23893, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; contract IMigrationContract { function migrate(address _addr, uint256 _tokens, uint256 _totaltokens) public returns (bool success); } /* taking ideas from FirstBlood token */ contract SafeMath { function safeAdd(uint256 x, uint256 y) internal pure returns(uint256) { uint256 z = x + y; assert((z >= x) && (z >= y)); return z; } function safeSubtract(uint256 x, uint256 y) internal pure returns(uint256) { assert(x >= y); uint256 z = x - y; return z; } function safeMult(uint256 x, uint256 y) internal pure returns(uint256) { uint256 z = x * y; assert((x == 0)||(z/x == y)); return z; } function safeDiv(uint256 x, uint256 y) internal pure returns(uint256) { uint256 z = x / y; return z; } } /** * @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 ethFundDeposit; event OwnershipTransferred(address indexed ethFundDeposit, address indexed _newFundDeposit); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { ethFundDeposit = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == ethFundDeposit); _; } /** * @dev Allows the current owner to transfer control of the contract to a _newFundDeposit. * @param _newFundDeposit The address to transfer ownership to. */ function transferOwnership(address _newFundDeposit) public onlyOwner { require(_newFundDeposit != address(0)); emit OwnershipTransferred(ethFundDeposit, _newFundDeposit); ethFundDeposit = _newFundDeposit; } } /** * @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 allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } /** * @title Controllable * @dev Base contract which allows children to control the address */ contract controllable is Ownable { event AddToBlacklist(address _addr); event DeleteFromBlacklist(address _addr); // controllable variable mapping (address => bool) internal blacklist; // black list /** * @dev called by the owner to AddToBlacklist */ function addtoblacklist(address _addr) public onlyOwner { blacklist[_addr] = true; emit AddToBlacklist(_addr); } /** * @dev called by the owner to unpDeleteFromBlacklistause */ function deletefromblacklist(address _addr) public onlyOwner { blacklist[_addr] = false; emit DeleteFromBlacklist(_addr); } /** * @dev called by the owner to check the blacklist address */ function isBlacklist(address _addr) public view returns(bool) { return blacklist[_addr]; } } /** * @title Lockable * @dev Base contract which allows children to control the token release mechanism */ contract Lockable is Ownable, SafeMath { // parameters mapping (address => uint256) balances; mapping (address => uint256) totalbalances; uint256 public totalreleaseblances; mapping (address => mapping (uint256 => uint256)) userbalances; // address , order ,balances amount mapping (address => mapping (uint256 => uint256)) userRelease; // address , order ,release amount mapping (address => mapping (uint256 => uint256)) isRelease; // already release period mapping (address => mapping (uint256 => uint256)) userChargeTime; // address , order ,charge time mapping (address => uint256) userChargeCount; // user total charge times mapping (address => mapping (uint256 => uint256)) lastCliff; // address , order ,last cliff time // userbalances each time segmentation mapping (address => mapping (uint256 => mapping (uint256 => uint256))) userbalancesSegmentation; // address , order ,balances amount uint256 internal duration = 30*15 days; uint256 internal cliff = 90 days; // event event userlockmechanism(address _addr,uint256 _amount,uint256 _timestamp); event userrelease(address _addr, uint256 _times, uint256 _amount); modifier onlySelfOrOwner(address _addr) { require(msg.sender == _addr || msg.sender == ethFundDeposit); _; } function LockMechanism ( address _addr, uint256 _value ) internal { require(_addr != address(0)); require(_value != 0); // count userChargeCount[_addr] = safeAdd(userChargeCount[_addr],1); uint256 _times = userChargeCount[_addr]; // time userChargeTime[_addr][_times] = ShowTime(); // balances userbalances[_addr][_times] = _value; initsegmentation(_addr,userChargeCount[_addr],_value); totalbalances[_addr] = safeAdd(totalbalances[_addr],_value); isRelease[_addr][_times] = 0; emit userlockmechanism(_addr,_value,ShowTime()); } // init segmentation function initsegmentation(address _addr,uint256 _times,uint256 _value) internal { for (uint8 i = 1 ; i <= 5 ; i++ ) { userbalancesSegmentation[_addr][_times][i] = safeDiv(_value,5); } } // calculate period function CalcPeriod(address _addr, uint256 _times) public view returns (uint256) { uint256 userstart = userChargeTime[_addr][_times]; if (ShowTime() >= safeAdd(userstart,duration)) { return 5; } uint256 timedifference = safeSubtract(ShowTime(),userstart); uint256 period = 0; for (uint8 i = 1 ; i <= 5 ; i++ ) { if (timedifference >= cliff) { timedifference = safeSubtract(timedifference,cliff); period += 1; } } return period; } // ReleasableAmount() looking for the current releasable amount function ReleasableAmount(address _addr, uint256 _times) public view returns (uint256) { require(_addr != address(0)); uint256 period = CalcPeriod(_addr,_times); if (safeSubtract(period,isRelease[_addr][_times]) > 0){ uint256 amount = 0; for (uint256 i = safeAdd(isRelease[_addr][_times],1) ; i <= period ; i++ ) { amount = safeAdd(amount,userbalancesSegmentation[_addr][_times][i]); } return amount; } else { return 0; } } // release() release the current releasable amount function release(address _addr, uint256 _times) external onlySelfOrOwner(_addr) { uint256 amount = ReleasableAmount(_addr,_times); require(amount > 0); userRelease[_addr][_times] = safeAdd(userRelease[_addr][_times],amount); balances[_addr] = safeAdd(balances[_addr],amount); lastCliff[_addr][_times] = ShowTime(); isRelease[_addr][_times] = CalcPeriod(_addr,_times); totalreleaseblances = safeAdd(totalreleaseblances,amount); emit userrelease(_addr, _times, amount); } // ShowTime function ShowTime() internal view returns (uint256) { return block.timestamp; } // totalBalance() function totalBalanceOf(address _addr) public view returns (uint256) { return totalbalances[_addr]; } // ShowRelease() looking for the already release amount of the address at some time function ShowRelease(address _addr, uint256 _times) public view returns (uint256) { return userRelease[_addr][_times]; } // ShowUnrelease() looking for the not yet release amount of the address at some time function ShowUnrelease(address _addr, uint256 _times) public view returns (uint256) { return safeSubtract(userbalances[_addr][_times],ShowRelease(_addr,_times)); } // ShowChargeTime() looking for the charge time function ShowChargeTime(address _addr, uint256 _times) public view returns (uint256) { return userChargeTime[_addr][_times]; } // ShowChargeCount() looking for the user total charge times function ShowChargeCount(address _addr) public view returns (uint256) { return userChargeCount[_addr]; } // ShowNextCliff() looking for the nex cliff time function ShowNextCliff(address _addr, uint256 _times) public view returns (uint256) { return safeAdd(lastCliff[_addr][_times],cliff); } // ShowSegmentation() looking for the user balances Segmentation function ShowSegmentation(address _addr, uint256 _times,uint256 _period) public view returns (uint256) { return userbalancesSegmentation[_addr][_times][_period]; } } contract Token { uint256 public totalSupply; function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /* ERC 20 token */ contract StandardToken is controllable, Pausable, Token, Lockable { function transfer(address _to, uint256 _value) public whenNotPaused() returns (bool success) { if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to] && !isBlacklist(msg.sender)) { // sender balances[msg.sender] = safeSubtract(balances[msg.sender],_value); totalbalances[msg.sender] = safeSubtract(totalbalances[msg.sender],_value); // _to balances[_to] = safeAdd(balances[_to],_value); totalbalances[_to] = safeAdd(totalbalances[_to],_value); emit Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused() returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to] && !isBlacklist(msg.sender)) { // _to balances[_to] = safeAdd(balances[_to],_value); totalbalances[_to] = safeAdd(totalbalances[_to],_value); // _from balances[_from] = safeSubtract(balances[_from],_value); totalbalances[_from] = safeSubtract(totalbalances[_from],_value); // allowed allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender],_value); emit Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } // mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } contract BugXToken is StandardToken { /** * base parameters */ // metadata string public constant name = "BUGX2.0"; string public constant symbol = "BUGX"; uint256 public constant decimals = 18; string public version = "2.0"; // contracts address public newContractAddr; // the new contract for BUGX token updates; // crowdsale parameters bool public isFunding; // switched to true in operational state uint256 public fundingStartBlock; uint256 public fundingStopBlock; uint256 public currentSupply; // current supply tokens for sell uint256 public tokenRaised = 0; // the number of total sold token uint256 public tokenIssued = 0; // the number of total issued token uint256 public tokenMigrated = 0; // the number of total Migrated token uint256 internal tokenExchangeRate = 9000; // 9000 BUGX tokens per 1 ETH uint256 internal tokenExchangeRateTwo = 9900; // 9000 * 1.1 BUGX tokens per 1 ETH uint256 internal tokenExchangeRateThree = 11250; // 9000 * 1.25 BUGX tokens per 1 ETH // events event AllocateToken(address indexed _to, uint256 _value); // issue token to buyer; event TakebackToken(address indexed _from, uint256 _value); // record token take back info; event RaiseToken(address indexed _to, uint256 _value); // record token raise info; event IssueToken(address indexed _to, uint256 _value); event IncreaseSupply(uint256 _value); event DecreaseSupply(uint256 _value); event Migrate(address indexed _addr, uint256 _tokens, uint256 _totaltokens); // format decimals. function formatDecimals(uint256 _value) internal pure returns (uint256 ) { return _value * 10 ** decimals; } /** * constructor function */ // constructor constructor( address _ethFundDeposit, uint256 _currentSupply ) public { require(_ethFundDeposit != address(0x0)); ethFundDeposit = _ethFundDeposit; isFunding = false; //controls pre through crowdsale state fundingStartBlock = 0; fundingStopBlock = 0; currentSupply = formatDecimals(_currentSupply); totalSupply = formatDecimals(1500000000); //1,500,000,000 total supply require(currentSupply <= totalSupply); balances[ethFundDeposit] = currentSupply; totalbalances[ethFundDeposit] = currentSupply; } /** * Modify currentSupply functions */ /// @dev increase the token's supply function increaseSupply (uint256 _tokens) onlyOwner external { uint256 _value = formatDecimals(_tokens); require (_value + currentSupply <= totalSupply); currentSupply = safeAdd(currentSupply, _value); tokenadd(ethFundDeposit,_value); emit IncreaseSupply(_value); } /// @dev decrease the token's supply function decreaseSupply (uint256 _tokens) onlyOwner external { uint256 _value = formatDecimals(_tokens); uint256 tokenCirculation = safeAdd(tokenRaised,tokenIssued); require (safeAdd(_value,tokenCirculation) <= currentSupply); currentSupply = safeSubtract(currentSupply, _value); tokensub(ethFundDeposit,_value); emit DecreaseSupply(_value); } /** * Funding functions */ modifier whenFunding() { require (isFunding); require (block.number >= fundingStartBlock); require (block.number <= fundingStopBlock); _; } /// @dev turn on the funding state function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) onlyOwner external { require (!isFunding); require (_fundingStartBlock < _fundingStopBlock); require (block.number < _fundingStartBlock); fundingStartBlock = _fundingStartBlock; fundingStopBlock = _fundingStopBlock; isFunding = true; } /// @dev turn off the funding state function stopFunding() onlyOwner external { require (isFunding); isFunding = false; } /** * migrate functions */ /// @dev set a new contract for recieve the tokens (for update contract) function setMigrateContract(address _newContractAddr) onlyOwner external { require (_newContractAddr != newContractAddr); newContractAddr = _newContractAddr; } /// sends the tokens to new contract by owner function migrate(address _addr) onlySelfOrOwner(_addr) external { require(!isFunding); require(newContractAddr != address(0x0)); uint256 tokens_value = balances[_addr]; uint256 totaltokens_value = totalbalances[_addr]; require (tokens_value != 0 || totaltokens_value != 0); balances[_addr] = 0; totalbalances[_addr] = 0; IMigrationContract newContract = IMigrationContract(newContractAddr); require (newContract.migrate(_addr, tokens_value, totaltokens_value)); tokenMigrated = safeAdd(tokenMigrated, totaltokens_value); emit Migrate(_addr, tokens_value, totaltokens_value); } /** * tokenRaised and tokenIssued control functions * base functions */ /// token raised function tokenRaise (address _addr,uint256 _value) internal { uint256 tokenCirculation = safeAdd(tokenRaised,tokenIssued); require (safeAdd(_value,tokenCirculation) <= currentSupply); tokenRaised = safeAdd(tokenRaised, _value); emit RaiseToken(_addr, _value); } /// issue token 1 : token issued function tokenIssue (address _addr,uint256 _value) internal { uint256 tokenCirculation = safeAdd(tokenRaised,tokenIssued); require (safeAdd(_value,tokenCirculation) <= currentSupply); tokenIssued = safeAdd(tokenIssued, _value); emit IssueToken(_addr, _value); } /// issue token 2 : issue token take back function tokenTakeback (address _addr,uint256 _value) internal { require (tokenIssued >= _value); tokenIssued = safeSubtract(tokenIssued, _value); emit TakebackToken(_addr, _value); } /// issue token take from ethFundDeposit to user function tokenadd (address _addr,uint256 _value) internal { require(_value != 0); require (_addr != address(0x0)); balances[_addr] = safeAdd(balances[_addr], _value); totalbalances[_addr] = safeAdd(totalbalances[_addr], _value); } /// issue token take from user to ethFundDeposit function tokensub (address _addr,uint256 _value) internal { require(_value != 0); require (_addr != address(0x0)); balances[_addr] = safeSubtract(balances[_addr], _value); totalbalances[_addr] = safeSubtract(totalbalances[_addr], _value); } /** * tokenRaised and tokenIssued control functions * main functions */ /// Issues tokens to buyers. function allocateToken(address _addr, uint256 _tokens) onlyOwner external { uint256 _value = formatDecimals(_tokens); tokenadd(_addr,_value); tokensub(ethFundDeposit,_value); tokenIssue(_addr,_value); emit Transfer(ethFundDeposit, _addr, _value); } /// Issues tokens deduction. function deductionToken (address _addr, uint256 _tokens) onlyOwner external { uint256 _value = formatDecimals(_tokens); tokensub(_addr,_value); tokenadd(ethFundDeposit,_value); tokenTakeback(_addr,_value); emit Transfer(_addr, ethFundDeposit, _value); } /// add the segmentation function addSegmentation(address _addr, uint256 _times,uint256 _period,uint256 _tokens) onlyOwner external returns (bool) { uint256 amount = userbalancesSegmentation[_addr][_times][_period]; if (amount != 0 && _tokens != 0){ uint256 _value = formatDecimals(_tokens); userbalancesSegmentation[_addr][_times][_period] = safeAdd(amount,_value); userbalances[_addr][_times] = safeAdd(userbalances[_addr][_times], _value); totalbalances[_addr] = safeAdd(totalbalances[_addr], _value); tokensub(ethFundDeposit,_value); tokenIssue(_addr,_value); return true; } else { return false; } } /// sub the segmentation function subSegmentation(address _addr, uint256 _times,uint256 _period,uint256 _tokens) onlyOwner external returns (bool) { uint256 amount = userbalancesSegmentation[_addr][_times][_period]; if (amount != 0 && _tokens != 0){ uint256 _value = formatDecimals(_tokens); userbalancesSegmentation[_addr][_times][_period] = safeSubtract(amount,_value); userbalances[_addr][_times] = safeSubtract(userbalances[_addr][_times], _value); totalbalances[_addr] = safeSubtract(totalbalances[_addr], _value); tokenadd(ethFundDeposit,_value); tokenTakeback(_addr,_value); return true; } else { return false; } } /** * tokenExchangeRate functions */ /// @dev set the token's tokenExchangeRate, function setTokenExchangeRate(uint256 _RateOne,uint256 _RateTwo,uint256 _RateThree) onlyOwner external { require (_RateOne != 0 && _RateTwo != 0 && _RateThree != 0); require (_RateOne != tokenExchangeRate && _RateTwo != tokenExchangeRateTwo && _RateThree != tokenExchangeRateThree); tokenExchangeRate = _RateOne; tokenExchangeRateTwo = _RateTwo; tokenExchangeRateThree = _RateThree; } /// calculate the tokenExchangeRate function computeTokenAmount(uint256 _eth) internal view returns (uint256 tokens) { if(_eth > 0 && _eth < 100 ether){ tokens = safeMult(_eth, tokenExchangeRate); } if (_eth >= 100 ether && _eth < 500 ether){ tokens = safeMult(_eth, tokenExchangeRateTwo); } if (_eth >= 500 ether ){ tokens = safeMult(_eth, tokenExchangeRateThree); } } /** * Append : the LockMechanism functions by owner */ function LockMechanismByOwner ( address _addr, uint256 _tokens ) external onlyOwner whenFunding { require (_tokens != 0); uint256 _value = formatDecimals(_tokens); tokenRaise(_addr,_value); tokensub(ethFundDeposit,_value); LockMechanism(_addr,_value); emit Transfer(ethFundDeposit,_addr,_value); } /** * ETH control functions */ /// @dev sends ETH to BUGX team function transferETH() onlyOwner external { require (address(this).balance != 0); ethFundDeposit.transfer(address(this).balance); } function () public payable whenFunding { // fallback function require (msg.value != 0); uint256 _value = computeTokenAmount(msg.value); tokenRaise(msg.sender,_value); tokensub(ethFundDeposit,_value); LockMechanism(msg.sender,_value); emit Transfer(ethFundDeposit,msg.sender,_value); } }
@dev turn on the funding state
function startFunding (uint256 _fundingStartBlock, uint256 _fundingStopBlock) onlyOwner external { require (!isFunding); require (_fundingStartBlock < _fundingStopBlock); require (block.number < _fundingStartBlock); fundingStartBlock = _fundingStartBlock; fundingStopBlock = _fundingStopBlock; isFunding = true; }
5,466,097
[ 1, 20922, 603, 326, 22058, 919, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 787, 42, 14351, 261, 11890, 5034, 389, 74, 14351, 1685, 1768, 16, 2254, 5034, 389, 74, 14351, 4947, 1768, 13, 1338, 5541, 3903, 288, 203, 3639, 2583, 16051, 291, 42, 14351, 1769, 203, 3639, 2583, 261, 67, 74, 14351, 1685, 1768, 411, 389, 74, 14351, 4947, 1768, 1769, 203, 3639, 2583, 261, 2629, 18, 2696, 411, 389, 74, 14351, 1685, 1768, 1769, 203, 203, 3639, 22058, 1685, 1768, 273, 389, 74, 14351, 1685, 1768, 31, 203, 3639, 22058, 4947, 1768, 273, 389, 74, 14351, 4947, 1768, 31, 203, 3639, 17646, 14351, 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 ]
pragma solidity ^0.4.24; contract EthertipGateway { event Withdraw(address indexed owner, uint value); event Deposit(address indexed from, uint value); mapping(uint=>uint) public used; mapping(uint=>address) public users; address public validator; uint public tipToEther = 0.0001 ether; constructor (address _validator) public { validator = _validator; } function () public payable { emit Deposit(msg.sender, msg.value); } function register(uint _id, address _address) public { require(msg.sender == validator); users[_id] = _address; } function withdraw(uint _id, uint _value, bytes _sig) public { bytes32 dataHash = keccak256(validator, _id, _value); bytes32 prefixedHash = keccak256("\x19Ethereum Signed Message:\n32", dataHash); address recovered = getRecoveredAddress(_sig, prefixedHash); require(validator == recovered); require(users[_id] == msg.sender); require(used[_id] < _value); uint _transfer = (_value - used[_id]) * tipToEther; used[_id] = _value; msg.sender.transfer(_transfer); emit Withdraw(msg.sender, _transfer); } function getRecoveredAddress(bytes sig, bytes32 dataHash) internal pure returns (address addr) { bytes32 ra; bytes32 sa; uint8 va; // Check the signature length if (sig.length != 65) { return (0); } // Divide the signature in r, s and v variables assembly { ra := mload(add(sig, 32)) sa := mload(add(sig, 64)) va := byte(0, mload(add(sig, 96))) } if (va < 27) { va += 27; } address recoveredAddress = ecrecover(dataHash, va, ra, sa); return (recoveredAddress); } }
Check the signature length Divide the signature in r, s and v variables
function getRecoveredAddress(bytes sig, bytes32 dataHash) internal pure returns (address addr) { bytes32 ra; bytes32 sa; uint8 va; if (sig.length != 65) { return (0); } assembly { ra := mload(add(sig, 32)) sa := mload(add(sig, 64)) va := byte(0, mload(add(sig, 96))) } if (va < 27) { va += 27; } address recoveredAddress = ecrecover(dataHash, va, ra, sa); return (recoveredAddress); }
6,455,104
[ 1, 1564, 326, 3372, 769, 21411, 831, 326, 3372, 316, 436, 16, 272, 471, 331, 3152, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5561, 16810, 1887, 12, 3890, 3553, 16, 1731, 1578, 501, 2310, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 2867, 3091, 13, 203, 565, 288, 203, 3639, 1731, 1578, 767, 31, 203, 3639, 1731, 1578, 7864, 31, 203, 3639, 2254, 28, 14162, 31, 203, 203, 3639, 309, 261, 7340, 18, 2469, 480, 15892, 13, 288, 203, 1850, 327, 261, 20, 1769, 203, 3639, 289, 203, 203, 3639, 19931, 288, 203, 1850, 767, 519, 312, 945, 12, 1289, 12, 7340, 16, 3847, 3719, 203, 1850, 7864, 519, 312, 945, 12, 1289, 12, 7340, 16, 5178, 3719, 203, 1850, 14162, 519, 1160, 12, 20, 16, 312, 945, 12, 1289, 12, 7340, 16, 19332, 20349, 203, 3639, 289, 203, 203, 3639, 309, 261, 15304, 411, 12732, 13, 288, 203, 1850, 14162, 1011, 12732, 31, 203, 3639, 289, 203, 203, 3639, 1758, 24616, 1887, 273, 425, 1793, 3165, 12, 892, 2310, 16, 14162, 16, 767, 16, 7864, 1769, 203, 203, 3639, 327, 261, 266, 16810, 1887, 1769, 203, 565, 289, 1377, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; import "./WonkaLibrary.sol"; /// @title An Ethereum contract that contains the metadata for a rules engine /// @author Aaron Kendall /// @notice 1.) Certain steps are required in order to use this engine correctly + 2.) Deployment of this contract to a blockchain is expensive (~8000000 gas) + 3.) Various require() statements are commented out to save deployment costs /// @dev Even though you can create rule trees by calling this contract directly, it is generally recommended that you create them using the Nethereum library contract WonkaEngineMetadata { using WonkaLibrary for *; address public rulesMaster; uint public attrCounter; // The Attributes known by this instance of the rules engine mapping(bytes32 => WonkaLibrary.WonkaAttr) private attrMap; WonkaLibrary.WonkaAttr[] public attributes; // The cache of records that are owned by "rulers" and that are validated when invoking a rule tree mapping(address => mapping(bytes32 => string)) currentRecords; /// @dev Constructor for the rules engine /// @notice Currently, the engine will create three dummy Attributes within the cache by default, but they will be removed later constructor() { attributes.push(WonkaLibrary.WonkaAttr({ attrId: 1, attrName: "Title", maxLength: 256, maxLengthTruncate: true, maxNumValue: 0, defaultValue: "", isString: true, isDecimal: false, isNumeric: false, isValue: true })); attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1]; attributes.push(WonkaLibrary.WonkaAttr({ attrId: 2, attrName: "Price", maxLength: 128, maxLengthTruncate: false, maxNumValue: 1000000, defaultValue: "", isString: false, isDecimal: false, isNumeric: true, isValue: true })); attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1]; attributes.push(WonkaLibrary.WonkaAttr({ attrId: 3, attrName: "PageAmount", maxLength: 256, maxLengthTruncate: false, maxNumValue: 1000, defaultValue: "", isString: false, isDecimal: false, isNumeric: true, isValue: true })); attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1]; attrCounter = 4; } modifier onlyEngineOwner() { // NOTE: Should be altered later // require(msg.sender == rulesMaster, "No exec perm"); // Do not forget the "_;"! It will // be replaced by the actual function // body when the modifier is used. _; } /// @dev This method will add a new Attribute to the cache. By adding Attributes, we expand the set of possible values that can be held by a record. /// @notice function addAttribute(bytes32 pAttrName, uint pMaxLen, uint pMaxNumVal, string memory pDefVal, bool pIsStr, bool pIsNum) public onlyEngineOwner { attributes.push(WonkaLibrary.WonkaAttr({ attrId: attrCounter++, attrName: pAttrName, maxLength: pMaxLen, maxLengthTruncate: (pMaxLen > 0), maxNumValue: pMaxNumVal, defaultValue: pDefVal, isString: pIsStr, isDecimal: false, isNumeric: pIsNum, isValue: true })); attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1]; } /// @dev This method will return the Attribute struct (if one has been provided) /// @notice function getAttribute(bytes32 pAttrName) public view returns(WonkaLibrary.WonkaAttr memory _attr) { return attrMap[pAttrName]; } /// @dev This method will return the current number of Attributes in the cache /// @notice This method should only be used for debugging purposes. function getNumberOfAttributes() public view returns(uint) { return attributes.length; } }
@title An Ethereum contract that contains the metadata for a rules engine @author Aaron Kendall @notice 1.) Certain steps are required in order to use this engine correctly + 2.) Deployment of this contract to a blockchain is expensive (~8000000 gas) + 3.) Various require() statements are commented out to save deployment costs @dev Even though you can create rule trees by calling this contract directly, it is generally recommended that you create them using the Nethereum library The Attributes known by this instance of the rules engine The cache of records that are owned by "rulers" and that are validated when invoking a rule tree
contract WonkaEngineMetadata { using WonkaLibrary for *; address public rulesMaster; uint public attrCounter; mapping(bytes32 => WonkaLibrary.WonkaAttr) private attrMap; WonkaLibrary.WonkaAttr[] public attributes; mapping(address => mapping(bytes32 => string)) currentRecords; pragma solidity ^0.7.6; constructor() { attributes.push(WonkaLibrary.WonkaAttr({ attrId: 1, attrName: "Title", maxLength: 256, maxLengthTruncate: true, maxNumValue: 0, defaultValue: "", isString: true, isDecimal: false, isNumeric: false, isValue: true })); attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1]; attributes.push(WonkaLibrary.WonkaAttr({ attrId: 2, attrName: "Price", maxLength: 128, maxLengthTruncate: false, maxNumValue: 1000000, defaultValue: "", isString: false, isDecimal: false, isNumeric: true, isValue: true })); attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1]; attributes.push(WonkaLibrary.WonkaAttr({ attrId: 3, attrName: "PageAmount", maxLength: 256, maxLengthTruncate: false, maxNumValue: 1000, defaultValue: "", isString: false, isDecimal: false, isNumeric: true, isValue: true })); attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1]; attrCounter = 4; } constructor() { attributes.push(WonkaLibrary.WonkaAttr({ attrId: 1, attrName: "Title", maxLength: 256, maxLengthTruncate: true, maxNumValue: 0, defaultValue: "", isString: true, isDecimal: false, isNumeric: false, isValue: true })); attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1]; attributes.push(WonkaLibrary.WonkaAttr({ attrId: 2, attrName: "Price", maxLength: 128, maxLengthTruncate: false, maxNumValue: 1000000, defaultValue: "", isString: false, isDecimal: false, isNumeric: true, isValue: true })); attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1]; attributes.push(WonkaLibrary.WonkaAttr({ attrId: 3, attrName: "PageAmount", maxLength: 256, maxLengthTruncate: false, maxNumValue: 1000, defaultValue: "", isString: false, isDecimal: false, isNumeric: true, isValue: true })); attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1]; attrCounter = 4; } constructor() { attributes.push(WonkaLibrary.WonkaAttr({ attrId: 1, attrName: "Title", maxLength: 256, maxLengthTruncate: true, maxNumValue: 0, defaultValue: "", isString: true, isDecimal: false, isNumeric: false, isValue: true })); attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1]; attributes.push(WonkaLibrary.WonkaAttr({ attrId: 2, attrName: "Price", maxLength: 128, maxLengthTruncate: false, maxNumValue: 1000000, defaultValue: "", isString: false, isDecimal: false, isNumeric: true, isValue: true })); attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1]; attributes.push(WonkaLibrary.WonkaAttr({ attrId: 3, attrName: "PageAmount", maxLength: 256, maxLengthTruncate: false, maxNumValue: 1000, defaultValue: "", isString: false, isDecimal: false, isNumeric: true, isValue: true })); attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1]; attrCounter = 4; } constructor() { attributes.push(WonkaLibrary.WonkaAttr({ attrId: 1, attrName: "Title", maxLength: 256, maxLengthTruncate: true, maxNumValue: 0, defaultValue: "", isString: true, isDecimal: false, isNumeric: false, isValue: true })); attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1]; attributes.push(WonkaLibrary.WonkaAttr({ attrId: 2, attrName: "Price", maxLength: 128, maxLengthTruncate: false, maxNumValue: 1000000, defaultValue: "", isString: false, isDecimal: false, isNumeric: true, isValue: true })); attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1]; attributes.push(WonkaLibrary.WonkaAttr({ attrId: 3, attrName: "PageAmount", maxLength: 256, maxLengthTruncate: false, maxNumValue: 1000, defaultValue: "", isString: false, isDecimal: false, isNumeric: true, isValue: true })); attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1]; attrCounter = 4; } modifier onlyEngineOwner() { _; } function addAttribute(bytes32 pAttrName, uint pMaxLen, uint pMaxNumVal, string memory pDefVal, bool pIsStr, bool pIsNum) public onlyEngineOwner { attributes.push(WonkaLibrary.WonkaAttr({ attrId: attrCounter++, attrName: pAttrName, maxLength: pMaxLen, maxLengthTruncate: (pMaxLen > 0), maxNumValue: pMaxNumVal, defaultValue: pDefVal, isString: pIsStr, isDecimal: false, isNumeric: pIsNum, isValue: true })); attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1]; } function addAttribute(bytes32 pAttrName, uint pMaxLen, uint pMaxNumVal, string memory pDefVal, bool pIsStr, bool pIsNum) public onlyEngineOwner { attributes.push(WonkaLibrary.WonkaAttr({ attrId: attrCounter++, attrName: pAttrName, maxLength: pMaxLen, maxLengthTruncate: (pMaxLen > 0), maxNumValue: pMaxNumVal, defaultValue: pDefVal, isString: pIsStr, isDecimal: false, isNumeric: pIsNum, isValue: true })); attrMap[attributes[attributes.length-1].attrName] = attributes[attributes.length-1]; } function getAttribute(bytes32 pAttrName) public view returns(WonkaLibrary.WonkaAttr memory _attr) { return attrMap[pAttrName]; } function getNumberOfAttributes() public view returns(uint) { return attributes.length; } }
977,392
[ 1, 979, 512, 18664, 379, 6835, 716, 1914, 326, 1982, 364, 279, 2931, 4073, 225, 432, 297, 265, 1475, 409, 454, 225, 404, 12998, 11921, 530, 6075, 854, 1931, 316, 1353, 358, 999, 333, 4073, 8783, 397, 576, 12998, 8587, 434, 333, 6835, 358, 279, 16766, 353, 19326, 261, 98, 28, 9449, 16189, 13, 397, 890, 12998, 11487, 1481, 2583, 1435, 6317, 854, 31813, 596, 358, 1923, 6314, 22793, 225, 25067, 11376, 1846, 848, 752, 1720, 11491, 635, 4440, 333, 6835, 5122, 16, 518, 353, 19190, 14553, 716, 1846, 752, 2182, 1450, 326, 423, 546, 822, 379, 5313, 1021, 9055, 4846, 635, 333, 791, 434, 326, 2931, 4073, 1021, 1247, 434, 3853, 716, 854, 16199, 635, 315, 86, 332, 414, 6, 471, 716, 854, 10266, 1347, 15387, 279, 1720, 2151, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 678, 265, 7282, 4410, 2277, 288, 203, 203, 565, 1450, 678, 265, 7282, 9313, 364, 380, 31, 203, 203, 565, 1758, 1071, 2931, 7786, 31, 203, 203, 565, 2254, 565, 1071, 1604, 4789, 31, 203, 203, 565, 2874, 12, 3890, 1578, 516, 678, 265, 7282, 9313, 18, 59, 265, 7282, 3843, 13, 3238, 1604, 863, 31, 377, 203, 565, 678, 265, 7282, 9313, 18, 59, 265, 7282, 3843, 8526, 1071, 1677, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 3890, 1578, 516, 533, 3719, 783, 6499, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 27, 18, 26, 31, 203, 565, 3885, 1435, 288, 203, 203, 3639, 1677, 18, 6206, 12, 59, 265, 7282, 9313, 18, 59, 265, 7282, 3843, 12590, 203, 5411, 1604, 548, 30, 404, 16, 203, 5411, 11583, 30, 315, 4247, 3113, 203, 5411, 13642, 30, 8303, 16, 203, 5411, 13642, 25871, 30, 638, 16, 203, 5411, 943, 2578, 620, 30, 374, 16, 203, 5411, 4593, 30, 23453, 203, 5411, 9962, 30, 638, 16, 203, 5411, 353, 5749, 30, 629, 16, 203, 5411, 26434, 30, 629, 16, 203, 5411, 21578, 30, 638, 1171, 203, 3639, 289, 10019, 203, 203, 3639, 1604, 863, 63, 4350, 63, 4350, 18, 2469, 17, 21, 8009, 1747, 461, 65, 273, 1677, 63, 4350, 18, 2469, 17, 21, 15533, 203, 203, 3639, 1677, 18, 6206, 12, 59, 265, 7282, 9313, 18, 59, 265, 7282, 3843, 12590, 203, 5411, 1604, 548, 30, 576, 16, 203, 5411, 11583, 30, 315, 5147, 3113, 203, 5411, 13642, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-05-21 */ // File: contracts/api/BuilderMasterAPI.sol abstract contract BuilderMasterAPI { function getContractId(uint tokenId) public view virtual returns (uint); function getNiftyTypeId(uint tokenId) public view virtual returns (uint); function getSpecificNiftyNum(uint tokenId) public view virtual returns (uint); function encodeTokenId(uint contractId, uint niftyType, uint specificNiftyNum) public view virtual returns (uint); function strConcat(string memory _a, string memory _b) public view virtual returns (string memory); function uint2str(uint _i) public view virtual returns (string memory _uintAsString); } // File: contracts/interface/IERC165.sol /** * @title IERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * @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. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: contracts/interface/IERC721.sol /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: contracts/interface/IERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: contracts/interface/IERC721Metadata.sol /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: contracts/util/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/util/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/util/Strings.sol /** * @dev String operations. */ library Strings { 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); } } // File: contracts/ERC165.sol /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: contracts/api/NiftyRegistryAPI.sol abstract contract NiftyRegistryAPI { function isValidNiftySender(address sending_key) public view virtual returns (bool); function isOwner(address owner_key) public view virtual returns (bool); } // File: contracts/NiftyEntity.sol contract NiftyEntity { // 0xCA9fC51835DBB525BB6E6ebfcc67b8bE1b08BDfA address public immutable masterBuilderContract; // 0x33F8cb717384A96C2a5de7964d0c7c1a10777660 address immutable niftyRegistryContract; modifier onlyValidSender() { NiftyRegistryAPI nftg_registry = NiftyRegistryAPI(niftyRegistryContract); bool is_valid = nftg_registry.isValidNiftySender(msg.sender); require(is_valid, "NiftyEntity: Invalid msg.sender"); _; } constructor(address _masterBuilderContract, address _niftyRegistryContract) { masterBuilderContract = _masterBuilderContract; niftyRegistryContract = _niftyRegistryContract; } } // File: contracts/ERC721.sol /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is NiftyEntity, Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; //Optional mapping for IPFS link to canonical image file mapping(uint256 => string) private _tokenIPFSHashes; mapping(uint256 => string) private _niftyTypeName; // Optional mapping for IPFS link to canonical image file by Nifty type mapping(uint256 => string) private _niftyTypeIPFSHashes; mapping(uint256 => string) private _tokenName; // 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_, address masterBuilderContract_, address niftyRegistryContract_) NiftyEntity(masterBuilderContract_, niftyRegistryContract_) { _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 Returns an URI for a given token ID. * 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) external view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); BuilderMasterAPI bm = BuilderMasterAPI(masterBuilderContract); string memory tokenIdStr = Strings.toString(tokenId); string memory tokenURIStr = bm.strConcat(_baseURI(), tokenIdStr); return tokenURIStr; } /** * @dev Returns an IPFS hash for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenIPFSHash(uint256 tokenId) external view virtual returns (string memory) {} /** * @dev Returns the Name for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenName(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: Name query for nonexistent token"); BuilderMasterAPI bm = BuilderMasterAPI(masterBuilderContract); uint nifty_type = bm.getNiftyTypeId(tokenId); return _niftyTypeName[nifty_type]; } /** * @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), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = uri; } /** * @dev Internal function to set the token IPFS hash for a nifty type. * @param nifty_type uint256 ID component of the token to set its IPFS hash * @param ipfs_hash string IPFS link to assign */ function _setTokenIPFSHashNiftyType(uint256 nifty_type, string memory ipfs_hash) internal { require(bytes(_niftyTypeIPFSHashes[nifty_type]).length == 0, "ERC721Metadata: IPFS hash already set"); _niftyTypeIPFSHashes[nifty_type] = ipfs_hash; } /** * @dev Internal function to set the name for a nifty type. * @param nifty_type uint256 of nifty type name to be set * @param nifty_type_name name of nifty type */ function _setNiftyTypeName(uint256 nifty_type, string memory nifty_type_name) internal { _niftyTypeName[nifty_type] = nifty_type_name; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) {} /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(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` 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: contracts/util/Counters.sol /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ 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; } } } // File: contracts/ERC721Burnable.sol /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ abstract contract ERC721Burnable is Context, ERC721 { /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } } // File: contracts/interface/IERC721Enumerable.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); } // File: contracts/ERC721Enumerable.sol /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: contracts/api/DateTimeAPI.sol /** * Abstract contract for interfacing with the DateTime contract. */ abstract contract DateTimeAPI { function isLeapYear(uint16 year) public view virtual returns (bool); function getYear(uint timestamp) public view virtual returns (uint16); function getMonth(uint timestamp) public view virtual returns (uint8); function getDay(uint timestamp) public view virtual returns (uint8); function getHour(uint timestamp) public view virtual returns (uint8); function getMinute(uint timestamp) public view virtual returns (uint8); function getSecond(uint timestamp) public view virtual returns (uint8); function getWeekday(uint timestamp) public view virtual returns (uint8); function toTimestamp(uint16 year, uint8 month, uint8 day) public view virtual returns (uint timestamp); function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour) public view virtual returns (uint timestamp); function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute) public view virtual returns (uint timestamp); function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute, uint8 second) public view virtual returns (uint timestamp); } // File: contracts/NiftyBuilderInstance.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; contract NiftyBuilderInstance is ERC721, ERC721Burnable, ERC721Enumerable { using Counters for Counters.Counter; string private _baseTokenURI; string public creator; string[12] artifact = ["QmQdb77jfHZSwk8dGpN3mqx8q4N7EUNytiAgEkXrMPbMVw", //State 1 "QmS3kaQnxb28vcXQg35PrGarJKkSysttZdNLdZp3JquttQ", //State 2 "QmX8beRtZAsed6naFWqddKejV33NoXotqZoGTuDaV5SHqN", //State 3 "QmQvsAMYzJm8kGQ7YNF5ziWUb6hr7vqdmkrn1qEPDykYi4", //State 4 "QmZwHt9ZhCgVMqpcFDhwKSA3higVYQXzyaPqh2BPjjXJXU", //State 5 "Qmd2MNfgzPYXGMS1ZgdsiWuAkriRRx15pfRXU7ZVK22jce", //State 6 "QmWcYzNdUYbMzrM7bGgTZXVE4GBm7v4dQneKb9fxgjMdAX", //State 7 "QmaXX7VuBY1dCeK78TTGEvYLTF76sf6fnzK7TJSni4PHxj", //State 8 "QmaqeJnzF2cAdfDrYRAw6VwzNn9dY9bKTyUuTHg1gUSQY7", //State 9 "QmSZquD6yGy5QvsJnygXUnWKrsKJvk942L8nzs6YZFKbxY", //State 10 "QmYtdrfPd3jAWWpjkd24NzLGqH5TDsHNvB8Qtqu6xnBcJF", //State 11 "QmesagGNeyjDvJ2N5oc8ykBiwsiE7gdk9vnfjjAe3ipjx4"];//State 12 address private dateTimeContract; uint immutable public id; uint immutable public countType; uint immutable private niftyType; mapping (uint => uint) public _numNiftyPermitted; mapping (uint => Counters.Counter) public _numNiftyMinted; event NiftyCreated(address new_owner, uint _niftyType, uint _tokenId); event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed fromAddress, address indexed toAddress); constructor(address _dateTimeContract, address _masterBuilderContract, address _niftyRegistryContract) ERC721("Eroding and Reforming Bust of Rome (One Year) by Daniel Arsham", "ROME", _masterBuilderContract, _niftyRegistryContract) { id = 1; niftyType = 1; countType = 1; creator = "Daniel Arsham"; dateTimeContract = _dateTimeContract; _setNiftyTypeName(1, "Eroding and Reforming Bust of Rome (One Year) by Daniel Arsham"); _setBaseURIParent("https://api.niftygateway.com/danielarsham/"); } /** * Configurable address for DateTime. */ function setDateTimeContract(address _dateTimeContract) onlyValidSender public { dateTimeContract = _dateTimeContract; } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } function _setBaseURIParent(string memory newBaseURI) internal { _baseTokenURI = newBaseURI; } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } /** * This functions as the inverse of closeContract(). */ function setNumNiftyPermitted(uint256 num_nifty_permitted) onlyValidSender public { require(_numNiftyPermitted[niftyType] == 0, "NiftyBuilderInstance: Permitted number already set for this NFT"); require(num_nifty_permitted < 9999 && num_nifty_permitted != 0, "NiftyBuilderInstance: Illegal argument"); _numNiftyPermitted[niftyType] = num_nifty_permitted; } /** * Allow owner to change nifty name. */ function setNiftyName(string memory nifty_name) onlyValidSender public { _setNiftyTypeName(niftyType, nifty_name); } function isGiftNiftyPermitted() internal view returns (bool) { if (_numNiftyMinted[niftyType].current() >= _numNiftyPermitted[niftyType]) { return false; } return true; } function giftNifty(address collector_address) onlyValidSender public { require(isGiftNiftyPermitted() == true, "NiftyBuilderInstance: Nifty sold out!"); BuilderMasterAPI bm = BuilderMasterAPI(masterBuilderContract); _numNiftyMinted[niftyType].increment(); uint specificTokenId = _numNiftyMinted[niftyType].current(); uint tokenId = bm.encodeTokenId(id, niftyType, specificTokenId); _mint(collector_address, tokenId); emit NiftyCreated(collector_address, niftyType, tokenId); } /** * Loop through array and create nifties. */ function massMintNFTs(address collector_address, uint num_to_mint) onlyValidSender public { BuilderMasterAPI bm = BuilderMasterAPI(masterBuilderContract); uint specificTokenId00 = _numNiftyMinted[niftyType].current() + 1; uint tokenId00 = bm.encodeTokenId(id, niftyType, specificTokenId00); for (uint i = 0; i < num_to_mint; i++) { giftNifty(collector_address); } uint specificTokenId01 = _numNiftyMinted[niftyType].current(); uint tokenId01 = bm.encodeTokenId(id, niftyType, specificTokenId01); emit ConsecutiveTransfer(tokenId00, tokenId01, address(0), collector_address); } function tokenIPFSHash(uint256 tokenId) external view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: IPFS hash query for nonexistent token"); DateTimeAPI dateTime = DateTimeAPI(dateTimeContract); uint value = dateTime.getMonth(block.timestamp); if (value == 1) { return artifact[0]; } if (value == 2) { return artifact[1]; } if (value == 3) { return artifact[2]; } if (value == 4) { return artifact[3]; } if (value == 5) { return artifact[4]; } if (value == 6) { return artifact[5]; } if (value == 7) { return artifact[6]; } if (value == 8) { return artifact[7]; } if (value == 9) { return artifact[8]; } if (value == 10) { return artifact[9]; } if (value == 11) { return artifact[10]; } return artifact[11]; } }
* Configurable address for DateTime./
function setDateTimeContract(address _dateTimeContract) onlyValidSender public { dateTimeContract = _dateTimeContract; }
10,635,487
[ 1, 31660, 1758, 364, 3716, 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, 565, 445, 444, 5096, 8924, 12, 2867, 389, 712, 950, 8924, 13, 1338, 1556, 12021, 1071, 288, 203, 3639, 9296, 8924, 273, 389, 712, 950, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: contracts/GodMode.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title God Mode /// @author Anthony Burzillo <[email protected]> /// @dev This contract provides a basic interface for God /// in a contract as well as the ability for God to pause /// the contract contract GodMode { /// @dev Is the contract paused? bool public isPaused; /// @dev God's address address public god; /// @dev Only God can run this function modifier onlyGod() { require(god == msg.sender); _; } /// @dev This function can only be run while the contract /// is not paused modifier notPaused() { require(!isPaused); _; } /// @dev This event is fired when the contract is paused event GodPaused(); /// @dev This event is fired when the contract is unpaused event GodUnpaused(); constructor() public { // Make the creator of the contract God god = msg.sender; } /// @dev God can change the address of God /// @param _newGod The new address for God function godChangeGod(address _newGod) public onlyGod { god = _newGod; } /// @dev God can pause the game function godPause() public onlyGod { isPaused = true; emit GodPaused(); } /// @dev God can unpause the game function godUnpause() public onlyGod { isPaused = false; emit GodUnpaused(); } } // File: contracts/KingOfEthAbstractInterface.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title King of Eth Abstract Interface /// @author Anthony Burzillo <[email protected]> /// @dev Abstract interface contract for titles and taxes contract KingOfEthAbstractInterface { /// @dev The address of the current King address public king; /// @dev The address of the current Wayfarer address public wayfarer; /// @dev Anyone can pay taxes function payTaxes() public payable; } // File: contracts/KingOfEthBlindAuctionsReferencer.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title King of Eth: Blind Auctions Referencer /// @author Anthony Burzillo <[email protected]> /// @dev This contract provides a reference to the blind auctions contract contract KingOfEthBlindAuctionsReferencer is GodMode { /// @dev The address of the blind auctions contract address public blindAuctionsContract; /// @dev Only the blind auctions contract can run this modifier onlyBlindAuctionsContract() { require(blindAuctionsContract == msg.sender); _; } /// @dev God can set a new blind auctions contract /// @param _blindAuctionsContract the address of the blind auctions /// contract function godSetBlindAuctionsContract(address _blindAuctionsContract) public onlyGod { blindAuctionsContract = _blindAuctionsContract; } } // File: contracts/KingOfEthOpenAuctionsReferencer.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title King of Eth: Open Auctions Referencer /// @author Anthony Burzillo <[email protected]> /// @dev This contract provides a reference to the open auctions contract contract KingOfEthOpenAuctionsReferencer is GodMode { /// @dev The address of the auctions contract address public openAuctionsContract; /// @dev Only the open auctions contract can run this modifier onlyOpenAuctionsContract() { require(openAuctionsContract == msg.sender); _; } /// @dev God can set a new auctions contract function godSetOpenAuctionsContract(address _openAuctionsContract) public onlyGod { openAuctionsContract = _openAuctionsContract; } } // File: contracts/KingOfEthAuctionsReferencer.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title King of Eth: Auctions Referencer /// @author Anthony Burzillo <[email protected]> /// @dev This contract provides a reference to the auctions contracts contract KingOfEthAuctionsReferencer is KingOfEthBlindAuctionsReferencer , KingOfEthOpenAuctionsReferencer { /// @dev Only an auctions contract can run this modifier onlyAuctionsContract() { require(blindAuctionsContract == msg.sender || openAuctionsContract == msg.sender); _; } } // File: contracts/KingOfEthReferencer.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title King of Eth Referencer /// @author Anthony Burzillo <[email protected]> /// @dev Functionality to allow contracts to reference the king contract contract KingOfEthReferencer is GodMode { /// @dev The address of the king contract address public kingOfEthContract; /// @dev Only the king contract can run this modifier onlyKingOfEthContract() { require(kingOfEthContract == msg.sender); _; } /// @dev God can change the king contract /// @param _kingOfEthContract The new address function godSetKingOfEthContract(address _kingOfEthContract) public onlyGod { kingOfEthContract = _kingOfEthContract; } } // File: contracts/KingOfEthBoard.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title King of Eth: Board /// @author Anthony Burzillo <[email protected]> /// @dev Contract for board contract KingOfEthBoard is GodMode , KingOfEthAuctionsReferencer , KingOfEthReferencer { /// @dev x coordinate of the top left corner of the boundary uint public boundX1 = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffef; /// @dev y coordinate of the top left corner of the boundary uint public boundY1 = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffef; /// @dev x coordinate of the bottom right corner of the boundary uint public boundX2 = 0x800000000000000000000000000000000000000000000000000000000000000f; /// @dev y coordinate of the bottom right corner of the boundary uint public boundY2 = 0x800000000000000000000000000000000000000000000000000000000000000f; /// @dev Number used to divide the total number of house locations /// after any expansion to yield the number of auctions that will be /// available to start for the expansion's duration uint public constant auctionsAvailableDivisor = 10; /// @dev Amount of time the King must wait between increasing the board uint public constant kingTimeBetweenIncrease = 2 weeks; /// @dev Amount of time the Wayfarer must wait between increasing the board uint public constant wayfarerTimeBetweenIncrease = 3 weeks; /// @dev Amount of time that anyone but the King or Wayfarer must wait /// before increasing the board uint public constant plebTimeBetweenIncrease = 4 weeks; /// @dev The last time the board was increased in size uint public lastIncreaseTime; /// @dev The direction of the next increase uint8 public nextIncreaseDirection; /// @dev The number of auctions that players may choose to start /// for this expansion uint public auctionsRemaining; constructor() public { // Game is paused as God must start it isPaused = true; // Set the auctions remaining setAuctionsAvailableForBounds(); } /// @dev Fired when the board is increased in size event BoardSizeIncreased( address initiator , uint newBoundX1 , uint newBoundY1 , uint newBoundX2 , uint newBoundY2 , uint lastIncreaseTime , uint nextIncreaseDirection , uint auctionsRemaining ); /// @dev Only the King can run this modifier onlyKing() { require(KingOfEthAbstractInterface(kingOfEthContract).king() == msg.sender); _; } /// @dev Only the Wayfarer can run this modifier onlyWayfarer() { require(KingOfEthAbstractInterface(kingOfEthContract).wayfarer() == msg.sender); _; } /// @dev Set the total auctions available function setAuctionsAvailableForBounds() private { uint boundDiffX = boundX2 - boundX1; uint boundDiffY = boundY2 - boundY1; auctionsRemaining = boundDiffX * boundDiffY / 2 / auctionsAvailableDivisor; } /// @dev Increase the board's size making sure to keep steady at /// the maximum outer bounds function increaseBoard() private { // The length of increase uint _increaseLength; // If this increase direction is right if(0 == nextIncreaseDirection) { _increaseLength = boundX2 - boundX1; uint _updatedX2 = boundX2 + _increaseLength; // Stay within bounds if(_updatedX2 <= boundX2 || _updatedX2 <= _increaseLength) { boundX2 = ~uint(0); } else { boundX2 = _updatedX2; } } // If this increase direction is down else if(1 == nextIncreaseDirection) { _increaseLength = boundY2 - boundY1; uint _updatedY2 = boundY2 + _increaseLength; // Stay within bounds if(_updatedY2 <= boundY2 || _updatedY2 <= _increaseLength) { boundY2 = ~uint(0); } else { boundY2 = _updatedY2; } } // If this increase direction is left else if(2 == nextIncreaseDirection) { _increaseLength = boundX2 - boundX1; // Stay within bounds if(boundX1 <= _increaseLength) { boundX1 = 0; } else { boundX1 -= _increaseLength; } } // If this increase direction is up else if(3 == nextIncreaseDirection) { _increaseLength = boundY2 - boundY1; // Stay within bounds if(boundY1 <= _increaseLength) { boundY1 = 0; } else { boundY1 -= _increaseLength; } } // The last increase time is now lastIncreaseTime = now; // Set the next increase direction nextIncreaseDirection = (nextIncreaseDirection + 1) % 4; // Reset the auctions available setAuctionsAvailableForBounds(); emit BoardSizeIncreased( msg.sender , boundX1 , boundY1 , boundX2 , boundY2 , now , nextIncreaseDirection , auctionsRemaining ); } /// @dev God can start the game function godStartGame() public onlyGod { // Reset increase times lastIncreaseTime = now; // Unpause the game godUnpause(); } /// @dev The auctions contracts can decrement the number /// of auctions that are available to be started function auctionsDecrementAuctionsRemaining() public onlyAuctionsContract { auctionsRemaining -= 1; } /// @dev The auctions contracts can increment the number /// of auctions that are available to be started when /// an auction ends wihout a winner function auctionsIncrementAuctionsRemaining() public onlyAuctionsContract { auctionsRemaining += 1; } /// @dev The King can increase the board much faster than the plebs function kingIncreaseBoard() public onlyKing { // Require enough time has passed since the last increase require(lastIncreaseTime + kingTimeBetweenIncrease < now); increaseBoard(); } /// @dev The Wayfarer can increase the board faster than the plebs function wayfarerIncreaseBoard() public onlyWayfarer { // Require enough time has passed since the last increase require(lastIncreaseTime + wayfarerTimeBetweenIncrease < now); increaseBoard(); } /// @dev Any old pleb can increase the board function plebIncreaseBoard() public { // Require enough time has passed since the last increase require(lastIncreaseTime + plebTimeBetweenIncrease < now); increaseBoard(); } } // File: contracts/KingOfEthBoardReferencer.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title King of Eth: Board Referencer /// @author Anthony Burzillo <[email protected]> /// @dev Functionality to allow contracts to reference the board contract contract KingOfEthBoardReferencer is GodMode { /// @dev The address of the board contract address public boardContract; /// @dev Only the board contract can run this modifier onlyBoardContract() { require(boardContract == msg.sender); _; } /// @dev God can change the board contract /// @param _boardContract The new address function godSetBoardContract(address _boardContract) public onlyGod { boardContract = _boardContract; } } // File: contracts/KingOfEthHousesAbstractInterface.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title King of Eth: Houses Abstract Interface /// @author Anthony Burzillo <[email protected]> /// @dev Abstract interface contract for houses contract KingOfEthHousesAbstractInterface { /// @dev Get the owner of the house at some location /// @param _x The x coordinate of the house /// @param _y The y coordinate of the house /// @return The address of the owner function ownerOf(uint _x, uint _y) public view returns(address); /// @dev Get the level of the house at some location /// @param _x The x coordinate of the house /// @param _y The y coordinate of the house /// @return The level of the house function level(uint _x, uint _y) public view returns(uint8); /// @dev The auctions contracts can set the owner of a house after an auction /// @param _x The x coordinate of the house /// @param _y The y coordinate of the house /// @param _owner The new owner of the house function auctionsSetOwner(uint _x, uint _y, address _owner) public; /// @dev The house realty contract can transfer house ownership /// @param _x The x coordinate of the house /// @param _y The y coordinate of the house /// @param _from The previous owner of house /// @param _to The new owner of house function houseRealtyTransferOwnership( uint _x , uint _y , address _from , address _to ) public; } // File: contracts/KingOfEthHousesReferencer.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title King of Eth: Houses Referencer /// @author Anthony Burzillo <[email protected]> /// @dev Provides functionality to reference the houses contract contract KingOfEthHousesReferencer is GodMode { /// @dev The houses contract's address address public housesContract; /// @dev Only the houses contract can run this function modifier onlyHousesContract() { require(housesContract == msg.sender); _; } /// @dev God can set the realty contract /// @param _housesContract The new address function godSetHousesContract(address _housesContract) public onlyGod { housesContract = _housesContract; } } // File: contracts/KingOfEthEthExchangeReferencer.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title King of Eth: Resource-to-ETH Exchange Referencer /// @author Anthony Burzillo <[email protected]> /// @dev Provides functionality to interface with the /// ETH exchange contract contract KingOfEthEthExchangeReferencer is GodMode { /// @dev Address of the ETH exchange contract address public ethExchangeContract; /// @dev Only the ETH exchange contract may run this function modifier onlyEthExchangeContract() { require(ethExchangeContract == msg.sender); _; } /// @dev God may set the ETH exchange contract's address /// @dev _ethExchangeContract The new address function godSetEthExchangeContract(address _ethExchangeContract) public onlyGod { ethExchangeContract = _ethExchangeContract; } } // File: contracts/KingOfEthResourceExchangeReferencer.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title King of Eth: Resource-to-Resource Exchange Referencer /// @author Anthony Burzillo <[email protected]> /// @dev Provides functionality to interface with the /// resource-to-resource contract contract KingOfEthResourceExchangeReferencer is GodMode { /// @dev Address of the resource-to-resource contract address public resourceExchangeContract; /// @dev Only the resource-to-resource contract may run this function modifier onlyResourceExchangeContract() { require(resourceExchangeContract == msg.sender); _; } /// @dev God may set the resource-to-resource contract's address /// @dev _resourceExchangeContract The new address function godSetResourceExchangeContract(address _resourceExchangeContract) public onlyGod { resourceExchangeContract = _resourceExchangeContract; } } // File: contracts/KingOfEthExchangeReferencer.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title King of Eth: Exchange Referencer /// @author Anthony Burzillo <[email protected]> /// @dev Provides functionality to interface with the exchange contract contract KingOfEthExchangeReferencer is GodMode , KingOfEthEthExchangeReferencer , KingOfEthResourceExchangeReferencer { /// @dev Only one of the exchange contracts may /// run this function modifier onlyExchangeContract() { require( ethExchangeContract == msg.sender || resourceExchangeContract == msg.sender ); _; } } // File: contracts/KingOfEthResourcesInterfaceReferencer.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title King of Eth: Resources Interface Referencer /// @author Anthony Burzillo <[email protected]> /// @dev Provides functionality to reference the resource interface contract contract KingOfEthResourcesInterfaceReferencer is GodMode { /// @dev The interface contract's address address public interfaceContract; /// @dev Only the interface contract can run this function modifier onlyInterfaceContract() { require(interfaceContract == msg.sender); _; } /// @dev God can set the realty contract /// @param _interfaceContract The new address function godSetInterfaceContract(address _interfaceContract) public onlyGod { interfaceContract = _interfaceContract; } } // File: contracts/KingOfEthResource.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title ERC20Interface /// @dev ERC20 token interface contract contract ERC20Interface { 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); } /// @title King of Eth: Resource /// @author Anthony Burzillo <[email protected]> /// @dev Common contract implementation for resources contract KingOfEthResource is ERC20Interface , GodMode , KingOfEthResourcesInterfaceReferencer { /// @dev Current resource supply uint public resourceSupply; /// @dev ERC20 token's decimals uint8 public constant decimals = 0; /// @dev mapping of addresses to holdings mapping (address => uint) holdings; /// @dev mapping of addresses to amount of tokens frozen mapping (address => uint) frozenHoldings; /// @dev mapping of addresses to mapping of allowances for an address mapping (address => mapping (address => uint)) allowances; /// @dev ERC20 total supply /// @return The current total supply of the resource function totalSupply() public constant returns(uint) { return resourceSupply; } /// @dev ERC20 balance of address /// @param _tokenOwner The address to look up /// @return The balance of the address function balanceOf(address _tokenOwner) public constant returns(uint balance) { return holdings[_tokenOwner]; } /// @dev Total resources frozen for an address /// @param _tokenOwner The address to look up /// @return The frozen balance of the address function frozenTokens(address _tokenOwner) public constant returns(uint balance) { return frozenHoldings[_tokenOwner]; } /// @dev The allowance for a spender on an account /// @param _tokenOwner The account that allows withdrawels /// @param _spender The account that is allowed to withdraw /// @return The amount remaining in the allowance function allowance(address _tokenOwner, address _spender) public constant returns(uint remaining) { return allowances[_tokenOwner][_spender]; } /// @dev Only run if player has at least some amount of tokens /// @param _owner The owner of the tokens /// @param _tokens The amount of tokens required modifier hasAvailableTokens(address _owner, uint _tokens) { require(holdings[_owner] - frozenHoldings[_owner] >= _tokens); _; } /// @dev Only run if player has at least some amount of tokens frozen /// @param _owner The owner of the tokens /// @param _tokens The amount of frozen tokens required modifier hasFrozenTokens(address _owner, uint _tokens) { require(frozenHoldings[_owner] >= _tokens); _; } /// @dev Set up the exact same state in each resource constructor() public { // God gets 200 to put on exchange holdings[msg.sender] = 200; resourceSupply = 200; } /// @dev The resources interface can burn tokens for building /// roads or houses /// @param _owner The owner of the tokens /// @param _tokens The amount of tokens to burn function interfaceBurnTokens(address _owner, uint _tokens) public onlyInterfaceContract hasAvailableTokens(_owner, _tokens) { holdings[_owner] -= _tokens; resourceSupply -= _tokens; // Pretend the tokens were sent to 0x0 emit Transfer(_owner, 0x0, _tokens); } /// @dev The resources interface contract can mint tokens for houses /// @param _owner The owner of the tokens /// @param _tokens The amount of tokens to burn function interfaceMintTokens(address _owner, uint _tokens) public onlyInterfaceContract { holdings[_owner] += _tokens; resourceSupply += _tokens; // Pretend the tokens were sent from the interface contract emit Transfer(interfaceContract, _owner, _tokens); } /// @dev The interface can freeze tokens /// @param _owner The owner of the tokens /// @param _tokens The amount of tokens to freeze function interfaceFreezeTokens(address _owner, uint _tokens) public onlyInterfaceContract hasAvailableTokens(_owner, _tokens) { frozenHoldings[_owner] += _tokens; } /// @dev The interface can thaw tokens /// @param _owner The owner of the tokens /// @param _tokens The amount of tokens to thaw function interfaceThawTokens(address _owner, uint _tokens) public onlyInterfaceContract hasFrozenTokens(_owner, _tokens) { frozenHoldings[_owner] -= _tokens; } /// @dev The interface can transfer tokens /// @param _from The owner of the tokens /// @param _to The new owner of the tokens /// @param _tokens The amount of tokens to transfer function interfaceTransfer(address _from, address _to, uint _tokens) public onlyInterfaceContract { assert(holdings[_from] >= _tokens); holdings[_from] -= _tokens; holdings[_to] += _tokens; emit Transfer(_from, _to, _tokens); } /// @dev The interface can transfer frozend tokens /// @param _from The owner of the tokens /// @param _to The new owner of the tokens /// @param _tokens The amount of frozen tokens to transfer function interfaceFrozenTransfer(address _from, address _to, uint _tokens) public onlyInterfaceContract hasFrozenTokens(_from, _tokens) { // Make sure to deduct the tokens from both the total and frozen amounts holdings[_from] -= _tokens; frozenHoldings[_from] -= _tokens; holdings[_to] += _tokens; emit Transfer(_from, _to, _tokens); } /// @dev ERC20 transfer /// @param _to The address to transfer to /// @param _tokens The amount of tokens to transfer function transfer(address _to, uint _tokens) public hasAvailableTokens(msg.sender, _tokens) returns(bool success) { holdings[_to] += _tokens; holdings[msg.sender] -= _tokens; emit Transfer(msg.sender, _to, _tokens); return true; } /// @dev ERC20 approve /// @param _spender The address to approve /// @param _tokens The amount of tokens to approve function approve(address _spender, uint _tokens) public returns(bool success) { allowances[msg.sender][_spender] = _tokens; emit Approval(msg.sender, _spender, _tokens); return true; } /// @dev ERC20 transfer from /// @param _from The address providing the allowance /// @param _to The address using the allowance /// @param _tokens The amount of tokens to transfer function transferFrom(address _from, address _to, uint _tokens) public hasAvailableTokens(_from, _tokens) returns(bool success) { require(allowances[_from][_to] >= _tokens); holdings[_to] += _tokens; holdings[_from] -= _tokens; allowances[_from][_to] -= _tokens; emit Transfer(_from, _to, _tokens); return true; } } // File: contracts/KingOfEthResourceType.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title King of Eth: Resource Type /// @author Anthony Burzillo <[email protected]> /// @dev Provides enum to choose resource types contract KingOfEthResourceType { /// @dev Enum describing a choice of a resource enum ResourceType { ETH , BRONZE , CORN , GOLD , OIL , ORE , STEEL , URANIUM , WOOD } } // File: contracts/KingOfEthRoadsReferencer.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title King of Eth: Roads Referencer /// @author Anthony Burzillo <[email protected]> /// @dev Provides functionality to reference the roads contract contract KingOfEthRoadsReferencer is GodMode { /// @dev The roads contract's address address public roadsContract; /// @dev Only the roads contract can run this function modifier onlyRoadsContract() { require(roadsContract == msg.sender); _; } /// @dev God can set the realty contract /// @param _roadsContract The new address function godSetRoadsContract(address _roadsContract) public onlyGod { roadsContract = _roadsContract; } } // File: contracts/KingOfEthResourcesInterface.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title King of Eth: Resources Interface /// @author Anthony Burzillo <[email protected]> /// @dev Contract for interacting with resources contract KingOfEthResourcesInterface is GodMode , KingOfEthExchangeReferencer , KingOfEthHousesReferencer , KingOfEthResourceType , KingOfEthRoadsReferencer { /// @dev Amount of resources a user gets for building a house uint public constant resourcesPerHouse = 3; /// @dev Address for the bronze contract address public bronzeContract; /// @dev Address for the corn contract address public cornContract; /// @dev Address for the gold contract address public goldContract; /// @dev Address for the oil contract address public oilContract; /// @dev Address for the ore contract address public oreContract; /// @dev Address for the steel contract address public steelContract; /// @dev Address for the uranium contract address public uraniumContract; /// @dev Address for the wood contract address public woodContract; /// @param _bronzeContract The address of the bronze contract /// @param _cornContract The address of the corn contract /// @param _goldContract The address of the gold contract /// @param _oilContract The address of the oil contract /// @param _oreContract The address of the ore contract /// @param _steelContract The address of the steel contract /// @param _uraniumContract The address of the uranium contract /// @param _woodContract The address of the wood contract constructor( address _bronzeContract , address _cornContract , address _goldContract , address _oilContract , address _oreContract , address _steelContract , address _uraniumContract , address _woodContract ) public { bronzeContract = _bronzeContract; cornContract = _cornContract; goldContract = _goldContract; oilContract = _oilContract; oreContract = _oreContract; steelContract = _steelContract; uraniumContract = _uraniumContract; woodContract = _woodContract; } /// @dev Return the particular address for a certain resource type /// @param _type The resource type /// @return The address for that resource function contractFor(ResourceType _type) public view returns(address) { // ETH does not have a contract require(ResourceType.ETH != _type); if(ResourceType.BRONZE == _type) { return bronzeContract; } else if(ResourceType.CORN == _type) { return cornContract; } else if(ResourceType.GOLD == _type) { return goldContract; } else if(ResourceType.OIL == _type) { return oilContract; } else if(ResourceType.ORE == _type) { return oreContract; } else if(ResourceType.STEEL == _type) { return steelContract; } else if(ResourceType.URANIUM == _type) { return uraniumContract; } else if(ResourceType.WOOD == _type) { return woodContract; } } /// @dev Determine the resource type of a tile /// @param _x The x coordinate of the top left corner of the tile /// @param _y The y coordinate of the top left corner of the tile function resourceType(uint _x, uint _y) public pure returns(ResourceType resource) { uint _seed = (_x + 7777777) ^ _y; if(0 == _seed % 97) { return ResourceType.URANIUM; } else if(0 == _seed % 29) { return ResourceType.OIL; } else if(0 == _seed % 23) { return ResourceType.STEEL; } else if(0 == _seed % 17) { return ResourceType.GOLD; } else if(0 == _seed % 11) { return ResourceType.BRONZE; } else if(0 == _seed % 5) { return ResourceType.WOOD; } else if(0 == _seed % 2) { return ResourceType.CORN; } else { return ResourceType.ORE; } } /// @dev Lookup the number of resource points for a certain /// player /// @param _player The player in question function lookupResourcePoints(address _player) public view returns(uint) { uint result = 0; result += KingOfEthResource(bronzeContract).balanceOf(_player); result += KingOfEthResource(goldContract).balanceOf(_player) * 3; result += KingOfEthResource(steelContract).balanceOf(_player) * 6; result += KingOfEthResource(oilContract).balanceOf(_player) * 10; result += KingOfEthResource(uraniumContract).balanceOf(_player) * 44; return result; } /// @dev Burn the resources necessary to build a house /// @param _count the number of houses being built /// @param _player The player who is building the house function burnHouseCosts(uint _count, address _player) public onlyHousesContract { // Costs 2 corn per house KingOfEthResource(contractFor(ResourceType.CORN)).interfaceBurnTokens( _player , 2 * _count ); // Costs 2 ore per house KingOfEthResource(contractFor(ResourceType.ORE)).interfaceBurnTokens( _player , 2 * _count ); // Costs 1 wood per house KingOfEthResource(contractFor(ResourceType.WOOD)).interfaceBurnTokens( _player , _count ); } /// @dev Burn the costs of upgrading a house /// @param _currentLevel The level of the house before the upgrade /// @param _player The player who is upgrading the house function burnUpgradeCosts(uint8 _currentLevel, address _player) public onlyHousesContract { // Do not allow upgrades after level 4 require(5 > _currentLevel); // Burn the base house cost burnHouseCosts(1, _player); if(0 == _currentLevel) { // Level 1 costs bronze KingOfEthResource(contractFor(ResourceType.BRONZE)).interfaceBurnTokens( _player , 1 ); } else if(1 == _currentLevel) { // Level 2 costs gold KingOfEthResource(contractFor(ResourceType.GOLD)).interfaceBurnTokens( _player , 1 ); } else if(2 == _currentLevel) { // Level 3 costs steel KingOfEthResource(contractFor(ResourceType.STEEL)).interfaceBurnTokens( _player , 1 ); } else if(3 == _currentLevel) { // Level 4 costs oil KingOfEthResource(contractFor(ResourceType.OIL)).interfaceBurnTokens( _player , 1 ); } else if(4 == _currentLevel) { // Level 5 costs uranium KingOfEthResource(contractFor(ResourceType.URANIUM)).interfaceBurnTokens( _player , 1 ); } } /// @dev Mint resources for a house and distribute all to its owner /// @param _owner The owner of the house /// @param _x The x coordinate of the house /// @param _y The y coordinate of the house /// @param _y The y coordinate of the house /// @param _level The new level of the house function distributeResources(address _owner, uint _x, uint _y, uint8 _level) public onlyHousesContract { // Calculate the count of resources for this level uint _count = resourcesPerHouse * uint(_level + 1); // Distribute the top left resource KingOfEthResource(contractFor(resourceType(_x - 1, _y - 1))).interfaceMintTokens( _owner , _count ); // Distribute the top right resource KingOfEthResource(contractFor(resourceType(_x, _y - 1))).interfaceMintTokens( _owner , _count ); // Distribute the bottom right resource KingOfEthResource(contractFor(resourceType(_x, _y))).interfaceMintTokens( _owner , _count ); // Distribute the bottom left resource KingOfEthResource(contractFor(resourceType(_x - 1, _y))).interfaceMintTokens( _owner , _count ); } /// @dev Burn the costs necessary to build a road /// @param _length The length of the road /// @param _player The player who is building the house function burnRoadCosts(uint _length, address _player) public onlyRoadsContract { // Burn corn KingOfEthResource(cornContract).interfaceBurnTokens( _player , _length ); // Burn ore KingOfEthResource(oreContract).interfaceBurnTokens( _player , _length ); } /// @dev The exchange can freeze tokens /// @param _type The type of resource /// @param _owner The owner of the tokens /// @param _tokens The amount of tokens to freeze function exchangeFreezeTokens(ResourceType _type, address _owner, uint _tokens) public onlyExchangeContract { KingOfEthResource(contractFor(_type)).interfaceFreezeTokens(_owner, _tokens); } /// @dev The exchange can thaw tokens /// @param _type The type of resource /// @param _owner The owner of the tokens /// @param _tokens The amount of tokens to thaw function exchangeThawTokens(ResourceType _type, address _owner, uint _tokens) public onlyExchangeContract { KingOfEthResource(contractFor(_type)).interfaceThawTokens(_owner, _tokens); } /// @dev The exchange can transfer tokens /// @param _type The type of resource /// @param _from The owner of the tokens /// @param _to The new owner of the tokens /// @param _tokens The amount of tokens to transfer function exchangeTransfer(ResourceType _type, address _from, address _to, uint _tokens) public onlyExchangeContract { KingOfEthResource(contractFor(_type)).interfaceTransfer(_from, _to, _tokens); } /// @dev The exchange can transfer frozend tokens /// @param _type The type of resource /// @param _from The owner of the tokens /// @param _to The new owner of the tokens /// @param _tokens The amount of frozen tokens to transfer function exchangeFrozenTransfer(ResourceType _type, address _from, address _to, uint _tokens) public onlyExchangeContract { KingOfEthResource(contractFor(_type)).interfaceFrozenTransfer(_from, _to, _tokens); } } // File: contracts/KingOfEthRoadsAbstractInterface.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title King of Eth: Roads Abstract Interface /// @author Anthony Burzillo <[email protected]> /// @dev Abstract interface contract for roads contract KingOfEthRoadsAbstractInterface { /// @dev Get the owner of the road at some location /// @param _x The x coordinate of the road /// @param _y The y coordinate of the road /// @param _direction The direction of the road (either /// 0 for right or 1 for down) /// @return The address of the owner function ownerOf(uint _x, uint _y, uint8 _direction) public view returns(address); /// @dev The road realty contract can transfer road ownership /// @param _x The x coordinate of the road /// @param _y The y coordinate of the road /// @param _direction The direction of the road /// @param _from The previous owner of road /// @param _to The new owner of road function roadRealtyTransferOwnership( uint _x , uint _y , uint8 _direction , address _from , address _to ) public; } // File: contracts/KingOfEthRoadRealty.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title King of Eth: Road Realty /// @author Anthony Burzillo <[email protected]> /// @dev Contract for controlling sales of roads contract KingOfEthRoadRealty is GodMode , KingOfEthReferencer , KingOfEthRoadsReferencer { /// @dev The number that divides the amount payed for any sale to produce /// the amount payed in taxes uint public constant taxDivisor = 25; /// @dev Mapping from the x, y coordinates and the direction (0 for right and /// 1 for down) of a road to the current sale price (0 if there is no sale) mapping (uint => mapping (uint => uint[2])) roadPrices; /// @dev Fired when there is a new road for sale event RoadForSale( uint x , uint y , uint8 direction , address owner , uint amount ); /// @dev Fired when the owner changes the price of a road event RoadPriceChanged( uint x , uint y , uint8 direction , uint amount ); /// @dev Fired when a road is sold event RoadSold( uint x , uint y , uint8 direction , address from , address to , uint amount ); /// @dev Fired when the sale for a road is cancelled by the owner event RoadSaleCancelled( uint x , uint y , uint8 direction , address owner ); /// @dev Only the owner of the road at a location can run this /// @param _x The x coordinate of the road /// @param _y The y coordinate of the road /// @param _direction The direction of the road modifier onlyRoadOwner(uint _x, uint _y, uint8 _direction) { require(KingOfEthRoadsAbstractInterface(roadsContract).ownerOf(_x, _y, _direction) == msg.sender); _; } /// @dev This can only be run if there is *not* an existing sale for a road /// at a location /// @param _x The x coordinate of the road /// @param _y The y coordinate of the road /// @param _direction The direction of the road modifier noExistingRoadSale(uint _x, uint _y, uint8 _direction) { require(0 == roadPrices[_x][_y][_direction]); _; } /// @dev This can only be run if there is an existing sale for a house /// at a location /// @param _x The x coordinate of the road /// @param _y The y coordinate of the road /// @param _direction The direction of the road modifier existingRoadSale(uint _x, uint _y, uint8 _direction) { require(0 != roadPrices[_x][_y][_direction]); _; } /// @param _kingOfEthContract The address of the king contract constructor(address _kingOfEthContract) public { kingOfEthContract = _kingOfEthContract; } /// @dev The roads contract can cancel a sale when a road is transfered /// to another player /// @param _x The x coordinate of the road /// @param _y The y coordinate of the road /// @param _direction The direction of the road function roadsCancelRoadSale(uint _x, uint _y, uint8 _direction) public onlyRoadsContract { // If there is indeed a sale if(0 != roadPrices[_x][_y][_direction]) { // Cancel the sale roadPrices[_x][_y][_direction] = 0; emit RoadSaleCancelled(_x, _y, _direction, msg.sender); } } /// @dev The owner of a road can start a sale /// @param _x The x coordinate of the road /// @param _y The y coordinate of the road /// @param _direction The direction of the road /// @param _askingPrice The price that must be payed by another player /// to purchase the road function startRoadSale( uint _x , uint _y , uint8 _direction , uint _askingPrice ) public notPaused onlyRoadOwner(_x, _y, _direction) noExistingRoadSale(_x, _y, _direction) { // Require that the price is at least 0 require(0 != _askingPrice); // Record the price roadPrices[_x][_y][_direction] = _askingPrice; emit RoadForSale(_x, _y, _direction, msg.sender, _askingPrice); } /// @dev The owner of a road can change the price of a sale /// @param _x The x coordinate of the road /// @param _y The y coordinate of the road /// @param _direction The direction of the road /// @param _askingPrice The new price that must be payed by another /// player to purchase the road function changeRoadPrice( uint _x , uint _y , uint8 _direction , uint _askingPrice ) public notPaused onlyRoadOwner(_x, _y, _direction) existingRoadSale(_x, _y, _direction) { // Require that the price is at least 0 require(0 != _askingPrice); // Record the price roadPrices[_x][_y][_direction] = _askingPrice; emit RoadPriceChanged(_x, _y, _direction, _askingPrice); } /// @dev Anyone can purchase a road as long as the sale exists /// @param _x The x coordinate of the road /// @param _y The y coordinate of the road /// @param _direction The direction of the road function purchaseRoad(uint _x, uint _y, uint8 _direction) public payable notPaused existingRoadSale(_x, _y, _direction) { // Require that the exact price was paid require(roadPrices[_x][_y][_direction] == msg.value); // End the sale roadPrices[_x][_y][_direction] = 0; // Calculate the taxes to be paid uint taxCut = msg.value / taxDivisor; // Pay the taxes KingOfEthAbstractInterface(kingOfEthContract).payTaxes.value(taxCut)(); KingOfEthRoadsAbstractInterface _roadsContract = KingOfEthRoadsAbstractInterface(roadsContract); // Determine the previous owner address _oldOwner = _roadsContract.ownerOf(_x, _y, _direction); // Send the buyer the house _roadsContract.roadRealtyTransferOwnership( _x , _y , _direction , _oldOwner , msg.sender ); // Send the previous owner his share _oldOwner.transfer(msg.value - taxCut); emit RoadSold( _x , _y , _direction , _oldOwner , msg.sender , msg.value ); } /// @dev The owner of a road can cancel a sale /// @param _x The x coordinate of the road /// @param _y The y coordinate of the road /// @param _direction The direction of the road function cancelRoadSale(uint _x, uint _y, uint8 _direction) public notPaused onlyRoadOwner(_x, _y, _direction) existingRoadSale(_x, _y, _direction) { // Cancel the sale roadPrices[_x][_y][_direction] = 0; emit RoadSaleCancelled(_x, _y, _direction, msg.sender); } } // File: contracts/KingOfEthRoadRealtyReferencer.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title King of Eth: Road Realty Referencer /// @author Anthony Burzillo <[email protected]> /// @dev Provides functionality to reference the road realty contract contract KingOfEthRoadRealtyReferencer is GodMode { /// @dev The realty contract's address address public roadRealtyContract; /// @dev Only the road realty contract can run this function modifier onlyRoadRealtyContract() { require(roadRealtyContract == msg.sender); _; } /// @dev God can set the road realty contract /// @param _roadRealtyContract The new address function godSetRoadRealtyContract(address _roadRealtyContract) public onlyGod { roadRealtyContract = _roadRealtyContract; } } // File: contracts/KingOfEthRoads.sol /**************************************************** * * Copyright 2018 BurzNest LLC. All rights reserved. * * The contents of this file are provided for review * and educational purposes ONLY. You MAY NOT use, * copy, distribute, or modify this software without * explicit written permission from BurzNest LLC. * ****************************************************/ pragma solidity ^0.4.24; /// @title King of Eth: Roads /// @author Anthony Burzillo <[email protected]> /// @dev Contract for roads contract KingOfEthRoads is GodMode , KingOfEthBoardReferencer , KingOfEthHousesReferencer , KingOfEthReferencer , KingOfEthResourcesInterfaceReferencer , KingOfEthRoadRealtyReferencer , KingOfEthRoadsAbstractInterface { /// @dev ETH cost to build a road uint public roadCost = 0.0002 ether; /// @dev Mapping from the x, y, direction coordinate of the location to its owner mapping (uint => mapping (uint => address[2])) owners; /// @dev Mapping from a players address to his road counts mapping (address => uint) roadCounts; /// @param _boardContract The address of the board contract /// @param _roadRealtyContract The address of the road realty contract /// @param _kingOfEthContract The address of the king contract /// @param _interfaceContract The address of the resources /// interface contract constructor( address _boardContract , address _roadRealtyContract , address _kingOfEthContract , address _interfaceContract ) public { boardContract = _boardContract; roadRealtyContract = _roadRealtyContract; kingOfEthContract = _kingOfEthContract; interfaceContract = _interfaceContract; } /// @dev Fired when new roads are built event NewRoads( address owner , uint x , uint y , uint8 direction , uint length ); /// @dev Fired when a road is sent from one player to another event SentRoad( uint x , uint y , uint direction , address from , address to ); /// @dev Get the owner of the road at some location /// @param _x The x coordinate of the road /// @param _y The y coordinate of the road /// @param _direction The direction of the road (either /// 0 for right or 1 for down) /// @return The address of the owner function ownerOf(uint _x, uint _y, uint8 _direction) public view returns(address) { // Only 0 or 1 is a valid direction require(2 > _direction); return owners[_x][_y][_direction]; } /// @dev Get the number of roads owned by a player /// @param _player The player's address /// @return The number of roads function numberOfRoads(address _player) public view returns(uint) { return roadCounts[_player]; } /// @dev Only the owner of a road can run this /// @param _x The x coordinate of the road /// @param _y The y coordinate of the road /// @param _direction The direction of the road modifier onlyRoadOwner(uint _x, uint _y, uint8 _direction) { require(owners[_x][_y][_direction] == msg.sender); _; } /// @dev Build houses to the right /// @param _x The x coordinate of the starting point of the first road /// @param _y The y coordinate of the starting point of the first road /// @param _length The length to build function buildRight(uint _x, uint _y, uint _length) private { // Require that nobody currently owns the road require(0x0 == owners[_x][_y][0]); KingOfEthHousesAbstractInterface _housesContract = KingOfEthHousesAbstractInterface(housesContract); // Require that either the player owns the house at the // starting location, the road below it, the road to the // left of it, or the road above it address _houseOwner = _housesContract.ownerOf(_x, _y); require(_houseOwner == msg.sender || (0x0 == _houseOwner && ( owners[_x][_y][1] == msg.sender || owners[_x - 1][_y][0] == msg.sender || owners[_x][_y - 1][1] == msg.sender ))); // Set the new owner owners[_x][_y][0] = msg.sender; for(uint _i = 1; _i < _length; ++_i) { // Require that nobody currently owns the road require(0x0 == owners[_x + _i][_y][0]); // Require that either the house location is empty or // that it is owned by the player require( _housesContract.ownerOf(_x + _i, _y) == 0x0 || _housesContract.ownerOf(_x + _i, _y) == msg.sender ); // Set the new owner owners[_x + _i][_y][0] = msg.sender; } } /// @dev Build houses downwards /// @param _x The x coordinate of the starting point of the first road /// @param _y The y coordinate of the starting point of the first road /// @param _length The length to build function buildDown(uint _x, uint _y, uint _length) private { // Require that nobody currently owns the road require(0x0 == owners[_x][_y][1]); KingOfEthHousesAbstractInterface _housesContract = KingOfEthHousesAbstractInterface(housesContract); // Require that either the player owns the house at the // starting location, the road to the right of it, the road to // the left of it, or the road above it address _houseOwner = _housesContract.ownerOf(_x, _y); require(_houseOwner == msg.sender || (0x0 == _houseOwner && ( owners[_x][_y][0] == msg.sender || owners[_x - 1][_y][0] == msg.sender || owners[_x][_y - 1][1] == msg.sender ))); // Set the new owner owners[_x][_y][1] = msg.sender; for(uint _i = 1; _i < _length; ++_i) { // Require that nobody currently owns the road require(0x0 == owners[_x][_y + _i][1]); // Require that either the house location is empty or // that it is owned by the player require( _housesContract.ownerOf(_x, _y + _i) == 0x0 || _housesContract.ownerOf(_x, _y + _i) == msg.sender ); // Set the new owner owners[_x][_y + _i][1] = msg.sender; } } /// @dev Build houses to the left /// @param _x The x coordinate of the starting point of the first road /// @param _y The y coordinate of the starting point of the first road /// @param _length The length to build function buildLeft(uint _x, uint _y, uint _length) private { // Require that nobody currently owns the road require(0x0 == owners[_x - 1][_y][0]); KingOfEthHousesAbstractInterface _housesContract = KingOfEthHousesAbstractInterface(housesContract); // Require that either the player owns the house at the // starting location, the road to the right of it, the road // below it, or the road above it address _houseOwner = _housesContract.ownerOf(_x, _y); require(_houseOwner == msg.sender || (0x0 == _houseOwner && ( owners[_x][_y][0] == msg.sender || owners[_x][_y][1] == msg.sender || owners[_x][_y - 1][1] == msg.sender ))); // Set the new owner owners[_x - 1][_y][0] = msg.sender; for(uint _i = 1; _i < _length; ++_i) { // Require that nobody currently owns the road require(0x0 == owners[_x - _i - 1][_y][0]); // Require that either the house location is empty or // that it is owned by the player require( _housesContract.ownerOf(_x - _i, _y) == 0x0 || _housesContract.ownerOf(_x - _i, _y) == msg.sender ); // Set the new owner owners[_x - _i - 1][_y][0] = msg.sender; } } /// @dev Build houses upwards /// @param _x The x coordinate of the starting point of the first road /// @param _y The y coordinate of the starting point of the first road /// @param _length The length to build function buildUp(uint _x, uint _y, uint _length) private { // Require that nobody currently owns the road require(0x0 == owners[_x][_y - 1][1]); KingOfEthHousesAbstractInterface _housesContract = KingOfEthHousesAbstractInterface(housesContract); // Require that either the player owns the house at the // starting location, the road to the right of it, the road // below it, or the road to the left of it address _houseOwner = _housesContract.ownerOf(_x, _y); require(_houseOwner == msg.sender || (0x0 == _houseOwner && ( owners[_x][_y][0] == msg.sender || owners[_x][_y][1] == msg.sender || owners[_x - 1][_y][0] == msg.sender ))); // Set the new owner owners[_x][_y - 1][1] = msg.sender; for(uint _i = 1; _i < _length; ++_i) { // Require that nobody currently owns the road require(0x0 == owners[_x][_y - _i - 1][1]); // Require that either the house location is empty or // that it is owned by the player require( _housesContract.ownerOf(_x, _y - _i) == 0x0 || _housesContract.ownerOf(_x, _y - _i) == msg.sender ); // Set the new owner owners[_x][_y - _i - 1][1] = msg.sender; } } /// @dev God can change the road cost /// @param _newRoadCost The new cost of a road function godChangeRoadCost(uint _newRoadCost) public onlyGod { roadCost = _newRoadCost; } /// @dev The road realty contract can transfer road ownership /// @param _x The x coordinate of the road /// @param _y The y coordinate of the road /// @param _direction The direction of the road /// @param _from The previous owner of road /// @param _to The new owner of road function roadRealtyTransferOwnership( uint _x , uint _y , uint8 _direction , address _from , address _to ) public onlyRoadRealtyContract { // Assert that the previous owner still has the road assert(owners[_x][_y][_direction] == _from); // Set the new owner owners[_x][_y][_direction] = _to; // Update the road counts --roadCounts[_from]; ++roadCounts[_to]; } /// @dev Build a road in a direction from a location /// @param _x The x coordinate of the starting location /// @param _y The y coordinate of the starting location /// @param _direction The direction to build (right is 0, down is 1, /// 2 is left, and 3 is up) /// @param _length The number of roads to build function buildRoads( uint _x , uint _y , uint8 _direction , uint _length ) public payable { // Require at least one road to be built require(0 < _length); // Require that the cost for each road was payed require(roadCost * _length == msg.value); KingOfEthBoard _boardContract = KingOfEthBoard(boardContract); // Require that the start is within bounds require(_boardContract.boundX1() <= _x); require(_boardContract.boundY1() <= _y); require(_boardContract.boundX2() > _x); require(_boardContract.boundY2() > _y); // Burn the resource costs for each road KingOfEthResourcesInterface(interfaceContract).burnRoadCosts( _length , msg.sender ); // If the direction is right if(0 == _direction) { // Require that the roads will be in bounds require(_boardContract.boundX2() > _x + _length); buildRight(_x, _y, _length); } // If the direction is down else if(1 == _direction) { // Require that the roads will be in bounds require(_boardContract.boundY2() > _y + _length); buildDown(_x, _y, _length); } // If the direction is left else if(2 == _direction) { // Require that the roads will be in bounds require(_boardContract.boundX1() < _x - _length - 1); buildLeft(_x, _y, _length); } // If the direction is up else if(3 == _direction) { // Require that the roads will be in bounds require(_boardContract.boundY1() < _y - _length - 1); buildUp(_x, _y, _length); } else { // Revert if the direction is invalid revert(); } // Update the number of roads of the player roadCounts[msg.sender] += _length; // Pay taxes KingOfEthAbstractInterface(kingOfEthContract).payTaxes.value(msg.value)(); emit NewRoads(msg.sender, _x, _y, _direction, _length); } /// @dev Send a road to another player /// @param _x The x coordinate of the road /// @param _y The y coordinate of the road /// @param _direction The direction of the road /// @param _to The recipient of the road function sendRoad(uint _x, uint _y, uint8 _direction, address _to) public onlyRoadOwner(_x, _y, _direction) { // Set the new owner owners[_x][_y][_direction] = _to; // Update road counts --roadCounts[msg.sender]; ++roadCounts[_to]; // Cancel any sales that exist KingOfEthRoadRealty(roadRealtyContract).roadsCancelRoadSale( _x , _y , _direction ); emit SentRoad(_x, _y, _direction, msg.sender, _to); } }
Set the next increase direction
nextIncreaseDirection = (nextIncreaseDirection + 1) % 4;
5,490,437
[ 1, 694, 326, 1024, 10929, 4068, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1024, 382, 11908, 8212, 273, 261, 4285, 382, 11908, 8212, 397, 404, 13, 738, 1059, 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 ]
./full_match/43113/0x0b19B8c1108B9130f0730eC57c4AF5154bb141cD/sources/contracts/lbfContract.sol
UsdtInterface usdtContract = UsdtInterface(0xA4001E78DBF93b929D1d558901c14D8154F31542);
contract lbfContract { ERC20 usdtContract; constructor(ERC20 _token) { usdtContract = _token; } function approveToken(address spender, uint amount) public returns(bool) { return usdtContract.approve(spender, amount); } function showAllowance(address spender) public view returns(uint){ return usdtContract.allowance(msg.sender, spender); } function showBalance(address owner) public view returns(uint){ return usdtContract.balanceOf(owner); } function showSuply() public view returns(uint){ return usdtContract.totalSupply(); } }
7,120,528
[ 1, 3477, 7510, 1358, 584, 7510, 8924, 273, 587, 6427, 88, 1358, 12, 20, 21703, 24, 11664, 41, 8285, 2290, 42, 11180, 70, 29, 5540, 40, 21, 72, 2539, 6675, 1611, 71, 3461, 40, 28, 29003, 42, 23, 3600, 9452, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 7831, 74, 8924, 288, 203, 203, 565, 4232, 39, 3462, 584, 7510, 8924, 31, 203, 203, 203, 203, 203, 203, 565, 3885, 12, 654, 39, 3462, 389, 2316, 13, 288, 203, 3639, 584, 7510, 8924, 273, 389, 2316, 31, 203, 565, 289, 203, 203, 565, 445, 6617, 537, 1345, 12, 2867, 17571, 264, 16, 2254, 3844, 13, 1071, 1135, 12, 6430, 13, 288, 203, 3639, 327, 584, 7510, 8924, 18, 12908, 537, 12, 87, 1302, 264, 16, 3844, 1769, 203, 565, 289, 203, 203, 565, 445, 2405, 7009, 1359, 12, 2867, 17571, 264, 13, 1071, 1476, 1135, 12, 11890, 15329, 203, 3639, 327, 584, 7510, 8924, 18, 5965, 1359, 12, 3576, 18, 15330, 16, 17571, 264, 1769, 203, 565, 289, 203, 203, 565, 445, 2405, 13937, 12, 2867, 3410, 13, 1071, 1476, 1135, 12, 11890, 15329, 203, 3639, 327, 584, 7510, 8924, 18, 12296, 951, 12, 8443, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 2405, 17072, 1283, 1435, 1071, 1476, 1135, 12, 11890, 15329, 203, 3639, 327, 584, 7510, 8924, 18, 4963, 3088, 1283, 5621, 203, 565, 289, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { 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.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.5; /* The MIT License (MIT) Copyright (c) 2018 Murray Software, LLC. 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. */ /// @notice Implementation of [EIP-1167] based on [clone-factory] /// source code. /// /// EIP 1167: https://eips.ethereum.org/EIPS/eip-1167 // Original implementation: https://github.com/optionality/clone-factory // Modified to use ^0.8.5; instead of ^0.4.23 solidity version. /* solhint-disable no-inline-assembly */ abstract contract CloneFactory { /// @notice Creates EIP-1167 clone of the contract under the provided /// `target` address. Returns address of the created clone. /// @dev In specific circumstances, such as the `target` contract destroyed, /// create opcode may return 0x0 address. The code calling this /// function should handle this corner case properly. function createClone(address target) internal returns (address result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore( clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone, 0x14), targetBytes) mstore( add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) result := create(0, clone, 0x37) } } /// @notice Checks if the contract under the `query` address is a EIP-1167 /// clone of the contract under `target` address. function isClone(address target, address query) internal view returns (bool result) { bytes20 targetBytes = bytes20(target); assembly { let clone := mload(0x40) mstore( clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000 ) mstore(add(clone, 0xa), targetBytes) mstore( add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) let other := add(clone, 0x40) extcodecopy(query, other, 0, 0x2d) result := and( eq(mload(clone), mload(other)), eq(mload(add(clone, 0xd)), mload(add(other, 0xd))) ) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "./IERC20WithPermit.sol"; import "./IReceiveApproval.sol"; /// @title ERC20WithPermit /// @notice Burnable ERC20 token with EIP2612 permit functionality. User can /// authorize a transfer of their token with a signature conforming /// EIP712 standard instead of an on-chain transaction from their /// address. Anyone can submit this signature on the user's behalf by /// calling the permit function, as specified in EIP2612 standard, /// paying gas fees, and possibly performing other actions in the same /// transaction. contract ERC20WithPermit is IERC20WithPermit, Ownable { /// @notice The amount of tokens owned by the given account. mapping(address => uint256) public override balanceOf; /// @notice The remaining number of tokens that spender will be /// allowed to spend on behalf of owner through `transferFrom` and /// `burnFrom`. This is zero by default. mapping(address => mapping(address => uint256)) public override allowance; /// @notice Returns the current nonce for EIP2612 permission for the /// provided token owner for a replay protection. Used to construct /// EIP2612 signature provided to `permit` function. mapping(address => uint256) public override nonces; uint256 public immutable cachedChainId; bytes32 public immutable cachedDomainSeparator; /// @notice Returns EIP2612 Permit message hash. Used to construct EIP2612 /// signature provided to `permit` function. bytes32 public constant override PERMIT_TYPEHASH = keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ); /// @notice The amount of tokens in existence. uint256 public override totalSupply; /// @notice The name of the token. string public override name; /// @notice The symbol of the token. string public override symbol; /// @notice The decimals places of the token. uint8 public constant override decimals = 18; constructor(string memory _name, string memory _symbol) { name = _name; symbol = _symbol; cachedChainId = block.chainid; cachedDomainSeparator = buildDomainSeparator(); } /// @notice Moves `amount` tokens from the caller's account to `recipient`. /// @return True if the operation succeeded, reverts otherwise. /// @dev Requirements: /// - `recipient` cannot be the zero address, /// - the caller must have a balance of at least `amount`. function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /// @notice Moves `amount` tokens from `sender` to `recipient` using the /// allowance mechanism. `amount` is then deducted from the caller's /// allowance unless the allowance was made for `type(uint256).max`. /// @return True if the operation succeeded, reverts otherwise. /// @dev 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 override returns (bool) { uint256 currentAllowance = allowance[sender][msg.sender]; if (currentAllowance != type(uint256).max) { require( currentAllowance >= amount, "Transfer amount exceeds allowance" ); _approve(sender, msg.sender, currentAllowance - amount); } _transfer(sender, recipient, amount); return true; } /// @notice EIP2612 approval made with secp256k1 signature. /// Users can authorize a transfer of their tokens with a signature /// conforming EIP712 standard, rather than an on-chain transaction /// from their address. Anyone can submit this signature on the /// user's behalf by calling the permit function, paying gas fees, /// and possibly performing other actions in the same transaction. /// @dev The deadline argument can be set to `type(uint256).max to create /// permits that effectively never expire. If the `amount` is set /// to `type(uint256).max` then `transferFrom` and `burnFrom` will /// not reduce an allowance. function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { /* solhint-disable-next-line not-rely-on-time */ require(deadline >= block.timestamp, "Permission expired"); // Validate `s` and `v` values for a malleability concern described in EIP2. // Only signatures with `s` value in the lower half of the secp256k1 // curve's order and `v` value of 27 or 28 are considered valid. require( uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "Invalid signature 's' value" ); require(v == 27 || v == 28, "Invalid signature 'v' value"); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR(), keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline ) ) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require( recoveredAddress != address(0) && recoveredAddress == owner, "Invalid signature" ); _approve(owner, spender, amount); } /// @notice Creates `amount` tokens and assigns them to `account`, /// increasing the total supply. /// @dev Requirements: /// - `recipient` cannot be the zero address. function mint(address recipient, uint256 amount) external onlyOwner { require(recipient != address(0), "Mint to the zero address"); beforeTokenTransfer(address(0), recipient, amount); totalSupply += amount; balanceOf[recipient] += amount; emit Transfer(address(0), recipient, amount); } /// @notice Destroys `amount` tokens from the caller. /// @dev Requirements: /// - the caller must have a balance of at least `amount`. function burn(uint256 amount) external override { _burn(msg.sender, amount); } /// @notice Destroys `amount` of tokens from `account` using the allowance /// mechanism. `amount` is then deducted from the caller's allowance /// unless the allowance was made for `type(uint256).max`. /// @dev Requirements: /// - `account` must have a balance of at least `amount`, /// - the caller must have allowance for `account`'s tokens of at least /// `amount`. function burnFrom(address account, uint256 amount) external override { uint256 currentAllowance = allowance[account][msg.sender]; if (currentAllowance != type(uint256).max) { require( currentAllowance >= amount, "Burn amount exceeds allowance" ); _approve(account, msg.sender, currentAllowance - amount); } _burn(account, amount); } /// @notice Calls `receiveApproval` function on spender previously approving /// the spender to withdraw from the caller multiple times, up to /// the `amount` amount. If this function is called again, it /// overwrites the current allowance with `amount`. Reverts if the /// approval reverted or if `receiveApproval` call on the spender /// reverted. /// @return True if both approval and `receiveApproval` calls succeeded. /// @dev If the `amount` is set to `type(uint256).max` then /// `transferFrom` and `burnFrom` will not reduce an allowance. function approveAndCall( address spender, uint256 amount, bytes memory extraData ) external override returns (bool) { if (approve(spender, amount)) { IReceiveApproval(spender).receiveApproval( msg.sender, amount, address(this), extraData ); return true; } return false; } /// @notice Sets `amount` as the allowance of `spender` over the caller's /// tokens. /// @return True if the operation succeeded. /// @dev If the `amount` is set to `type(uint256).max` then /// `transferFrom` and `burnFrom` will not reduce an allowance. /// 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 function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } /// @notice Returns hash of EIP712 Domain struct with the token name as /// a signing domain and token contract as a verifying contract. /// Used to construct EIP2612 signature provided to `permit` /// function. /* solhint-disable-next-line func-name-mixedcase */ function DOMAIN_SEPARATOR() public view override returns (bytes32) { // As explained in EIP-2612, if the DOMAIN_SEPARATOR contains the // chainId and is defined at contract deployment instead of // reconstructed for every signature, there is a risk of possible replay // attacks between chains in the event of a future chain split. // To address this issue, we check the cached chain ID against the // current one and in case they are different, we build domain separator // from scratch. if (block.chainid == cachedChainId) { return cachedDomainSeparator; } else { return buildDomainSeparator(); } } /// @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. // slither-disable-next-line dead-code function beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function _burn(address account, uint256 amount) internal { uint256 currentBalance = balanceOf[account]; require(currentBalance >= amount, "Burn amount exceeds balance"); beforeTokenTransfer(account, address(0), amount); balanceOf[account] = currentBalance - amount; totalSupply -= amount; emit Transfer(account, address(0), amount); } function _transfer( address sender, address recipient, uint256 amount ) private { require(sender != address(0), "Transfer from the zero address"); require(recipient != address(0), "Transfer to the zero address"); require(recipient != address(this), "Transfer to the token address"); beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = balanceOf[sender]; require(senderBalance >= amount, "Transfer amount exceeds balance"); balanceOf[sender] = senderBalance - amount; balanceOf[recipient] += amount; emit Transfer(sender, recipient, amount); } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "Approve from the zero address"); require(spender != address(0), "Approve to the zero address"); allowance[owner][spender] = amount; emit Approval(owner, spender, amount); } function buildDomainSeparator() private view returns (bytes32) { return keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(name)), keccak256(bytes("1")), block.chainid, address(this) ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice An interface that should be implemented by tokens supporting /// `approveAndCall`/`receiveApproval` pattern. interface IApproveAndCall { /// @notice Executes `receiveApproval` function on spender as specified in /// `IReceiveApproval` interface. Approves spender to withdraw from /// the caller multiple times, up to the `amount`. If this /// function is called again, it overwrites the current allowance /// with `amount`. Reverts if the approval reverted or if /// `receiveApproval` call on the spender reverted. function approveAndCall( address spender, uint256 amount, bytes memory extraData ) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "./IApproveAndCall.sol"; /// @title IERC20WithPermit /// @notice Burnable ERC20 token with EIP2612 permit functionality. User can /// authorize a transfer of their token with a signature conforming /// EIP712 standard instead of an on-chain transaction from their /// address. Anyone can submit this signature on the user's behalf by /// calling the permit function, as specified in EIP2612 standard, /// paying gas fees, and possibly performing other actions in the same /// transaction. interface IERC20WithPermit is IERC20, IERC20Metadata, IApproveAndCall { /// @notice EIP2612 approval made with secp256k1 signature. /// Users can authorize a transfer of their tokens with a signature /// conforming EIP712 standard, rather than an on-chain transaction /// from their address. Anyone can submit this signature on the /// user's behalf by calling the permit function, paying gas fees, /// and possibly performing other actions in the same transaction. /// @dev The deadline argument can be set to `type(uint256).max to create /// permits that effectively never expire. function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /// @notice Destroys `amount` tokens from the caller. function burn(uint256 amount) external; /// @notice Destroys `amount` of tokens from `account`, deducting the amount /// from caller's allowance. function burnFrom(address account, uint256 amount) external; /// @notice Returns hash of EIP712 Domain struct with the token name as /// a signing domain and token contract as a verifying contract. /// Used to construct EIP2612 signature provided to `permit` /// function. /* solhint-disable-next-line func-name-mixedcase */ function DOMAIN_SEPARATOR() external view returns (bytes32); /// @notice Returns the current nonce for EIP2612 permission for the /// provided token owner for a replay protection. Used to construct /// EIP2612 signature provided to `permit` function. function nonces(address owner) external view returns (uint256); /// @notice Returns EIP2612 Permit message hash. Used to construct EIP2612 /// signature provided to `permit` function. /* solhint-disable-next-line func-name-mixedcase */ function PERMIT_TYPEHASH() external pure returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice An interface that should be implemented by contracts supporting /// `approveAndCall`/`receiveApproval` pattern. interface IReceiveApproval { /// @notice Receives approval to spend tokens. Called as a result of /// `approveAndCall` call on the token. function receiveApproval( address from, uint256 amount, address token, bytes calldata extraData ) external; } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; import "./interfaces/IAssetPool.sol"; import "./interfaces/IAssetPoolUpgrade.sol"; import "./RewardsPool.sol"; import "./UnderwriterToken.sol"; import "./GovernanceUtils.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /// @title Asset Pool /// @notice Asset pool is a component of a Coverage Pool. Asset Pool /// accepts a single ERC20 token as collateral, and returns an /// underwriter token. For example, an asset pool might accept deposits /// in KEEP in return for covKEEP underwriter tokens. Underwriter tokens /// represent an ownership share in the underlying collateral of the /// Asset Pool. contract AssetPool is Ownable, IAssetPool { using SafeERC20 for IERC20; using SafeERC20 for UnderwriterToken; IERC20 public immutable collateralToken; UnderwriterToken public immutable underwriterToken; RewardsPool public immutable rewardsPool; IAssetPoolUpgrade public newAssetPool; /// @notice The time it takes the underwriter to withdraw their collateral /// and rewards from the pool. This is the time that needs to pass /// between initiating and completing the withdrawal. During that /// time, underwriter is still earning rewards and their share of /// the pool is still a subject of a possible coverage claim. uint256 public withdrawalDelay = 21 days; uint256 public newWithdrawalDelay; uint256 public withdrawalDelayChangeInitiated; /// @notice The time the underwriter has after the withdrawal delay passed /// to complete the withdrawal. During that time, underwriter is /// still earning rewards and their share of the pool is still /// a subject of a possible coverage claim. /// After the withdrawal timeout elapses, tokens stay in the pool /// and the underwriter has to initiate the withdrawal again and /// wait for the full withdrawal delay to complete the withdrawal. uint256 public withdrawalTimeout = 2 days; uint256 public newWithdrawalTimeout; uint256 public withdrawalTimeoutChangeInitiated; mapping(address => uint256) public withdrawalInitiatedTimestamp; mapping(address => uint256) public pendingWithdrawal; event Deposited( address indexed underwriter, uint256 amount, uint256 covAmount ); event CoverageClaimed( address indexed recipient, uint256 amount, uint256 timestamp ); event WithdrawalInitiated( address indexed underwriter, uint256 covAmount, uint256 timestamp ); event WithdrawalCompleted( address indexed underwriter, uint256 amount, uint256 covAmount, uint256 timestamp ); event ApprovedAssetPoolUpgrade(address newAssetPool); event CancelledAssetPoolUpgrade(address cancelledAssetPool); event AssetPoolUpgraded( address indexed underwriter, uint256 collateralAmount, uint256 covAmount, uint256 timestamp ); event WithdrawalDelayUpdateStarted( uint256 withdrawalDelay, uint256 timestamp ); event WithdrawalDelayUpdated(uint256 withdrawalDelay); event WithdrawalTimeoutUpdateStarted( uint256 withdrawalTimeout, uint256 timestamp ); event WithdrawalTimeoutUpdated(uint256 withdrawalTimeout); /// @notice Reverts if the withdrawal governance delay has not passed yet or /// if the change was not yet initiated. /// @param changeInitiatedTimestamp The timestamp at which the change has /// been initiated modifier onlyAfterWithdrawalGovernanceDelay( uint256 changeInitiatedTimestamp ) { require(changeInitiatedTimestamp > 0, "Change not initiated"); require( /* solhint-disable-next-line not-rely-on-time */ block.timestamp - changeInitiatedTimestamp >= withdrawalGovernanceDelay(), "Governance delay has not elapsed" ); _; } constructor( IERC20 _collateralToken, UnderwriterToken _underwriterToken, address rewardsManager ) { collateralToken = _collateralToken; underwriterToken = _underwriterToken; rewardsPool = new RewardsPool( _collateralToken, address(this), rewardsManager ); } /// @notice Accepts the given amount of collateral token as a deposit and /// mints underwriter tokens representing pool's ownership. /// Optional data in extraData may include a minimal amount of /// underwriter tokens expected to be minted for a depositor. There /// are cases when an amount of minted tokens matters for a /// depositor, as tokens might be used in third party exchanges. /// @dev This function is a shortcut for approve + deposit. function receiveApproval( address from, uint256 amount, address token, bytes calldata extraData ) external { require(msg.sender == token, "Only token caller allowed"); require( token == address(collateralToken), "Unsupported collateral token" ); uint256 toMint = _calculateTokensToMint(amount); if (extraData.length != 0) { require(extraData.length == 32, "Unexpected data length"); uint256 minAmountToMint = abi.decode(extraData, (uint256)); require( minAmountToMint <= toMint, "Amount to mint is smaller than the required minimum" ); } _deposit(from, amount, toMint); } /// @notice Accepts the given amount of collateral token as a deposit and /// mints underwriter tokens representing pool's ownership. /// @dev Before calling this function, collateral token needs to have the /// required amount accepted to transfer to the asset pool. /// @param amountToDeposit Collateral tokens amount that a user deposits to /// the asset pool /// @return The amount of minted underwriter tokens function deposit(uint256 amountToDeposit) external override returns (uint256) { uint256 toMint = _calculateTokensToMint(amountToDeposit); _deposit(msg.sender, amountToDeposit, toMint); return toMint; } /// @notice Accepts the given amount of collateral token as a deposit and /// mints at least a minAmountToMint underwriter tokens representing /// pool's ownership. /// @dev Before calling this function, collateral token needs to have the /// required amount accepted to transfer to the asset pool. /// @param amountToDeposit Collateral tokens amount that a user deposits to /// the asset pool /// @param minAmountToMint Underwriter minimal tokens amount that a user /// expects to receive in exchange for the deposited /// collateral tokens /// @return The amount of minted underwriter tokens function depositWithMin(uint256 amountToDeposit, uint256 minAmountToMint) external override returns (uint256) { uint256 toMint = _calculateTokensToMint(amountToDeposit); require( minAmountToMint <= toMint, "Amount to mint is smaller than the required minimum" ); _deposit(msg.sender, amountToDeposit, toMint); return toMint; } /// @notice Initiates the withdrawal of collateral and rewards from the /// pool. Must be followed with completeWithdrawal call after the /// withdrawal delay passes. Accepts the amount of underwriter /// tokens representing the share of the pool that should be /// withdrawn. Can be called multiple times increasing the pool share /// to withdraw and resetting the withdrawal initiated timestamp for /// each call. Can be called with 0 covAmount to reset the /// withdrawal initiated timestamp if the underwriter has a pending /// withdrawal. In practice 0 covAmount should be used only to /// initiate the withdrawal again in case one did not complete the /// withdrawal before the withdrawal timeout elapsed. /// @dev Before calling this function, underwriter token needs to have the /// required amount accepted to transfer to the asset pool. function initiateWithdrawal(uint256 covAmount) external override { uint256 pending = pendingWithdrawal[msg.sender]; require( covAmount > 0 || pending > 0, "Underwriter token amount must be greater than 0" ); pending += covAmount; pendingWithdrawal[msg.sender] = pending; /* solhint-disable not-rely-on-time */ withdrawalInitiatedTimestamp[msg.sender] = block.timestamp; emit WithdrawalInitiated(msg.sender, pending, block.timestamp); /* solhint-enable not-rely-on-time */ if (covAmount > 0) { underwriterToken.safeTransferFrom( msg.sender, address(this), covAmount ); } } /// @notice Completes the previously initiated withdrawal for the /// underwriter. Anyone can complete the withdrawal for the /// underwriter. The withdrawal has to be completed before the /// withdrawal timeout elapses. Otherwise, the withdrawal has to /// be initiated again and the underwriter has to wait for the /// entire withdrawal delay again before being able to complete /// the withdrawal. /// @return The amount of collateral withdrawn function completeWithdrawal(address underwriter) external override returns (uint256) { /* solhint-disable not-rely-on-time */ uint256 initiatedAt = withdrawalInitiatedTimestamp[underwriter]; require(initiatedAt > 0, "No withdrawal initiated for the underwriter"); uint256 withdrawalDelayEndTimestamp = initiatedAt + withdrawalDelay; require( withdrawalDelayEndTimestamp < block.timestamp, "Withdrawal delay has not elapsed" ); require( withdrawalDelayEndTimestamp + withdrawalTimeout >= block.timestamp, "Withdrawal timeout elapsed" ); uint256 covAmount = pendingWithdrawal[underwriter]; uint256 covSupply = underwriterToken.totalSupply(); delete withdrawalInitiatedTimestamp[underwriter]; delete pendingWithdrawal[underwriter]; // slither-disable-next-line reentrancy-events rewardsPool.withdraw(); uint256 collateralBalance = collateralToken.balanceOf(address(this)); uint256 amountToWithdraw = (covAmount * collateralBalance) / covSupply; emit WithdrawalCompleted( underwriter, amountToWithdraw, covAmount, block.timestamp ); collateralToken.safeTransfer(underwriter, amountToWithdraw); /* solhint-enable not-rely-on-time */ underwriterToken.burn(covAmount); return amountToWithdraw; } /// @notice Transfers collateral tokens to a new Asset Pool which previously /// was approved by the governance. Upgrade does not have to obey /// withdrawal delay. /// Old underwriter tokens are burned in favor of new tokens minted /// in a new Asset Pool. New tokens are sent directly to the /// underwriter from a new Asset Pool. /// @param covAmount Amount of underwriter tokens used to calculate collateral /// tokens which are transferred to a new asset pool /// @param _newAssetPool New Asset Pool address to check validity with the one /// that was approved by the governance function upgradeToNewAssetPool(uint256 covAmount, address _newAssetPool) external { /* solhint-disable not-rely-on-time */ require( address(newAssetPool) != address(0), "New asset pool must be assigned" ); require( address(newAssetPool) == _newAssetPool, "Addresses of a new asset pool must match" ); require( covAmount > 0, "Underwriter token amount must be greater than 0" ); uint256 covSupply = underwriterToken.totalSupply(); // slither-disable-next-line reentrancy-events rewardsPool.withdraw(); uint256 collateralBalance = collateralToken.balanceOf(address(this)); uint256 collateralToTransfer = (covAmount * collateralBalance) / covSupply; collateralToken.safeApprove( address(newAssetPool), collateralToTransfer ); // old underwriter tokens are burned in favor of new minted in a new // asset pool underwriterToken.burnFrom(msg.sender, covAmount); // collateralToTransfer will be sent to a new AssetPool and new // underwriter tokens will be minted and transferred back to the underwriter newAssetPool.depositFor(msg.sender, collateralToTransfer); emit AssetPoolUpgraded( msg.sender, collateralToTransfer, covAmount, block.timestamp ); } /// @notice Allows governance to set a new asset pool so the underwriters /// can move their collateral tokens to a new asset pool without /// having to wait for the withdrawal delay. function approveNewAssetPoolUpgrade(IAssetPoolUpgrade _newAssetPool) external onlyOwner { require( address(_newAssetPool) != address(0), "New asset pool can't be zero address" ); newAssetPool = _newAssetPool; emit ApprovedAssetPoolUpgrade(address(_newAssetPool)); } /// @notice Allows governance to cancel already approved new asset pool /// in case of some misconfiguration. function cancelNewAssetPoolUpgrade() external onlyOwner { emit CancelledAssetPoolUpgrade(address(newAssetPool)); newAssetPool = IAssetPoolUpgrade(address(0)); } /// @notice Allows the coverage pool to demand coverage from the asset hold /// by this pool and send it to the provided recipient address. function claim(address recipient, uint256 amount) external onlyOwner { emit CoverageClaimed(recipient, amount, block.timestamp); rewardsPool.withdraw(); collateralToken.safeTransfer(recipient, amount); } /// @notice Lets the contract owner to begin an update of withdrawal delay /// parameter value. Withdrawal delay is the time it takes the /// underwriter to withdraw their collateral and rewards from the /// pool. This is the time that needs to pass between initiating and /// completing the withdrawal. The change needs to be finalized with /// a call to finalizeWithdrawalDelayUpdate after the required /// governance delay passes. It is up to the contract owner to /// decide what the withdrawal delay value should be but it should /// be long enough so that the possibility of having free-riding /// underwriters escaping from a potential coverage claim by /// withdrawing their positions from the pool is negligible. /// @param _newWithdrawalDelay The new value of withdrawal delay function beginWithdrawalDelayUpdate(uint256 _newWithdrawalDelay) external onlyOwner { newWithdrawalDelay = _newWithdrawalDelay; withdrawalDelayChangeInitiated = block.timestamp; emit WithdrawalDelayUpdateStarted(_newWithdrawalDelay, block.timestamp); } /// @notice Lets the contract owner to finalize an update of withdrawal /// delay parameter value. This call has to be preceded with /// a call to beginWithdrawalDelayUpdate and the governance delay /// has to pass. function finalizeWithdrawalDelayUpdate() external onlyOwner onlyAfterWithdrawalGovernanceDelay(withdrawalDelayChangeInitiated) { withdrawalDelay = newWithdrawalDelay; emit WithdrawalDelayUpdated(withdrawalDelay); newWithdrawalDelay = 0; withdrawalDelayChangeInitiated = 0; } /// @notice Lets the contract owner to begin an update of withdrawal timeout /// parameter value. The withdrawal timeout is the time the /// underwriter has - after the withdrawal delay passed - to /// complete the withdrawal. The change needs to be finalized with /// a call to finalizeWithdrawalTimeoutUpdate after the required /// governance delay passes. It is up to the contract owner to /// decide what the withdrawal timeout value should be but it should /// be short enough so that the time of free-riding by being able to /// immediately escape from the claim is minimal and long enough so /// that honest underwriters have a possibility to finalize the /// withdrawal. It is all about the right proportions with /// a relation to withdrawal delay value. /// @param _newWithdrawalTimeout The new value of the withdrawal timeout function beginWithdrawalTimeoutUpdate(uint256 _newWithdrawalTimeout) external onlyOwner { newWithdrawalTimeout = _newWithdrawalTimeout; withdrawalTimeoutChangeInitiated = block.timestamp; emit WithdrawalTimeoutUpdateStarted( _newWithdrawalTimeout, block.timestamp ); } /// @notice Lets the contract owner to finalize an update of withdrawal /// timeout parameter value. This call has to be preceded with /// a call to beginWithdrawalTimeoutUpdate and the governance delay /// has to pass. function finalizeWithdrawalTimeoutUpdate() external onlyOwner onlyAfterWithdrawalGovernanceDelay(withdrawalTimeoutChangeInitiated) { withdrawalTimeout = newWithdrawalTimeout; emit WithdrawalTimeoutUpdated(withdrawalTimeout); newWithdrawalTimeout = 0; withdrawalTimeoutChangeInitiated = 0; } /// @notice Grants pool shares by minting a given amount of the underwriter /// tokens for the recipient address. In result, the recipient /// obtains part of the pool ownership without depositing any /// collateral tokens. Shares are usually granted for notifiers /// reporting about various contract state changes. /// @dev Can be called only by the contract owner. /// @param recipient Address of the underwriter tokens recipient /// @param covAmount Amount of the underwriter tokens which should be minted function grantShares(address recipient, uint256 covAmount) external onlyOwner { rewardsPool.withdraw(); underwriterToken.mint(recipient, covAmount); } /// @notice Returns the remaining time that has to pass before the contract /// owner will be able to finalize withdrawal delay update. /// Bear in mind the contract owner may decide to wait longer and /// this value is just an absolute minimum. /// @return The time left until withdrawal delay update can be finalized function getRemainingWithdrawalDelayUpdateTime() external view returns (uint256) { return GovernanceUtils.getRemainingChangeTime( withdrawalDelayChangeInitiated, withdrawalGovernanceDelay() ); } /// @notice Returns the remaining time that has to pass before the contract /// owner will be able to finalize withdrawal timeout update. /// Bear in mind the contract owner may decide to wait longer and /// this value is just an absolute minimum. /// @return The time left until withdrawal timeout update can be finalized function getRemainingWithdrawalTimeoutUpdateTime() external view returns (uint256) { return GovernanceUtils.getRemainingChangeTime( withdrawalTimeoutChangeInitiated, withdrawalGovernanceDelay() ); } /// @notice Returns the current collateral token balance of the asset pool /// plus the reward amount (in collateral token) earned by the asset /// pool and not yet withdrawn to the asset pool. /// @return The total value of asset pool in collateral token. function totalValue() external view returns (uint256) { return collateralToken.balanceOf(address(this)) + rewardsPool.earned(); } /// @notice The time it takes to initiate and complete the withdrawal from /// the pool plus 2 days to make a decision. This governance delay /// should be used for all changes directly affecting underwriter /// positions. This time is a minimum and the governance may choose /// to wait longer before finalizing the update. /// @return The withdrawal governance delay in seconds function withdrawalGovernanceDelay() public view returns (uint256) { return withdrawalDelay + withdrawalTimeout + 2 days; } /// @dev Calculates underwriter tokens to mint. function _calculateTokensToMint(uint256 amountToDeposit) internal returns (uint256) { rewardsPool.withdraw(); uint256 covSupply = underwriterToken.totalSupply(); uint256 collateralBalance = collateralToken.balanceOf(address(this)); if (covSupply == 0) { return amountToDeposit; } return (amountToDeposit * covSupply) / collateralBalance; } function _deposit( address depositor, uint256 amountToDeposit, uint256 amountToMint ) internal { require(depositor != address(this), "Self-deposit not allowed"); require( amountToMint > 0, "Minted tokens amount must be greater than 0" ); emit Deposited(depositor, amountToDeposit, amountToMint); underwriterToken.mint(depositor, amountToMint); collateralToken.safeTransferFrom( depositor, address(this), amountToDeposit ); } } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; import "./interfaces/IAuction.sol"; import "./Auctioneer.sol"; import "./CoveragePoolConstants.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /// @title Auction /// @notice A contract to run a linear falling-price auction against a diverse /// basket of assets held in a collateral pool. Auctions are taken using /// a single asset. Over time, a larger and larger portion of the assets /// are on offer, eventually hitting 100% of the backing collateral /// pool. Auctions can be partially filled, and are meant to be amenable /// to flash loans and other atomic constructions to take advantage of /// arbitrage opportunities within a single block. /// @dev Auction contracts are not meant to be deployed directly, and are /// instead cloned by an auction factory. Auction contracts clean up and /// self-destruct on close. An auction that has run the entire length will /// stay open, forever, or until priced fluctuate and it's eventually /// profitable to close. contract Auction is IAuction { using SafeERC20 for IERC20; struct AuctionStorage { IERC20 tokenAccepted; Auctioneer auctioneer; // the auction price, denominated in tokenAccepted uint256 amountOutstanding; uint256 amountDesired; uint256 startTime; uint256 startTimeOffset; uint256 auctionLength; } AuctionStorage public self; address public immutable masterContract; /// @notice Throws if called by any account other than the auctioneer. modifier onlyAuctioneer() { //slither-disable-next-line incorrect-equality require( msg.sender == address(self.auctioneer), "Caller is not the auctioneer" ); _; } constructor() { masterContract = address(this); } /// @notice Initializes auction /// @dev At the beginning of an auction, velocity pool depleting rate is /// always 1. It increases over time after a partial auction buy. /// @param _auctioneer the auctioneer contract responsible for seizing /// funds from the backing collateral pool /// @param _tokenAccepted the token with which the auction can be taken /// @param _amountDesired the amount denominated in _tokenAccepted. After /// this amount is received, the auction can close. /// @param _auctionLength the amount of time it takes for the auction to get /// to 100% of all collateral on offer, in seconds. function initialize( Auctioneer _auctioneer, IERC20 _tokenAccepted, uint256 _amountDesired, uint256 _auctionLength ) external { require(!isMasterContract(), "Can not initialize master contract"); //slither-disable-next-line incorrect-equality require(self.startTime == 0, "Auction already initialized"); require(_amountDesired > 0, "Amount desired must be greater than zero"); require(_auctionLength > 0, "Auction length must be greater than zero"); self.auctioneer = _auctioneer; self.tokenAccepted = _tokenAccepted; self.amountOutstanding = _amountDesired; self.amountDesired = _amountDesired; /* solhint-disable-next-line not-rely-on-time */ self.startTime = block.timestamp; self.startTimeOffset = 0; self.auctionLength = _auctionLength; } /// @notice Takes an offer from an auction buyer. /// @dev There are two possible ways to take an offer from a buyer. The first /// one is to buy entire auction with the amount desired for this auction. /// The other way is to buy a portion of an auction. In this case an /// auction depleting rate is increased. /// WARNING: When calling this function directly, it might happen that /// the expected amount of tokens to seize from the coverage pool is /// different from the actual one. There are a couple of reasons for that /// such another bids taking this offer, claims or withdrawals on an /// Asset Pool that are executed in the same block. The recommended way /// for taking an offer is through 'AuctionBidder' contract with /// 'takeOfferWithMin' function, where a caller can specify the minimal /// value to receive from the coverage pool in exchange for its amount /// of tokenAccepted. /// @param amount the amount the taker is paying, denominated in tokenAccepted. /// In the scenario when amount exceeds the outstanding tokens /// for the auction to complete, only the amount outstanding will /// be taken from a caller. function takeOffer(uint256 amount) external override { require(amount > 0, "Can't pay 0 tokens"); uint256 amountToTransfer = Math.min(amount, self.amountOutstanding); uint256 amountOnOffer = _onOffer(); //slither-disable-next-line reentrancy-no-eth self.tokenAccepted.safeTransferFrom( msg.sender, address(self.auctioneer), amountToTransfer ); uint256 portionToSeize = (amountOnOffer * amountToTransfer) / self.amountOutstanding; if (!isAuctionOver() && amountToTransfer != self.amountOutstanding) { // Time passed since the auction start or the last takeOffer call // with a partial fill. uint256 timePassed /* solhint-disable-next-line not-rely-on-time */ = block.timestamp - self.startTime - self.startTimeOffset; // Ratio of the auction's amount included in this takeOffer call to // the whole outstanding auction amount. uint256 ratioAmountPaid = (CoveragePoolConstants .FLOATING_POINT_DIVISOR * amountToTransfer) / self.amountOutstanding; // We will shift the start time offset and increase the velocity pool // depleting rate proportionally to the fraction of the outstanding // amount paid in this function call so that the auction can offer // no worse financial outcome for the next takers than the current // taker has. // //slither-disable-next-line divide-before-multiply self.startTimeOffset = self.startTimeOffset + ((timePassed * ratioAmountPaid) / CoveragePoolConstants.FLOATING_POINT_DIVISOR); } self.amountOutstanding -= amountToTransfer; //slither-disable-next-line incorrect-equality bool isFullyFilled = self.amountOutstanding == 0; // inform auctioneer of proceeds and winner. the auctioneer seizes funds // from the collateral pool in the name of the winner, and controls all // proceeds // //slither-disable-next-line reentrancy-no-eth self.auctioneer.offerTaken( msg.sender, self.tokenAccepted, amountToTransfer, portionToSeize, isFullyFilled ); //slither-disable-next-line incorrect-equality if (isFullyFilled) { harikari(); } } /// @notice Tears down the auction manually, before its entire amount /// is bought by takers. /// @dev Can be called only by the auctioneer which may decide to early // close the auction in case it is no longer needed. function earlyClose() external onlyAuctioneer { require(self.amountOutstanding > 0, "Auction must be open"); harikari(); } /// @notice How much of the collateral pool can currently be purchased at /// auction, across all assets. /// @dev _onOffer() / FLOATING_POINT_DIVISOR) returns a portion of the /// collateral pool. Ex. if 35% available of the collateral pool, /// then _onOffer() / FLOATING_POINT_DIVISOR) returns 0.35 /// @return the ratio of the collateral pool currently on offer function onOffer() external view override returns (uint256, uint256) { return (_onOffer(), CoveragePoolConstants.FLOATING_POINT_DIVISOR); } function amountOutstanding() external view returns (uint256) { return self.amountOutstanding; } function amountTransferred() external view returns (uint256) { return self.amountDesired - self.amountOutstanding; } /// @dev Delete all storage and destroy the contract. Should only be called /// after an auction has closed. function harikari() internal { require(!isMasterContract(), "Master contract can not harikari"); selfdestruct(payable(address(self.auctioneer))); } function _onOffer() internal view returns (uint256) { // when the auction is over, entire pool is on offer if (isAuctionOver()) { // Down the road, for determining a portion on offer, a value returned // by this function will be divided by FLOATING_POINT_DIVISOR. To // return the entire pool, we need to return just this divisor in order // to get 1.0 ie. FLOATING_POINT_DIVISOR / FLOATING_POINT_DIVISOR = 1.0 return CoveragePoolConstants.FLOATING_POINT_DIVISOR; } // How fast portions of the collateral pool become available on offer. // It is needed to calculate the right portion value on offer at the // given moment before the auction is over. // Auction length once set is constant and what changes is the auction's // "start time offset" once the takeOffer() call has been processed for // partial fill. The auction's "start time offset" is updated every takeOffer(). // velocityPoolDepletingRate = auctionLength / (auctionLength - startTimeOffset) // velocityPoolDepletingRate always starts at 1.0 and then can go up // depending on partial offer calls over auction life span to maintain // the right ratio between the remaining auction time and the remaining // portion of the collateral pool. //slither-disable-next-line divide-before-multiply uint256 velocityPoolDepletingRate = (CoveragePoolConstants .FLOATING_POINT_DIVISOR * self.auctionLength) / (self.auctionLength - self.startTimeOffset); return /* solhint-disable-next-line not-rely-on-time */ ((block.timestamp - (self.startTime + self.startTimeOffset)) * velocityPoolDepletingRate) / self.auctionLength; } function isAuctionOver() internal view returns (bool) { /* solhint-disable-next-line not-rely-on-time */ return block.timestamp >= self.startTime + self.auctionLength; } function isMasterContract() internal view returns (bool) { return masterContract == address(this); } } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; import "./Auction.sol"; import "./CoveragePool.sol"; import "@thesis/solidity-contracts/contracts/clone/CloneFactory.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title Auctioneer /// @notice Factory for the creation of new auction clones and receiving proceeds. /// @dev We avoid redeployment of auction contracts by using the clone factory. /// Proxy delegates calls to Auction and therefore does not affect auction state. /// This means that we only need to deploy the auction contracts once. /// The auctioneer provides clean state for every new auction clone. contract Auctioneer is CloneFactory { // Holds the address of the auction contract // which will be used as a master contract for cloning. address public immutable masterAuction; mapping(address => bool) public openAuctions; uint256 public openAuctionsCount; CoveragePool public immutable coveragePool; event AuctionCreated( address indexed tokenAccepted, uint256 amount, address auctionAddress ); event AuctionOfferTaken( address indexed auction, address indexed offerTaker, address tokenAccepted, uint256 amount, uint256 portionToSeize // This amount should be divided by FLOATING_POINT_DIVISOR ); event AuctionClosed(address indexed auction); constructor(CoveragePool _coveragePool, address _masterAuction) { coveragePool = _coveragePool; // slither-disable-next-line missing-zero-check masterAuction = _masterAuction; } /// @notice Informs the auctioneer to seize funds and log appropriate events /// @dev This function is meant to be called from a cloned auction. It logs /// "offer taken" and "auction closed" events, seizes funds, and cleans /// up closed auctions. /// @param offerTaker The address of the taker of the auction offer, /// who will receive the pool's seized funds /// @param tokenPaid The token this auction is denominated in /// @param tokenAmountPaid The amount of the token the taker paid /// @param portionToSeize The portion of the pool the taker won at auction. /// This amount should be divided by FLOATING_POINT_DIVISOR /// to calculate how much of the pool should be set /// aside as the taker's winnings. /// @param fullyFilled Indicates whether the auction was taken fully or /// partially. If auction was fully filled, it is /// closed. If auction was partially filled, it is /// sill open and waiting for remaining bids. function offerTaken( address offerTaker, IERC20 tokenPaid, uint256 tokenAmountPaid, uint256 portionToSeize, bool fullyFilled ) external { require(openAuctions[msg.sender], "Sender isn't an auction"); emit AuctionOfferTaken( msg.sender, offerTaker, address(tokenPaid), tokenAmountPaid, portionToSeize ); // actually seize funds, setting them aside for the taker to withdraw // from the coverage pool. // `portionToSeize` will be divided by FLOATING_POINT_DIVISOR which is // defined in Auction.sol // //slither-disable-next-line reentrancy-no-eth,reentrancy-events,reentrancy-benign coveragePool.seizeFunds(offerTaker, portionToSeize); Auction auction = Auction(msg.sender); if (fullyFilled) { onAuctionFullyFilled(auction); emit AuctionClosed(msg.sender); delete openAuctions[msg.sender]; openAuctionsCount -= 1; } else { onAuctionPartiallyFilled(auction); } } /// @notice Opens a new auction against the coverage pool. The auction /// will remain open until filled. /// @dev Calls `Auction.initialize` to initialize the instance. /// @param tokenAccepted The token with which the auction can be taken /// @param amountDesired The amount denominated in _tokenAccepted. After /// this amount is received, the auction can close. /// @param auctionLength The amount of time it takes for the auction to get /// to 100% of all collateral on offer, in seconds. function createAuction( IERC20 tokenAccepted, uint256 amountDesired, uint256 auctionLength ) internal returns (address) { address cloneAddress = createClone(masterAuction); require(cloneAddress != address(0), "Cloned auction address is 0"); Auction auction = Auction(cloneAddress); //slither-disable-next-line reentrancy-benign,reentrancy-events auction.initialize(this, tokenAccepted, amountDesired, auctionLength); openAuctions[cloneAddress] = true; openAuctionsCount += 1; emit AuctionCreated( address(tokenAccepted), amountDesired, cloneAddress ); return cloneAddress; } /// @notice Tears down an open auction with given address immediately. /// @dev Can be called by contract owner to early close an auction if it /// is no longer needed. Bear in mind that funds from the early closed /// auction last on the auctioneer contract. Calling code should take /// care of them. /// @return Amount of funds transferred to this contract by the Auction /// being early closed. function earlyCloseAuction(Auction auction) internal returns (uint256) { address auctionAddress = address(auction); require(openAuctions[auctionAddress], "Address is not an open auction"); uint256 amountTransferred = auction.amountTransferred(); //slither-disable-next-line reentrancy-no-eth,reentrancy-events,reentrancy-benign auction.earlyClose(); emit AuctionClosed(auctionAddress); delete openAuctions[auctionAddress]; openAuctionsCount -= 1; return amountTransferred; } /// @notice Auction lifecycle hook allowing to act on auction closed /// as fully filled. This function is not executed when an auction /// was partially filled. When this function is executed auction is /// already closed and funds from the coverage pool are seized. /// @dev Override this function to act on auction closed as fully filled. function onAuctionFullyFilled(Auction auction) internal virtual {} /// @notice Auction lifecycle hook allowing to act on auction partially /// filled. This function is not executed when an auction /// was fully filled. /// @dev Override this function to act on auction partially filled. function onAuctionPartiallyFilled(Auction auction) internal view virtual {} } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; import "./interfaces/IAssetPoolUpgrade.sol"; import "./AssetPool.sol"; import "./CoveragePoolConstants.sol"; import "./GovernanceUtils.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title Coverage Pool /// @notice A contract that manages a single asset pool. Handles approving and /// unapproving of risk managers and allows them to seize funds from the /// asset pool if they are approved. /// @dev Coverage pool contract is owned by the governance. Coverage pool is the /// owner of the asset pool contract. contract CoveragePool is Ownable { AssetPool public immutable assetPool; IERC20 public immutable collateralToken; bool public firstRiskManagerApproved = false; // Currently approved risk managers mapping(address => bool) public approvedRiskManagers; // Timestamps of risk managers whose approvals have been initiated mapping(address => uint256) public riskManagerApprovalTimestamps; event RiskManagerApprovalStarted(address riskManager, uint256 timestamp); event RiskManagerApprovalCompleted(address riskManager, uint256 timestamp); event RiskManagerUnapproved(address riskManager, uint256 timestamp); /// @notice Reverts if called by a risk manager that is not approved modifier onlyApprovedRiskManager() { require(approvedRiskManagers[msg.sender], "Risk manager not approved"); _; } constructor(AssetPool _assetPool) { assetPool = _assetPool; collateralToken = _assetPool.collateralToken(); } /// @notice Approves the first risk manager /// @dev Can be called only by the contract owner. Can be called only once. /// Does not require any further calls to any functions. /// @param riskManager Risk manager that will be approved function approveFirstRiskManager(address riskManager) external onlyOwner { require( !firstRiskManagerApproved, "The first risk manager was approved" ); approvedRiskManagers[riskManager] = true; firstRiskManagerApproved = true; } /// @notice Begins risk manager approval process. /// @dev Can be called only by the contract owner and only when the first /// risk manager is already approved. For a risk manager to be /// approved, a call to `finalizeRiskManagerApproval` must follow /// (after a governance delay). /// @param riskManager Risk manager that will be approved function beginRiskManagerApproval(address riskManager) external onlyOwner { require( firstRiskManagerApproved, "The first risk manager is not yet approved; Please use " "approveFirstRiskManager instead" ); require( !approvedRiskManagers[riskManager], "Risk manager already approved" ); /* solhint-disable-next-line not-rely-on-time */ riskManagerApprovalTimestamps[riskManager] = block.timestamp; /* solhint-disable-next-line not-rely-on-time */ emit RiskManagerApprovalStarted(riskManager, block.timestamp); } /// @notice Finalizes risk manager approval process. /// @dev Can be called only by the contract owner. Must be preceded with a /// call to beginRiskManagerApproval and a governance delay must elapse. /// @param riskManager Risk manager that will be approved function finalizeRiskManagerApproval(address riskManager) external onlyOwner { require( riskManagerApprovalTimestamps[riskManager] > 0, "Risk manager approval not initiated" ); require( /* solhint-disable-next-line not-rely-on-time */ block.timestamp - riskManagerApprovalTimestamps[riskManager] >= assetPool.withdrawalGovernanceDelay(), "Risk manager governance delay has not elapsed" ); approvedRiskManagers[riskManager] = true; /* solhint-disable-next-line not-rely-on-time */ emit RiskManagerApprovalCompleted(riskManager, block.timestamp); delete riskManagerApprovalTimestamps[riskManager]; } /// @notice Unapproves an already approved risk manager or cancels the /// approval process of a risk manager (the latter happens if called /// between `beginRiskManagerApproval` and `finalizeRiskManagerApproval`). /// The change takes effect immediately. /// @dev Can be called only by the contract owner. /// @param riskManager Risk manager that will be unapproved function unapproveRiskManager(address riskManager) external onlyOwner { require( riskManagerApprovalTimestamps[riskManager] > 0 || approvedRiskManagers[riskManager], "Risk manager is neither approved nor with a pending approval" ); delete riskManagerApprovalTimestamps[riskManager]; delete approvedRiskManagers[riskManager]; /* solhint-disable-next-line not-rely-on-time */ emit RiskManagerUnapproved(riskManager, block.timestamp); } /// @notice Approves upgradeability to the new asset pool. /// Allows governance to set a new asset pool so the underwriters /// can move their collateral tokens to a new asset pool without /// having to wait for the withdrawal delay. /// @param _newAssetPool New asset pool function approveNewAssetPoolUpgrade(IAssetPoolUpgrade _newAssetPool) external onlyOwner { assetPool.approveNewAssetPoolUpgrade(_newAssetPool); } /// @notice Lets the governance to begin an update of withdrawal delay /// parameter value. Withdrawal delay is the time it takes the /// underwriter to withdraw their collateral and rewards from the /// pool. This is the time that needs to pass between initiating and /// completing the withdrawal. The change needs to be finalized with /// a call to finalizeWithdrawalDelayUpdate after the required /// governance delay passes. It is up to the governance to /// decide what the withdrawal delay value should be but it should /// be long enough so that the possibility of having free-riding /// underwriters escaping from a potential coverage claim by /// withdrawing their positions from the pool is negligible. /// @param newWithdrawalDelay The new value of withdrawal delay function beginWithdrawalDelayUpdate(uint256 newWithdrawalDelay) external onlyOwner { assetPool.beginWithdrawalDelayUpdate(newWithdrawalDelay); } /// @notice Lets the governance to finalize an update of withdrawal /// delay parameter value. This call has to be preceded with /// a call to beginWithdrawalDelayUpdate and the governance delay /// has to pass. function finalizeWithdrawalDelayUpdate() external onlyOwner { assetPool.finalizeWithdrawalDelayUpdate(); } /// @notice Lets the governance to begin an update of withdrawal timeout /// parameter value. The withdrawal timeout is the time the /// underwriter has - after the withdrawal delay passed - to /// complete the withdrawal. The change needs to be finalized with /// a call to finalizeWithdrawalTimeoutUpdate after the required /// governance delay passes. It is up to the governance to /// decide what the withdrawal timeout value should be but it should /// be short enough so that the time of free-riding by being able to /// immediately escape from the claim is minimal and long enough so /// that honest underwriters have a possibility to finalize the /// withdrawal. It is all about the right proportions with /// a relation to withdrawal delay value. /// @param newWithdrawalTimeout The new value of the withdrawal timeout function beginWithdrawalTimeoutUpdate(uint256 newWithdrawalTimeout) external onlyOwner { assetPool.beginWithdrawalTimeoutUpdate(newWithdrawalTimeout); } /// @notice Lets the governance to finalize an update of withdrawal /// timeout parameter value. This call has to be preceded with /// a call to beginWithdrawalTimeoutUpdate and the governance delay /// has to pass. function finalizeWithdrawalTimeoutUpdate() external onlyOwner { assetPool.finalizeWithdrawalTimeoutUpdate(); } /// @notice Seizes funds from the coverage pool and puts them aside for the /// recipient to withdraw. /// @dev `portionToSeize` value was multiplied by `FLOATING_POINT_DIVISOR` /// for calculation precision purposes. Further calculations in this /// function will need to take this divisor into account. /// @param recipient Address that will receive the pool's seized funds /// @param portionToSeize Portion of the pool to seize in the range (0, 1] /// multiplied by `FLOATING_POINT_DIVISOR` function seizeFunds(address recipient, uint256 portionToSeize) external onlyApprovedRiskManager { require( portionToSeize > 0 && portionToSeize <= CoveragePoolConstants.FLOATING_POINT_DIVISOR, "Portion to seize is not within the range (0, 1]" ); assetPool.claim(recipient, amountToSeize(portionToSeize)); } /// @notice Grants asset pool shares by minting a given amount of the /// underwriter tokens for the recipient address. In result, the /// recipient obtains part of the pool ownership without depositing /// any collateral tokens. Shares are usually granted for notifiers /// reporting about various contract state changes. /// @dev Can be called only by an approved risk manager. /// @param recipient Address of the underwriter tokens recipient /// @param covAmount Amount of the underwriter tokens which should be minted function grantAssetPoolShares(address recipient, uint256 covAmount) external onlyApprovedRiskManager { assetPool.grantShares(recipient, covAmount); } /// @notice Returns the time remaining until the risk manager approval /// process can be finalized /// @param riskManager Risk manager in the process of approval /// @return Remaining time in seconds. function getRemainingRiskManagerApprovalTime(address riskManager) external view returns (uint256) { return GovernanceUtils.getRemainingChangeTime( riskManagerApprovalTimestamps[riskManager], assetPool.withdrawalGovernanceDelay() ); } /// @notice Calculates amount of tokens to be seized from the coverage pool. /// @param portionToSeize Portion of the pool to seize in the range (0, 1] /// multiplied by FLOATING_POINT_DIVISOR function amountToSeize(uint256 portionToSeize) public view returns (uint256) { return (collateralToken.balanceOf(address(assetPool)) * portionToSeize) / CoveragePoolConstants.FLOATING_POINT_DIVISOR; } } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; library CoveragePoolConstants { // This divisor is for precision purposes only. We use this divisor around // auction related code to get the precise values without rounding it down // when dealing with floating numbers. uint256 public constant FLOATING_POINT_DIVISOR = 1e18; } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; library GovernanceUtils { /// @notice Gets the time remaining until the governable parameter update /// can be committed. /// @param changeTimestamp Timestamp indicating the beginning of the change. /// @param delay Governance delay. /// @return Remaining time in seconds. function getRemainingChangeTime(uint256 changeTimestamp, uint256 delay) internal view returns (uint256) { require(changeTimestamp > 0, "Change not initiated"); /* solhint-disable-next-line not-rely-on-time */ uint256 elapsed = block.timestamp - changeTimestamp; if (elapsed >= delay) { return 0; } else { return delay - elapsed; } } } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /// @title Rewards Pool /// @notice RewardsPool accepts a single reward token and releases it to the /// AssetPool over time in one week reward intervals. The owner of this /// contract is the reward distribution address funding it with reward /// tokens. contract RewardsPool is Ownable { using SafeERC20 for IERC20; uint256 public constant DURATION = 7 days; IERC20 public immutable rewardToken; address public immutable assetPool; // timestamp of the current reward interval end or the timestamp of the // last interval end in case a new reward interval has not been allocated uint256 public intervalFinish = 0; // rate per second with which reward tokens are unlocked uint256 public rewardRate = 0; // amount of rewards accumulated and not yet withdrawn from the previous // reward interval(s) uint256 public rewardAccumulated = 0; // the last time information in this contract was updated uint256 public lastUpdateTime = 0; event RewardToppedUp(uint256 amount); event RewardWithdrawn(uint256 amount); constructor( IERC20 _rewardToken, address _assetPool, address owner ) { rewardToken = _rewardToken; // slither-disable-next-line missing-zero-check assetPool = _assetPool; transferOwnership(owner); } /// @notice Transfers the provided reward amount into RewardsPool and /// creates a new, one-week reward interval starting from now. /// Reward tokens from the previous reward interval that unlocked /// over the time will be available for withdrawal immediately. /// Reward tokens from the previous interval that has not been yet /// unlocked, are added to the new interval being created. /// @dev This function can be called only by the owner given that it creates /// a new interval with one week length, starting from now. function topUpReward(uint256 reward) external onlyOwner { rewardAccumulated = earned(); /* solhint-disable not-rely-on-time */ if (block.timestamp >= intervalFinish) { // see https://github.com/crytic/slither/issues/844 // slither-disable-next-line divide-before-multiply rewardRate = reward / DURATION; } else { uint256 remaining = intervalFinish - block.timestamp; uint256 leftover = remaining * rewardRate; rewardRate = (reward + leftover) / DURATION; } intervalFinish = block.timestamp + DURATION; lastUpdateTime = block.timestamp; /* solhint-enable avoid-low-level-calls */ emit RewardToppedUp(reward); rewardToken.safeTransferFrom(msg.sender, address(this), reward); } /// @notice Withdraws all unlocked reward tokens to the AssetPool. function withdraw() external { uint256 amount = earned(); rewardAccumulated = 0; lastUpdateTime = lastTimeRewardApplicable(); emit RewardWithdrawn(amount); rewardToken.safeTransfer(assetPool, amount); } /// @notice Returns the amount of earned and not yet withdrawn reward /// tokens. function earned() public view returns (uint256) { return rewardAccumulated + ((lastTimeRewardApplicable() - lastUpdateTime) * rewardRate); } /// @notice Returns the timestamp at which a reward was last time applicable. /// When reward interval is pending, returns current block's /// timestamp. If the last reward interval ended and no other reward /// interval had been allocated, returns the last reward interval's /// end timestamp. function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, intervalFinish); } } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; import "@thesis/solidity-contracts/contracts/token/ERC20WithPermit.sol"; /// @title UnderwriterToken /// @notice Underwriter tokens represent an ownership share in the underlying /// collateral of the asset-specific pool. Underwriter tokens are minted /// when a user deposits ERC20 tokens into asset-specific pool and they /// are burned when a user exits the position. Underwriter tokens /// natively support meta transactions. Users can authorize a transfer /// of their underwriter tokens with a signature conforming EIP712 /// standard instead of an on-chain transaction from their address. /// Anyone can submit this signature on the user's behalf by calling the /// permit function, as specified in EIP2612 standard, paying gas fees, /// and possibly performing other actions in the same transaction. contract UnderwriterToken is ERC20WithPermit { constructor(string memory _name, string memory _symbol) ERC20WithPermit(_name, _symbol) {} } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; /// @title Asset Pool interface /// @notice Asset Pool accepts a single ERC20 token as collateral, and returns /// an underwriter token. For example, an asset pool might accept deposits /// in KEEP in return for covKEEP underwriter tokens. Underwriter tokens /// represent an ownership share in the underlying collateral of the /// Asset Pool. interface IAssetPool { /// @notice Accepts the given amount of collateral token as a deposit and /// mints underwriter tokens representing pool's ownership. /// @dev Before calling this function, collateral token needs to have the /// required amount accepted to transfer to the asset pool. /// @return The amount of minted underwriter tokens function deposit(uint256 amount) external returns (uint256); /// @notice Accepts the given amount of collateral token as a deposit and /// mints at least a minAmountToMint underwriter tokens representing /// pool's ownership. /// @dev Before calling this function, collateral token needs to have the /// required amount accepted to transfer to the asset pool. /// @return The amount of minted underwriter tokens function depositWithMin(uint256 amountToDeposit, uint256 minAmountToMint) external returns (uint256); /// @notice Initiates the withdrawal of collateral and rewards from the pool. /// @dev Before calling this function, underwriter token needs to have the /// required amount accepted to transfer to the asset pool. function initiateWithdrawal(uint256 covAmount) external; /// @notice Completes the previously initiated withdrawal for the /// underwriter. /// @return The amount of collateral withdrawn function completeWithdrawal(address underwriter) external returns (uint256); } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; /// @title Asset Pool upgrade interface /// @notice Interface that has to be implemented by an Asset Pool accepting /// upgrades from another asset pool. interface IAssetPoolUpgrade { /// @notice Accepts the given underwriter with collateral tokens amount as a /// deposit. In exchange new underwriter tokens will be calculated, /// minted and then transferred back to the underwriter. function depositFor(address underwriter, uint256 amount) external; } // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // Trust math, not hardware. // SPDX-License-Identifier: MIT pragma solidity 0.8.5; /// @title Auction interface /// @notice Auction runs a linear falling-price auction against a diverse /// basket of assets held in a collateral pool. Auctions are taken using /// a single asset. Over time, a larger and larger portion of the assets /// are on offer, eventually hitting 100% of the backing collateral interface IAuction { /// @notice Takes an offer from an auction buyer. There are two possible /// ways to take an offer from a buyer. The first one is to buy /// entire auction with the amount desired for this auction. /// The other way is to buy a portion of an auction. In this case an /// auction depleting rate is increased. /// @dev The implementation is not guaranteed to be protecting against /// frontrunning. See `AuctionBidder` for an example protection. function takeOffer(uint256 amount) external; /// @notice How much of the collateral pool can currently be purchased at /// auction, across all assets. /// @return The ratio of the collateral pool currently on offer and divisor /// for precision purposes. function onOffer() external view returns (uint256, uint256); }
@notice Seizes funds from the coverage pool and puts them aside for the recipient to withdraw. @dev `portionToSeize` value was multiplied by `FLOATING_POINT_DIVISOR` for calculation precision purposes. Further calculations in this function will need to take this divisor into account. @param recipient Address that will receive the pool's seized funds @param portionToSeize Portion of the pool to seize in the range (0, 1] multiplied by `FLOATING_POINT_DIVISOR`
function seizeFunds(address recipient, uint256 portionToSeize) external onlyApprovedRiskManager { require( portionToSeize > 0 && portionToSeize <= CoveragePoolConstants.FLOATING_POINT_DIVISOR, "Portion to seize is not within the range (0, 1]" ); assetPool.claim(recipient, amountToSeize(portionToSeize)); }
112,430
[ 1, 1761, 3128, 284, 19156, 628, 326, 11196, 2845, 471, 8200, 2182, 487, 831, 364, 326, 540, 8027, 358, 598, 9446, 18, 225, 1375, 17564, 774, 1761, 554, 68, 460, 1703, 27789, 635, 1375, 15640, 1360, 67, 8941, 67, 2565, 26780, 916, 68, 1377, 364, 11096, 6039, 13694, 18, 478, 8753, 20882, 316, 333, 1377, 445, 903, 1608, 358, 4862, 333, 15013, 1368, 2236, 18, 225, 8027, 5267, 716, 903, 6798, 326, 2845, 1807, 695, 1235, 284, 19156, 225, 14769, 774, 1761, 554, 6008, 285, 434, 326, 2845, 358, 695, 554, 316, 326, 1048, 261, 20, 16, 404, 65, 3639, 27789, 635, 1375, 15640, 1360, 67, 8941, 67, 2565, 26780, 916, 68, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 695, 554, 42, 19156, 12, 2867, 8027, 16, 2254, 5034, 14769, 774, 1761, 554, 13, 203, 3639, 3903, 203, 3639, 1338, 31639, 54, 10175, 1318, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 14769, 774, 1761, 554, 405, 374, 597, 203, 7734, 14769, 774, 1761, 554, 1648, 30856, 2864, 2918, 18, 15640, 1360, 67, 8941, 67, 2565, 26780, 916, 16, 203, 5411, 315, 2617, 285, 358, 695, 554, 353, 486, 3470, 326, 1048, 261, 20, 16, 404, 4279, 203, 3639, 11272, 203, 203, 3639, 3310, 2864, 18, 14784, 12, 20367, 16, 3844, 774, 1761, 554, 12, 17564, 774, 1761, 554, 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 ]
pragma solidity ^0.5.0; // Copyright 2018 OpenST Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import "../lib/Block.sol"; import "../lib/MetaBlock.sol"; import "../lib/SafeMath.sol"; import "./BlockStoreInterface.sol"; import "./OriginTransitionObjectInterface.sol"; /** * @title A block store stores blocks of a block chain. * * @notice The block store stores headers of blocks. Not all headers have to be * reported. It is only required to report all headers that should * become justified checkpoints. * The block store tracks all justifications and finalisations through * calls to the `justify()` method. Only the polling place can call * that method. */ contract BlockStore is BlockStoreInterface, OriginTransitionObjectInterface { using SafeMath for uint256; /* Events */ /** Logs that a block has been reported. */ event BlockReported(bytes32 blockHash); /** Logs that a block has been justified. */ event BlockJustified(bytes32 blockHash); /** Logs that a block has been finalised. */ event BlockFinalised(bytes32 blockHash); /* Structs */ /** A casper FFG checkpoint. */ struct Checkpoint { /** The block hash of the block at this checkpoint. */ bytes32 blockHash; /** The hash of the block of the parent checkpoint (not block) */ bytes32 parent; /** Is true if the checkpoint has been justified. */ bool justified; /** Is true if the checkpoint has been finalised. */ bool finalised; /** * The dynasty of block b is the number of finalized checkpoints in the * chain from the starting checkpoint to the parent of block b. */ uint256 dynasty; } /* Public Variables */ /** * The core identifier identifies the chain that this block store is * tracking. */ bytes20 internal coreIdentifier; /** * The epoch length is the number of blocks from one checkpoint to the * next. */ uint256 public epochLength; /** * If this block store doesn't start tracking a chain from origin, then the * starting height is the first block of the block chain where tracking * starts. For the purpose of Casper FFG it is considered the genesis. */ uint256 public startingHeight; /** * The address of the polling place address. Only the polling place may * call the justify method. */ address public pollingPlace; /** A mapping of block hashes to their reported headers. */ mapping (bytes32 => Block.Header) internal reportedBlocks; /** A mapping of block headers to their recorded checkpoints. */ mapping (bytes32 => Checkpoint) public checkpoints; /** The block hash of the highest finalised checkpoint. */ bytes32 internal head; /** * The current dynasty. The highest finalised checkpoint's dynasty is one * less. */ uint256 internal currentDynasty; /* Modifiers */ /** * @notice Functions with this modifier can only be called from the address * that is registered as the pollingPlace. */ modifier onlyPollingPlace() { require( msg.sender == pollingPlace, "This method must be called from the registered polling place." ); _; } /* Constructor */ /** * @notice Construct a new block store. Requires the block hash, state * root, and block height of an initial starting block. Depending * on which chain this store tracks, this could be a different * block than genesis. * * @param _coreIdentifier The core identifier identifies the chain that * this block store is tracking. * @param _epochLength The epoch length is the number of blocks from one * checkpoint to the next. * @param _pollingPlace The address of the polling place address. Only the * polling place may call the justify method. * @param _initialBlockHash The block hash of the initial starting block. * @param _initialStateRoot The state root of the initial starting block. * @param _initialBlockHeight The block height of the initial starting * block. */ constructor ( bytes20 _coreIdentifier, uint256 _epochLength, address _pollingPlace, bytes32 _initialBlockHash, bytes32 _initialStateRoot, uint256 _initialBlockHeight ) public { require( _epochLength > 0, "Epoch length must be greater zero." ); require( _pollingPlace != address(0), "Address of polling place must not be zero." ); require( _initialBlockHash != bytes32(0), "Initial block hash must not be zero." ); require( _initialStateRoot != bytes32(0), "Initial state root must not be zero." ); require( _initialBlockHeight.mod(_epochLength) == 0, "The initial block height is incompatible to the epoch length. Must be a multiple." ); coreIdentifier = _coreIdentifier; epochLength = _epochLength; pollingPlace = _pollingPlace; startingHeight = _initialBlockHeight; reportedBlocks[_initialBlockHash] = Block.Header( _initialBlockHash, bytes32(0), bytes32(0), address(0), _initialStateRoot, bytes32(0), bytes32(0), new bytes(0), uint256(0), _initialBlockHeight, uint64(0), uint64(0), uint256(0), new bytes(0), bytes32(0), uint256(0) ); checkpoints[_initialBlockHash] = Checkpoint( _initialBlockHash, bytes32(0), true, true, uint256(0) ); currentDynasty = uint256(1); } /* External Functions */ /** * @notice Returns the current head that is finalized in the block store. * * @return head_ The block hash of the head. */ function getHead() external view returns (bytes32 head_) { head_ = head; } /** * @notice Returns the current dynasty in the block store. * * @return dynasty_ The current dynasty. */ function getCurrentDynasty() external view returns (uint256 dynasty_) { dynasty_ = currentDynasty; } /** * @notice Report a block. A reported block header is stored and can then * be part of subsequent votes. * * @param _blockHeaderRlp The header of the reported block, RLP encoded. */ function reportBlock( bytes calldata _blockHeaderRlp ) external returns (bool success_) { Block.Header memory header = Block.decodeHeader(_blockHeaderRlp); success_ = reportBlock_(header); } /** * @notice Marks a block in the block store as justified. The source and * the target are required to know when a block is finalised. * Only the polling place may call this method. * * @param _sourceBlockHash The block hash of the source of the super- * majority link. * @param _targetBlockHash The block hash of the block that is justified. */ function justify( bytes32 _sourceBlockHash, bytes32 _targetBlockHash ) external onlyPollingPlace() { justify_(_sourceBlockHash, _targetBlockHash); } /** * @notice Returns the state root of the block that is stored at the given * height. The height must be <= the height of the latest finalised * checkpoint. Only state roots of checkpoints are known. * * @param _height The block height. * * @return The state root of the block at the given height. */ function stateRoot( uint256 _height ) external view returns (bytes32 stateRoot_) { require( _height <= reportedBlocks[head].height, "The state root is only known up to the height of the last finalised checkpoint." ); require( _height >= startingHeight, "The state root is only known from the starting height upwards." ); require( isAtCheckpointHeight(_height), "The height must be at a valid checkpoint height." ); /* * Walk backwards along the list of checkpoints as long as the height * of the checkpoint is greater than the target height. */ Checkpoint storage checkpoint = checkpoints[head]; while (reportedBlocks[checkpoint.blockHash].height > _height) { checkpoint = checkpoints[checkpoint.parent]; } /* * If the height of the resulting header is different from the height * that was given, then the given height was in between two justified * checkpoints. The height was skipped over when traversing the * recorded checkpoints. */ Block.Header storage header = reportedBlocks[checkpoint.blockHash]; require( header.height == _height, "State roots are only known for heights at justified checkpoints." ); stateRoot_ = header.stateRoot; } /** * @notice Returns the core identifier of the chain that this block store * tracks. * * @return coreIdentifier_ The core identifier of the tracked chain. */ function getCoreIdentifier() external view returns (bytes20 coreIdentifier_) { coreIdentifier_ = coreIdentifier; } /** * @notice Returns the height of the latest block that has been finalised. * * @return The height of the latest finalised block. */ function latestBlockHeight() external view returns (uint256 height_) { height_ = reportedBlocks[head].height; } /** * @notice Validates a given vote. For a vote to be valid: * - The transition object must be correct * - The hashes must exist * - The blocks of the hashes must be at checkpoint heights * - The source checkpoint must be justified * - The target must be higher than the current head * * @param _transitionHash The hash of the transition object of the related * meta-block. Depends on the source block. * @param _sourceBlockHash The hash of the source checkpoint of the vote. * @param _targetBlockHash The hash of teh target checkpoint of the vote. * * @return `true` if all of the above apply and therefore the vote is * considered valid by the block store. `false` otherwise. */ function isVoteValid( bytes32 _transitionHash, bytes32 _sourceBlockHash, bytes32 _targetBlockHash ) external view returns (bool valid_) { bool sourceValid; bool targetValid; bool transitionValid; (sourceValid,) = isSourceValid(_sourceBlockHash); (targetValid,) = isTargetValid( _sourceBlockHash, _targetBlockHash ); transitionValid = isValidTransitionHash( _transitionHash, _sourceBlockHash ); valid_ = sourceValid && targetValid && transitionValid; } /** * @notice Check, whether a block with a given block hash has been reported * before. * * @param _blockHash The hash of the block that should be checked. * * @return `true` if the block has been reported before. */ function isBlockReported( bytes32 _blockHash ) external view returns (bool reported_) { reported_ = isReported(_blockHash); } /** * @notice Returns transition object at the checkpoint defined at given * block hash. * * @dev It reverts transaction if checkpoint is not defined at given * block hash. * * @param _blockHash The hash of the block for which transition object * is requested. * * @return coreIdentifier_ The core identifier identifies the chain that * this block store is tracking. * @return dynasty_ Dynasty number of checkpoint for which transition * object is requested. * @return blockHash_ Hash of the block at checkpoint. */ function transitionObjectAtBlock( bytes32 _blockHash ) external view returns(bytes20 coreIdentifier_, uint256 dynasty_, bytes32 blockHash_) { require( isCheckpoint(_blockHash), "Checkpoint not defined for given block hash." ); coreIdentifier_ = coreIdentifier; dynasty_ = checkpoints[_blockHash].dynasty; blockHash_ = checkpoints[_blockHash].blockHash; } /** * @notice Returns transition hash at the checkpoint defined at the given * block hash. * * @dev It reverts transaction if checkpoint is not defined at given * block hash. * * @param _blockHash The hash of the block for which transition object * is requested. * * @return transitionHash_ Hash of the transition object at the checkpoint. */ function transitionHashAtBlock( bytes32 _blockHash ) external view returns(bytes32 transitionHash_) { require( isCheckpoint(_blockHash), "Checkpoint not defined for given block hash." ); transitionHash_ = MetaBlock.hashOriginTransition( checkpoints[_blockHash].dynasty, _blockHash, coreIdentifier ); } /* Internal Functions */ /** * @notice Marks a block in the block store as justified. The source and * the target are required to know when a block is finalised. * * @param _sourceBlockHash The block hash of the source of the super- * majority link. * @param _targetBlockHash The block hash of the block that is justified. */ function justify_( bytes32 _sourceBlockHash, bytes32 _targetBlockHash ) internal { bool blockValid; string memory reason; (blockValid, reason) = isSourceValid(_sourceBlockHash); require(blockValid, reason); (blockValid, reason) = isTargetValid( _sourceBlockHash, _targetBlockHash ); require(blockValid, reason); // Finalise first as it may increase the dynasty number of target. if (distanceInEpochs(_sourceBlockHash, _targetBlockHash) == 1) { finalise(_sourceBlockHash); } Checkpoint memory checkpoint = Checkpoint( _targetBlockHash, _sourceBlockHash, true, false, currentDynasty ); checkpoints[_targetBlockHash] = checkpoint; emit BlockJustified(_targetBlockHash); } /** * @notice Report a block. A reported block header is stored and can then * be part of subsequent votes. * * @param _header The header object of the reported block. */ function reportBlock_( Block.Header memory _header ) internal returns (bool success_) { reportedBlocks[_header.blockHash] = _header; emit BlockReported(_header.blockHash); success_ = true; } /** * @notice Returns true if the given block hash corresponds to a block that * has been reported. * * @param _blockHash The block hash to check. * * @return `true` if the given block hash was reported before. */ function isReported( bytes32 _blockHash ) internal view returns (bool wasReported_) { wasReported_ = reportedBlocks[_blockHash].blockHash == _blockHash; } /** * @notice Checks if a target block is valid. The same criteria apply for * voting and justifying, as justifying results from voting. * * @param _sourceBlockHash The hash of the corresponding source. * @param _targetBlockHash The hash of the potential target block. * * @return valid_ `true` if the given block hash is a valid target. * @return reason_ Gives the reason in case the block is not a valid target. */ function isTargetValid( bytes32 _sourceBlockHash, bytes32 _targetBlockHash ) internal view returns (bool valid_, string memory reason_) { if (!isReported(_targetBlockHash)) { valid_ = false; reason_ = "The target block must first be reported."; } else if (!isAtCheckpointHeight(_targetBlockHash)) { valid_ = false; reason_ = "The target must be at a height that is a multiple of the epoch length."; } else if (!isAboveHead(_targetBlockHash)) { valid_ = false; reason_ = "The target must be higher than the head."; } else if (!isAbove(_targetBlockHash, _sourceBlockHash)) { valid_ = false; reason_ = "The target must be above the source in height."; } else if ( isCheckpoint(_targetBlockHash) && !isParentCheckpoint(_sourceBlockHash, _targetBlockHash) ) { valid_ = false; reason_ = "The target must not be justified already with a different source."; } else { valid_ = true; } } /** * @notice Takes a transition hash and checks that the given block results * in the same transition hash. * * @param _transitionHash The hash to check. * @param _blockHash The block to test the hash against. * * @return `true` if the given block results in the same transition hash. */ function isValidTransitionHash( bytes32 _transitionHash, bytes32 _blockHash ) internal view returns (bool valid_) { bytes32 expectedHash = MetaBlock.hashOriginTransition( checkpoints[_blockHash].dynasty, _blockHash, coreIdentifier ); valid_ = _transitionHash == expectedHash; } /** * @notice Checks whether the given block hash represents a justified * checkpoint. * * @param _blockHash The block hash for which to check. * * @return isCheckpoint_ `true` if the block hash represents a justified * checkpoint. */ function isCheckpoint( bytes32 _blockHash ) internal view returns (bool isCheckpoint_) { isCheckpoint_ = checkpoints[_blockHash].blockHash == _blockHash; } /* Private Functions */ /** * @notice Finalises the checkpoint at the given block hash. Updates the * current head and dynasty if it is above the old head. * * @param _blockHash The checkpoint that shall be finalised. */ function finalise(bytes32 _blockHash) private { checkpoints[_blockHash].finalised = true; if (reportedBlocks[_blockHash].height > reportedBlocks[head].height) { head = _blockHash; currentDynasty = currentDynasty.add(1); } emit BlockFinalised(_blockHash); } /** * @notice Checks if a source block is valid. The same criteria apply for * voting and justifying, as justifying results from voting. * * @param _sourceBlockHash The hash of the potential source block. * * @return valid_ `true` if the given block hash is a valid source. * @return reason_ Gives the reason in case the block is not a valid source. */ function isSourceValid( bytes32 _sourceBlockHash ) private view returns (bool valid_, string memory reason_) { if(!isReported(_sourceBlockHash)) { valid_ = false; reason_ = "The source block must first be reported."; } else if (!isJustified(_sourceBlockHash)) { valid_ = false; reason_ = "The source block must first be justified."; } else { valid_ = true; } } /** * @notice Returns true if the given block hash corresponds to a checkpoint * that has been justified. * * @param _blockHash The block hash to check. * * @return `true` if there exists a justified checkpoint at the given block * hash. */ function isJustified( bytes32 _blockHash ) private view returns (bool justified_) { justified_ = checkpoints[_blockHash].justified; } /** * @notice Returns true if the given block hash corresponds to a block at a * valid checkpoint height (multiple of the epoch length). * * @param _blockHash The block hash to check. * * @return `true` if the given block hash is at a valid height. */ function isAtCheckpointHeight( bytes32 _blockHash ) private view returns (bool atCheckpointHeight_) { uint256 blockHeight = reportedBlocks[_blockHash].height; atCheckpointHeight_ = isAtCheckpointHeight(blockHeight); } /** * @notice Returns true if the given height corresponds to a valid * checkpoint height (multiple of the epoch length). * * @param _height The block height to check. * * @return `true` if the given block height is at a valid height. */ function isAtCheckpointHeight( uint256 _height ) private view returns (bool atCheckpointHeight_) { atCheckpointHeight_ = _height.mod(epochLength) == 0; } /** * @notice Returns true if the first block has a greater height than the * second block. * * @param _firstBlockHash Hash of the first block. * @param _secondBlockHash Hash of the second block. * * @return `true` if the first block has a greater height than the second * block. */ function isAbove( bytes32 _firstBlockHash, bytes32 _secondBlockHash ) private view returns (bool above_) { uint256 firstHeight = reportedBlocks[_firstBlockHash].height; uint256 secondHeight = reportedBlocks[_secondBlockHash].height; above_ = firstHeight > secondHeight; } /** * @notice Returns true if the given block hash corresponds to a block that * is above the currently highest finalised checkpoint. * * @param _blockHash The block hash to check. * * @return `true` if the given block hash is above the highest finalised * checkpoint. */ function isAboveHead( bytes32 _blockHash ) private view returns (bool aboveHead_) { aboveHead_ = isAbove(_blockHash, head); } /** * @notice Calculates and returns the number of epochs between two given * blocks. * * @param _lowerBlockHash Block hash of the lower block. * @param _higherBlockHash Block hash of the higher block. * * @return The distance between the given blocks in number of epochs. */ function distanceInEpochs( bytes32 _lowerBlockHash, bytes32 _higherBlockHash ) private view returns (uint256 epochDistance_) { /* * Other parts of the code checked that the blocks are at valid heights * and in the right order so this should always calculate correctly. */ uint256 lowerHeight = reportedBlocks[_lowerBlockHash].height; uint256 higherHeight = reportedBlocks[_higherBlockHash].height; uint256 blockDistance = higherHeight.sub(lowerHeight); epochDistance_ = blockDistance.div(epochLength); } /** * @notice Checks whether the older checkpoint is the parent of the * younger checkpoint. * * @param _olderBlockHash The block hash representing the older checkpoint. * @param _youngerBlockHash The block hash representing the younger * checkpoint. * * @return isParent_ `true` if the older is the parent of the younger. */ function isParentCheckpoint( bytes32 _olderBlockHash, bytes32 _youngerBlockHash ) private view returns (bool isParent_) { isParent_ = checkpoints[_youngerBlockHash].parent == _olderBlockHash; } }
Events */* Logs that a block has been reported. */* Logs that a block has been justified. */* Logs that a block has been finalised. */ Structs */* A casper FFG checkpoint. */
struct Checkpoint { bytes32 blockHash; bytes32 parent; bool justified; bool finalised; uint256 dynasty;
2,529,191
[ 1, 3783, 342, 20238, 716, 279, 1203, 711, 2118, 14010, 18, 342, 20238, 716, 279, 1203, 711, 2118, 2537, 939, 18, 342, 20238, 716, 279, 1203, 711, 2118, 727, 5918, 18, 342, 7362, 87, 342, 432, 8697, 457, 6512, 43, 9776, 18, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1958, 25569, 288, 203, 3639, 1731, 1578, 31493, 31, 203, 203, 3639, 1731, 1578, 982, 31, 203, 203, 3639, 1426, 2537, 939, 31, 203, 203, 3639, 1426, 727, 5918, 31, 203, 203, 3639, 2254, 5034, 19417, 689, 93, 31, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x12841eba50D1606507c09e4765F9083c680eeaE9/sources/Enigma1.sol
* @dev Interface of the ERC20 standard as defined in the EIP./
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); }
9,426,334
[ 1, 1358, 434, 326, 4232, 39, 3462, 4529, 487, 2553, 316, 326, 512, 2579, 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 ]
[ 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, 1560, 467, 654, 39, 3462, 288, 203, 1377, 445, 2078, 3088, 1283, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 1377, 445, 11013, 951, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 1377, 445, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 1377, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 1377, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 1377, 445, 7412, 1265, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 1377, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 203, 1377, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 460, 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 ]
/** * @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 transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) public balances; uint256 public totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, 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; } } contract Freeze is Ownable { using SafeMath for uint256; struct Group { address[] holders; uint until; } /** * @dev number of groups */ uint public groups; address[] public gofindAllowedAddresses; /** * @dev link group ID ---> Group structure */ mapping (uint => Group) public lockup; /** * @dev Check if holder under lock up */ modifier lockupEnded (address _holder, address _recipient) { uint index = indexOf(_recipient, gofindAllowedAddresses); if (index == 0) { bool freezed; uint groupId; (freezed, groupId) = isFreezed(_holder); if (freezed) { if (lockup[groupId-1].until < block.timestamp) _; else revert("Your holdings are freezed, wait until transfers become allowed"); } else _; } else _; } function addGofindAllowedAddress (address _newAddress) public onlyOwner returns (bool) { require(indexOf(_newAddress, gofindAllowedAddresses) == 0, "that address already exists"); gofindAllowedAddresses.push(_newAddress); return true; } /** * @param _holder address of token holder to check * @return bool - status of freezing and group */ function isFreezed (address _holder) public view returns(bool, uint) { bool freezed = false; uint i = 0; while (i < groups) { uint index = indexOf(_holder, lockup[i].holders); if (index == 0) { if (checkZeroIndex(_holder, i)) { freezed = true; i++; continue; } else { i++; continue; } } if (index != 0) { freezed = true; i++; continue; } i++; } if (!freezed) i = 0; return (freezed, i); } /** * @dev internal usage to get index of holder in group * @param element address of token holder to check * @param at array of addresses that is group of holders * @return index of holder at array */ function indexOf (address element, address[] memory at) internal pure returns (uint) { for (uint i=0; i < at.length; i++) { if (at[i] == element) return i; } return 0; } /** * @dev internal usage to check that 0 is 0 index or it means that address not exists * @param _holder address of token holder to check * @param lockGroup id of group to check address existance in it * @return true if holder at zero index at group false if holder doesn't exists */ function checkZeroIndex (address _holder, uint lockGroup) internal view returns (bool) { if (lockup[lockGroup].holders[0] == _holder) return true; else return false; } /** * @dev Will set group of addresses that will be under lock. When locked address can't do some actions with token * @param _holders array of addresses to lock * @param _until timestamp until that lock up will last * @return bool result of operation */ function setGroup (address[] memory _holders, uint _until) public onlyOwner returns (bool) { lockup[groups].holders = _holders; lockup[groups].until = _until; groups++; return true; } } /** * @dev This contract needed for inheritance of StandardToken interface, but with freezing modifiers. So, it have exactly same methods, but with lockupEnded(msg.sender) modifier. * @notice Inherit from it at SingleToken, to make freezing functionality works */ contract PausableToken is StandardToken, Freeze { function transfer( address _to, uint256 _value ) public lockupEnded(msg.sender, _to) returns (bool) { return super.transfer(_to, _value); } function transferFrom( address _from, address _to, uint256 _value ) public lockupEnded(msg.sender, _to) returns (bool) { return super.transferFrom(_from, _to, _value); } function approve( address _spender, uint256 _value ) public lockupEnded(msg.sender, _spender) returns (bool) { return super.approve(_spender, _value); } function increaseApproval( address _spender, uint256 _addedValue ) public lockupEnded(msg.sender, _spender) returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval( address _spender, uint256 _subtractedValue ) public lockupEnded(msg.sender, _spender) returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract SingleToken is PausableToken { string public constant name = "Gofind XR"; string public constant symbol = "XR"; uint32 public constant decimals = 8; uint256 public constant maxSupply = 13E16; constructor() public { totalSupply_ = totalSupply_.add(maxSupply); balances[msg.sender] = balances[msg.sender].add(maxSupply); } } contract Leasing is Ownable { using SafeMath for uint256; address XR = address(0); // testnet; SingleToken token; struct Stakes { uint256 stakingCurrency; // 0 for ETH 1 for XR uint256 stakingAmount; bytes coordinates; } struct Tenant { uint256 ids; Stakes[] stakes; } uint256 public tokenRate = 0; address public companyWallet = 0x553654Ad7808625B36F6AB29DdB41140300E024F; mapping (address => Tenant) public tenants; event Deposit(address indexed user, uint256 indexed amount, string indexed currency, uint256 timestamp); event Withdraw(address indexed user, uint256 indexed amount, string indexed currency, uint256 timestamp); constructor (address _xr) public { XR = _xr; } function () payable external { require(1 == 0); } /** * 0 - pre-ICO stage; Assuming 1 ETH = 150$; 1 ETH = 1500XR * 1 - ICO stage; Assuming 1 ETH = 150$; 1 ETH = 1000XR * 2 - post-ICO stage; Using price from exchange */ function projectStage (uint256 _stage) public onlyOwner returns (bool) { if (_stage == 0) tokenRate = 1500; if (_stage == 1) tokenRate = 1000; if (_stage == 2) tokenRate = 0; } /** * @dev Back-end will call that function to set Price from exchange * @param _rate the 1 ETH = _rate XR */ function oracleSetPrice (uint256 _rate) public onlyOwner returns (bool) { tokenRate = _rate; return true; } function stakeEth (bytes memory _coordinates) payable public returns (bool) { require(msg.value != 0); require(tokenRate != 0, "XR is on exchange, need to get price"); uint256 fee = msg.value * 10 / 110; address(0x553654Ad7808625B36F6AB29DdB41140300E024F).transfer(fee); uint256 afterFee = msg.value - fee; Stakes memory stake = Stakes(0, afterFee, _coordinates); tenants[msg.sender].stakes.push(stake); tenants[msg.sender].ids = tenants[msg.sender].ids.add(1); emit Deposit(msg.sender, afterFee, "ETH", block.timestamp); return true; } function returnEth (uint256 _id) public returns (bool) { require(_id != 0, "always invalid id"); require(tenants[msg.sender].ids != 0, "nothing to return"); require(tenants[msg.sender].ids >= _id, "no staking data with such id"); require(tenants[msg.sender].stakes[_id-1].stakingCurrency == 0, 'use returnXR'); require(tokenRate != 0, "XR is on exchange, need to get price"); uint256 indexify = _id-1; uint256 ethToReturn = tenants[msg.sender].stakes[indexify].stakingAmount; removeStakeById(indexify); ethToReturn = ethToReturn * 9 / 10; uint256 tokenAmountToReturn = ethToReturn * tokenRate / 10E9; require(SingleToken(XR).transferFrom(companyWallet, msg.sender, tokenAmountToReturn), "can not transfer tokens"); emit Withdraw(msg.sender, tokenAmountToReturn, "ETH", block.timestamp); return true; } function returnTokens (uint256 _id) public returns (bool){ require(_id != 0, "always invalid id"); require(tenants[msg.sender].ids != 0, "nothing to return"); require(tenants[msg.sender].ids >= _id, "no staking data with such id"); require(tenants[msg.sender].stakes[_id-1].stakingCurrency == 1, 'use returnETH'); uint256 indexify = _id-1; uint256 tokensToReturn = tenants[msg.sender].stakes[indexify].stakingAmount; SingleToken _instance = SingleToken(XR); removeStakeById(indexify); _instance.transfer(msg.sender, tokensToReturn); emit Withdraw(msg.sender, tokensToReturn, "XR", block.timestamp); return true; } function stakeTokens (uint256 amount, bytes memory _coordinates) public returns (bool) { require(amount != 0, "staking can not be 0"); Stakes memory stake = Stakes(1, amount, _coordinates); tenants[msg.sender].stakes.push(stake); tenants[msg.sender].ids = tenants[msg.sender].ids.add(1); require(SingleToken(XR).transferFrom(msg.sender, address(this), amount), "can not transfer tokens"); emit Deposit(msg.sender, amount, "XR", block.timestamp); return true; } function removeStakeById (uint256 _id) internal returns (bool) { for (uint256 i = _id; i < tenants[msg.sender].stakes.length-1; i++) { tenants[msg.sender].stakes[i] = tenants[msg.sender].stakes[i+1]; } tenants[msg.sender].stakes.length--; tenants[msg.sender].ids = tenants[msg.sender].ids.sub(1); return true; } function getStakeById (uint256 _id) public view returns (string memory, uint256, bytes memory) { require(_id != 0, "always invalid id"); require(tenants[msg.sender].ids != 0, "no staking data"); require(tenants[msg.sender].ids >= _id, "no staking data with such id"); uint256 indexify = _id-1; string memory currency; if (tenants[msg.sender].stakes[indexify].stakingCurrency == 0) currency = "ETH"; else currency = "XR"; return (currency, tenants[msg.sender].stakes[indexify].stakingAmount, tenants[msg.sender].stakes[indexify].coordinates); } function getStakingStructLength () public view returns (uint256) { return tenants[msg.sender].stakes.length; } }
* @dev Back-end will call that function to set Price from exchange @param _rate the 1 ETH = _rate XR/
function oracleSetPrice (uint256 _rate) public onlyOwner returns (bool) { tokenRate = _rate; return true; }
13,019,273
[ 1, 2711, 17, 409, 903, 745, 716, 445, 358, 444, 20137, 628, 7829, 225, 389, 5141, 326, 404, 512, 2455, 273, 389, 5141, 1139, 54, 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, 565, 445, 20865, 694, 5147, 261, 11890, 5034, 389, 5141, 13, 1071, 1338, 5541, 1135, 261, 6430, 13, 288, 203, 3639, 1147, 4727, 273, 389, 5141, 31, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 377, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; library SafeMath { function multiplication(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } // integer division of two numbers, truncating the quotient function division(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } // subtracts two numbers , throws an overflow function subtraction(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function addition(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** ownable contract has an owner address & provides basic authorization control functions, this simplifies the implementation of the user permission **/ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); // constructor sets the original owner of the contract to the sender account constructor() public { owner = msg.sender; } // throws if called by any account other than the owner modifier onlyOwner() { require(msg.sender == owner); _; } /** allows the current owner to transfer control of the contract to a new owner newOwner: the address to transfer ownership to **/ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // ERC20 basic interface 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); } 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); } // basic version of standard token with no allowances contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; // total numbers of tokens in existence function totalSupply() public view returns (uint256) { return totalSupply_; } /** _to: address to transfer to _value: amoutn to be transferred **/ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].subtraction(_value); balances[_to] = balances[_to].addition(_value); emit Transfer(msg.sender, _to, _value); return true; } /** gets the balance of the specified address _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) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping(address => mapping (address => uint256)) internal allowed; /** transfers tokens from one address to another _from address: address which you want to send tokens from _to address: address which you want to transfer to _value uint256: 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].subtraction(_value); balances[_to] = balances[_to].addition(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].subtraction(_value); emit Transfer(_from, _to, _value); return true; } /** approve the passed address to spend the specific amount of tokens on behalf of msg.sender _spender: address which will spend the funds _value: 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; } /** to check the amount of tokens that an owner allowed to a _spender _owner address: address which owns the funds _spender address: address which will spend the funds return: specifying the amount of tokens still available for the spender **/ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** increase amount of tokens that an owner allowed to a _spender _spender: address which will spend the funds _addedValue: 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].addition(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } 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.subtraction(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract Configurable { uint256 public constant cap = 1000000*10**18; uint256 public constant basePrice = 100*10**18; // tokens per 1 ETH uint256 public tokensSold = 0; uint256 public constant tokenReserve = 1000000*10**18; uint256 public remainingTokens = 0; } contract CrowdSaleToken is StandardToken, Configurable, Ownable { // enum of current crowdSale state enum Stages { none, icoStart, icoEnd } Stages currentStage; // constructor of CrowdSaleToken constructor() public { currentStage = Stages.none; balances[owner] = balances[owner].addition(tokenReserve); totalSupply_ = totalSupply_.addition(tokenReserve); remainingTokens = cap; emit Transfer(address(this), owner, tokenReserve); } // fallback function to send ether too for CrowdSale function() public payable { require(currentStage == Stages.icoStart); require(msg.value > 0); require(remainingTokens > 0); uint256 weiAmount = msg.value; // calculate tokens to sell uint256 tokens = weiAmount.multiplication(basePrice).division(1 ether); uint256 returnWei = 0; if(tokensSold.addition(tokens) > cap) { uint256 newTokens = cap.subtraction(tokensSold); uint256 newWei = newTokens.division(basePrice).multiplication(1 ether); returnWei = weiAmount.subtraction(newWei); weiAmount = newWei; tokens = newTokens; } tokensSold = tokensSold.addition(tokens); // increment raised amount remainingTokens = cap.subtraction(tokensSold); if(returnWei > 0) { msg.sender.transfer(returnWei); emit Transfer(address(this), msg.sender, returnWei); } balances[msg.sender] = balances[msg.sender].addition(tokens); emit Transfer(address(this), msg.sender, tokens); totalSupply_ = totalSupply_.addition(tokens); owner.transfer(weiAmount); // send money to owner } // starts the ICO function startIco() public onlyOwner { require(currentStage != Stages.icoEnd); currentStage = Stages.icoStart; } // ends the ICO function endIco() internal { currentStage = Stages.icoEnd; // transfer any remaining tokens if(remainingTokens > 0) { balances[owner] = balances[owner].addition(remainingTokens); } // transfer any remaining ETH to the owner owner.transfer(address(this).balance); } // finishes the ICO function finalizeIco() public onlyOwner { require(currentStage != Stages.icoEnd); endIco(); } } // Contract to create the token contract MementoToken is CrowdSaleToken { string public constant name = "Memento"; string public constant symbol = "MTX"; uint32 public constant decimals = 18; }
subtracts two numbers , throws an overflow
function subtraction(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; }
13,120,442
[ 1, 1717, 1575, 87, 2795, 5600, 269, 1216, 392, 9391, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 720, 25693, 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, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x53c55bB901812551aa36cbf022B5df35B24C9f59/sources/TokenService.sol
TODO think about try catch in transfers
function _transferSafe( ETypes.AssetItem memory _assetItem, address _from, address _to ) internal virtual returns (uint256 _transferedValue){ uint256 balanceBefore; if (_assetItem.asset.assetType == ETypes.AssetType.NATIVE) { balanceBefore = _to.balance; require(success, "transfer failed"); _transferedValue = _to.balance - balanceBefore; balanceBefore = IERC20Extended(_assetItem.asset.contractAddress).balanceOf(_to); if (_from == address(this)){ IERC20Extended(_assetItem.asset.contractAddress).safeTransfer(_to, _assetItem.amount); IERC20Extended(_assetItem.asset.contractAddress).safeTransferFrom(_from, _to, _assetItem.amount); } _transferedValue = IERC20Extended(_assetItem.asset.contractAddress).balanceOf(_to) - balanceBefore; } else if (_assetItem.asset.assetType == ETypes.AssetType.ERC721 && IERC721Mintable(_assetItem.asset.contractAddress).ownerOf(_assetItem.tokenId) == _from) { balanceBefore = IERC721Mintable(_assetItem.asset.contractAddress).balanceOf(_to); IERC721Mintable(_assetItem.asset.contractAddress).transferFrom(_from, _to, _assetItem.tokenId); if (IERC721Mintable(_assetItem.asset.contractAddress).ownerOf(_assetItem.tokenId) == _to && IERC721Mintable(_assetItem.asset.contractAddress).balanceOf(_to) - balanceBefore == 1 ) { _transferedValue = 1; } balanceBefore = IERC1155Mintable(_assetItem.asset.contractAddress).balanceOf(_to, _assetItem.tokenId); IERC1155Mintable(_assetItem.asset.contractAddress).safeTransferFrom(_from, _to, _assetItem.tokenId, _assetItem.amount, ""); _transferedValue = IERC1155Mintable(_assetItem.asset.contractAddress).balanceOf(_to, _assetItem.tokenId) - balanceBefore; revert UnSupportedAsset(_assetItem); } return _transferedValue; }
2,619,152
[ 1, 6241, 282, 15507, 2973, 775, 1044, 316, 29375, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 13866, 9890, 12, 203, 3639, 512, 2016, 18, 6672, 1180, 3778, 389, 9406, 1180, 16, 203, 3639, 1758, 389, 2080, 16, 203, 3639, 1758, 389, 869, 203, 565, 262, 2713, 5024, 1135, 261, 11890, 5034, 389, 13866, 329, 620, 15329, 203, 3639, 2254, 5034, 11013, 4649, 31, 203, 3639, 309, 261, 67, 9406, 1180, 18, 9406, 18, 9406, 559, 422, 512, 2016, 18, 6672, 559, 18, 50, 12992, 13, 288, 203, 5411, 11013, 4649, 273, 389, 869, 18, 12296, 31, 203, 5411, 2583, 12, 4768, 16, 315, 13866, 2535, 8863, 203, 5411, 389, 13866, 329, 620, 273, 389, 869, 18, 12296, 300, 11013, 4649, 31, 203, 540, 203, 5411, 11013, 4649, 273, 467, 654, 39, 3462, 11456, 24899, 9406, 1180, 18, 9406, 18, 16351, 1887, 2934, 12296, 951, 24899, 869, 1769, 203, 5411, 309, 261, 67, 2080, 422, 1758, 12, 2211, 3719, 95, 203, 7734, 467, 654, 39, 3462, 11456, 24899, 9406, 1180, 18, 9406, 18, 16351, 1887, 2934, 4626, 5912, 24899, 869, 16, 389, 9406, 1180, 18, 8949, 1769, 203, 7734, 467, 654, 39, 3462, 11456, 24899, 9406, 1180, 18, 9406, 18, 16351, 1887, 2934, 4626, 5912, 1265, 24899, 2080, 16, 389, 869, 16, 389, 9406, 1180, 18, 8949, 1769, 203, 5411, 289, 377, 203, 5411, 389, 13866, 329, 620, 273, 467, 654, 39, 3462, 11456, 24899, 9406, 1180, 18, 9406, 18, 16351, 1887, 2934, 12296, 951, 24899, 869, 13, 300, 11013, 4649, 31, 203, 540, 203, 3639, 289, 469, 309, 261, 67, 9406, 1180, 18, 9406, 18, 9406, 559, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; contract realEstate { // Declare state variables in this section uint8 public avgBlockTime; // Avg block time in seconds. uint8 private decimals; // Decimals of our Shares. Has to be 0. uint8 public tax; // Can Preset Tax rate in constructor. To be changed by government only. uint8 public rentalLimitMonths; // Months any tenant can pay rent in advance for. uint256 public rentalLimitBlocks; // ...in Blocks. uint256 constant private MAX_UINT256 = 2**256 - 1; // Very large number. uint256 public totalSupply; // By default 100 for 100% ownership. Can be changed. uint256 public totalSupply2; // Only Ether incoming of multiples of this variable will be allowed. This way we can have two itterations of divisions through totalSupply without remainder. There is no Float in ETH, so we need to prevent remainders in division. E.g. 1. iteration (incoming ether value = MultipleOfTokenSupplyPower2) / totalSupply * uint (desired percentage); 2nd iteration ( ether value = MultipleOfTokenSupplyPower) / totalSupply * uint (desired percentage); --> no remainder uint256 public rentPer30Day; // rate charged by mainPropertyOwner for 30 Days of rent. uint256 public accumulated; // Globally accumulated funds not distributed to stakeholder yet excluding gov. uint256 public blocksPer30Day; // Calculated from avgBlockTime. Acts as tiem measurement for rent. uint256 public rentalBegin; // begin of rental(in blocknumber) uint256 public occupiedUntill; // Blocknumber untill the Property is occupied. uint256 private _taxdeduct; // ammount of tax to be paid for incoming ether. string public name; // The name of our house (token). Can be determined in Constructor _propertyID string public symbol; // The Symbol of our house (token). Can be determined in Constructor _propertySymbol address public gov = msg.sender; // Government will deploy contract. address public mainPropertyOwner; // mainPropertyOwner can change tenant.Can become mainPropertyOwner by claimOwnership if owning > 51% of token. address public tenant; // only tenant can pay the Smart Contract. address[] public stakeholders; // Array of stakeholders. Government can addStakeholder or removeStakeholder. Recipient of token needs to be isStakeholder = true to be able to receive token. mainPropertyOwner & Government are stakeholder by default. mapping (address => uint256) public revenues; // Distributed revenue account ballance for each stakeholder including gov. mapping (address => uint256) public shares; // Addresses mapped to token ballances. mapping (address => mapping (address => uint256)) private allowed; // All addresses allow unlimited token withdrawals by the government. mapping (address => uint256) public rentpaidUntill; //Blocknumber untill the rent is paid. mapping (address => uint256) public sharesOffered; //Number of Shares a Stakeholder wants to offer to other stakeholders mapping (address => uint256) public shareSellPrice; // Price per Share a Stakeholder wants to have when offering to other Stakeholders // Define events event ShareTransfer(address indexed from, address indexed to, uint256 shares); event Seizure(address indexed seizedfrom, address indexed to, uint256 shares); event ChangedTax(uint256 NewTax); event MainPropertyOwner(address NewMainPropertyOwner); event NewStakeHolder(address StakeholderAdded); event CurrentlyEligibletoPayRent(address Tenant); event PrePayRentLimit (uint8 Months); event AvgBlockTimeChangedTo(uint8 s); event RentPer30DaySetTo (uint256 WEIs); event StakeHolderBanned (address banned); event RevenuesDistributed (address shareholder, uint256 gained, uint256 total); event Withdrawal (address shareholder, uint256 withdrawn); event Rental (uint256 date, address renter, uint256 rentPaid, uint256 tax, uint256 distributableRevenue, uint256 rentedFrom, uint256 rentedUntill); event SharesOffered(address Seller, uint256 AmmountShares, uint256 PricePerShare); event SharesSold(address Seller, address Buyer, uint256 SharesSold,uint256 PricePerShare); constructor (string memory _propertyID, string memory _propertySymbol, address _mainPropertyOwner, uint8 _tax, uint8 _avgBlockTime) { shares[_mainPropertyOwner] = 100; //one main Shareholder to be declared by government to get all initial shares. totalSupply = 100; //supply fixed to 100 for now, Can also work with 10, 1000, 10 000... totalSupply2 = totalSupply**2; //above to the power of 2 name = _propertyID; decimals = 0; symbol = _propertySymbol; tax = _tax; // set tax for deduction upon rental payment mainPropertyOwner = _mainPropertyOwner; stakeholders.push(gov); //gov & mainPropertyOwner pushed to stakeholdersarray upon construction to allow payout and transfers stakeholders.push(mainPropertyOwner); allowed[mainPropertyOwner][gov] = MAX_UINT256; //government can take all token from mainPropertyOwner with seizureFrom avgBlockTime = _avgBlockTime; // 13s recomended. Our representation of Time. Can be changed by gov with function SetAvgBlockTime blocksPer30Day = 60*60*24*30/avgBlockTime; rentalLimitMonths = 12; //rental limit in months can be changed by mainPropertyOwner rentalLimitBlocks = rentalLimitMonths * blocksPer30Day; } // Define modifiers in this section modifier onlyGov{ require(msg.sender == gov); _; } modifier onlyPropOwner{ require(msg.sender == mainPropertyOwner); _; } modifier isMultipleOf{ require(msg.value % totalSupply2 == 0); //modulo operation, only allow ether ammounts that are multiles of totalsupply^2. This is because there is no float and we will divide incoming ammounts two times to split it up and we do not want a remainder. _; } modifier eligibleToPayRent{ //only one tenant at a time can be allowed to pay rent. require(msg.sender == tenant); _; } // Define functions in this section //viewable functions function showSharesOf(address _owner) public view returns (uint256 balance) { //shows shares for each address. return shares[_owner]; } function isStakeholder(address _address) public view returns(bool, uint256) { //shows whether someone is a stakeholder. for (uint256 s = 0; s < stakeholders.length; s += 1){ if (_address == stakeholders[s]) return (true, s); } return (false, 0); } function currentTenantCheck (address _tenantcheck) public view returns(bool,uint256){ //only works if from block.number on there is just one tenant, otherwise tells untill when rent is paid. require(occupiedUntill == rentpaidUntill[tenant], "The entered address is not the current tenant"); if (rentpaidUntill[_tenantcheck] > block.number){ uint256 daysRemaining = (rentpaidUntill[_tenantcheck] - block.number)*avgBlockTime/86400; //86400 seconds in a day. return (true, daysRemaining); //gives tenant paid status true or false and days remaining } else return (false, 0); } //functions of government function addStakeholder(address _stakeholder) public onlyGov { //can add more stakeholders. (bool _isStakeholder, ) = isStakeholder(_stakeholder); if (!_isStakeholder) stakeholders.push(_stakeholder); allowed[_stakeholder][gov] = MAX_UINT256; //unlimited allowance to withdraw Shares for Government --> Government can seize shares. emit NewStakeHolder (_stakeholder); } function banStakeholder(address _stakeholder) public onlyGov { // can remove stakeholder from stakeholders array and... (bool _isStakeholder, uint256 s) = isStakeholder(_stakeholder); if (_isStakeholder){ stakeholders[s] = stakeholders[stakeholders.length - 1]; stakeholders.pop(); seizureFrom (_stakeholder, msg.sender,shares[_stakeholder]); //...seizes shares emit StakeHolderBanned(_stakeholder); } } function setTax (uint8 _x) public onlyGov { //set new tax rate (for incoming rent being taxed with %) require( _x <= 100, "Valid tax rate (0% - 100%) required" ); tax = _x; emit ChangedTax (tax); } function SetAvgBlockTime (uint8 _sPerBlock) public onlyGov{ //we do not have a forgery proof time measurement in Ethereum. Therefore we count the ammount of blocks. One Block equals to 13s but this can be changed by the government. require(_sPerBlock > 0, "Please enter a Value above 0"); avgBlockTime = _sPerBlock; blocksPer30Day = (60*60*24*30) / avgBlockTime; emit AvgBlockTimeChangedTo (avgBlockTime); } function distribute() public onlyGov { // accumulated funds are distributed into revenues array for each stakeholder according to how many shares are held by shareholders. Additionally, government gets tax revenues upon each rental payment. uint256 _accumulated = accumulated; for (uint256 s = 0; s < stakeholders.length; s += 1){ address stakeholder = stakeholders[s]; uint256 _shares = showSharesOf(stakeholder); uint256 ethertoreceive = (_accumulated/(totalSupply))*_shares; accumulated = accumulated - ethertoreceive; revenues[stakeholder] = revenues[stakeholder] + ethertoreceive; emit RevenuesDistributed(stakeholder,ethertoreceive, revenues[stakeholder]); } } //hybrid Governmental function seizureFrom(address _from, address _to, uint256 _value) public returns (bool success) { //government has unlimited allowance, therefore can seize all assets from every stakeholder. Function also used to buyShares from Stakeholder. uint256 allowance = allowed[_from][msg.sender]; require(shares[_from] >= _value && allowance >= _value); shares[_to] += _value; shares[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Seizure(_from, _to, _value); return true; } //mainPropertyOwner functions function canPayRent(address _tenant) public onlyPropOwner{ //decide who can pay rent in the future tenant = _tenant; emit CurrentlyEligibletoPayRent (tenant); } function limitadvancedrent(uint8 _monthstolimit) onlyPropOwner public{ //mainPropertyOwner can decide how many months in advance the property can be rented out max rentalLimitBlocks = _monthstolimit *blocksPer30Day; emit PrePayRentLimit (_monthstolimit); } function setRentper30Day(uint256 _rent) public onlyPropOwner{ //mainPropertyOwner can set rentPer30Day in WEI rentPer30Day = _rent; emit RentPer30DaySetTo (rentPer30Day); } //Stakeholder functions function offerShares(uint256 _sharesOffered, uint256 _shareSellPrice) public{ //Stakeholder can offer # of Shares for Price per Share (bool _isStakeholder, ) = isStakeholder(msg.sender); require(_isStakeholder); require(_sharesOffered <= shares[msg.sender]); sharesOffered[msg.sender] = _sharesOffered; shareSellPrice[msg.sender] = _shareSellPrice; emit SharesOffered(msg.sender, _sharesOffered, _shareSellPrice); } function buyShares (uint256 _sharesToBuy, address payable _from) public payable{ //Stakeholder can buy shares from seller for sellers price * ammount of shares (bool _isStakeholder, ) = isStakeholder(msg.sender); require(_isStakeholder); require(msg.value == _sharesToBuy * shareSellPrice[_from] && _sharesToBuy <= sharesOffered[_from] && _sharesToBuy <= shares[_from] &&_from != msg.sender); // allowed[_from][msg.sender] = _sharesToBuy; seizureFrom(_from, msg.sender, _sharesToBuy); sharesOffered[_from] -= _sharesToBuy; _from.transfer(msg.value); emit SharesSold(_from, msg.sender, _sharesToBuy,shareSellPrice[_from]); } function transfer(address _recipient, uint256 _amount) public returns (bool) { //transfer of Token, requires isStakeholder (bool isStakeholderX, ) = isStakeholder(_recipient); require(isStakeholderX); require(shares[msg.sender] >= _amount); shares[msg.sender] -= _amount; shares[_recipient] += _amount; emit ShareTransfer(msg.sender, _recipient, _amount); return true; } function claimOwnership () public { //claim main property ownership require(shares[msg.sender] > (totalSupply /2) && msg.sender != mainPropertyOwner,"Error. You do not own more than 50% of the property tokens or you are the main owner allready"); mainPropertyOwner = msg.sender; emit MainPropertyOwner(mainPropertyOwner); } function withdraw() payable public { //revenues can be withdrawn from individual shareholders (government can too withdraw its own revenues) uint256 revenue = revenues[msg.sender]; revenues[msg.sender] = 0; (msg.sender).transfer(revenue); emit Withdrawal(msg.sender, revenue); } //renter function function payRent(uint8 _months) public payable isMultipleOf eligibleToPayRent{ //needs to be eligible to pay rent uint256 _rentdue = _months * rentPer30Day; uint256 _additionalBlocks = _months * blocksPer30Day; require (msg.value == _rentdue && block.number + _additionalBlocks < block.number + rentalLimitBlocks); //sent in Ether has to be _rentdue; additional blocks for rental cannot be higher than limit. _taxdeduct = (msg.value/totalSupply * tax); //deduct taxes accumulated += (msg.value - _taxdeduct); //accumulate revenues revenues[gov] += _taxdeduct; //accumulate taxes if (rentpaidUntill[tenant] == 0 && occupiedUntill < block.number) { //hasn't rented yet & flat is empty rentpaidUntill[tenant] = block.number + _additionalBlocks; //rents from now on rentalBegin = block.number; } else if (rentpaidUntill[tenant] == 0 && occupiedUntill > block.number) { //hasn't rented yet & flat is occupied rentpaidUntill[tenant] = occupiedUntill + _additionalBlocks; //rents from when it is free rentalBegin = occupiedUntill; } else if ( rentpaidUntill[tenant] > block.number) { //is renting, contract is runing rentpaidUntill[tenant] += _additionalBlocks; //rents from when it is free rentalBegin = occupiedUntill; } else if (rentpaidUntill[tenant] < block.number && occupiedUntill>block.number) { //has rented before & flat is occupied rentpaidUntill[tenant] = occupiedUntill +_additionalBlocks; //rents from when it is free rentalBegin = occupiedUntill; } else if (rentpaidUntill[tenant] < block.number && occupiedUntill<block.number) { //has rented before & flat is empty rentpaidUntill[tenant] = block.number + _additionalBlocks; //rents from now on rentalBegin = block.number; //has lived before and flat is empgy } occupiedUntill = rentpaidUntill[tenant]; //set new occupiedUntill emit Rental (block.timestamp, msg.sender, msg.value, _taxdeduct, (msg.value - _taxdeduct), rentalBegin, occupiedUntill); } //falback receive () external payable { //fallback function returns ether back to origin (msg.sender).transfer(msg.value); } }
The name of our house (token). Can be determined in Constructor _propertyID
string public name;
5,401,230
[ 1, 1986, 508, 434, 3134, 23867, 261, 2316, 2934, 4480, 506, 11383, 316, 11417, 389, 4468, 734, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 1080, 1071, 508, 31, 21394, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "./Proposal.sol"; import "./interfaces/IProposal.sol"; import "./interfaces/ICampaign.sol"; import "./interfaces/ICampaignFactory.sol"; /** * @title CampaignFactory * @notice The Campaign factory is used for save the list of campaign deployed and also deploy proposal contract * @dev Inherit of for the CampaignFactory Interface */ contract CampaignFactory is ICampaignFactory { uint128 public campaignCounter = 1; address public owner; address public campaignCreatorContract; mapping(uint128 => address) public deployedCampaigns; mapping(address => uint128) public campaignToId; constructor(){ owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner, "!Not Authorized"); _; } /** * @inheritdoc ICampaignFactory */ function addCampaign(ICampaign _newCampaign) external override { require(msg.sender == campaignCreatorContract, "!Not Authorized"); deployedCampaigns[campaignCounter] = address(_newCampaign); campaignToId[address(_newCampaign)] = campaignCounter; campaignCounter++; } /** * @inheritdoc ICampaignFactory */ function deleteCampaign() public override { require(campaignToId[msg.sender] !=0 , "!Err: Not exist"); uint128 _indexToSwap = campaignToId[msg.sender]; if (_indexToSwap != campaignCounter - 1) { deployedCampaigns[_indexToSwap] = deployedCampaigns[campaignCounter - 1]; campaignToId[deployedCampaigns[campaignCounter-1]] = _indexToSwap; } delete deployedCampaigns[campaignCounter - 1]; delete campaignToId[msg.sender]; campaignCounter--; } /** * @inheritdoc ICampaignFactory */ function deployProposalContract(address _manager) external override { require(campaignToId[msg.sender] != 0, "!Not Authorized"); IProposal _proposalContract = new Proposal(msg.sender, _manager); ICampaign(msg.sender).setProposal(address(_proposalContract)); } /** * @inheritdoc ICampaignFactory */ function updateOwner(address _newOwner) external override onlyOwner() { owner = _newOwner; } /** * @inheritdoc ICampaignFactory */ function setCampaignCreator(address _campaignCreatorContract) external override onlyOwner() { campaignCreatorContract = _campaignCreatorContract; } }
* @inheritdoc ICampaignFactory/
function addCampaign(ICampaign _newCampaign) external override { require(msg.sender == campaignCreatorContract, "!Not Authorized"); deployedCampaigns[campaignCounter] = address(_newCampaign); campaignToId[address(_newCampaign)] = campaignCounter; campaignCounter++; }
1,821,003
[ 1, 36, 10093, 467, 13432, 1733, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 13432, 12, 2871, 5415, 389, 2704, 13432, 13, 3903, 3849, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 8965, 10636, 8924, 16, 17528, 1248, 6712, 1235, 8863, 203, 3639, 19357, 13432, 87, 63, 14608, 4789, 65, 273, 1758, 24899, 2704, 13432, 1769, 203, 3639, 8965, 774, 548, 63, 2867, 24899, 2704, 13432, 25887, 273, 8965, 4789, 31, 203, 3639, 8965, 4789, 9904, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./lib/BEP20.sol"; import "../../service/ServicePayer.sol"; import "../../utils/GeneratorCopyright.sol"; /** * @title SimpleBEP20 * @author BEP20 Generator (https://vittominacori.github.io/bep20-generator) * @dev Implementation of the SimpleBEP20 */ contract SimpleBEP20 is BEP20, ServicePayer, GeneratorCopyright("v2.0.0") { constructor ( string memory name, string memory symbol, uint256 initialBalance, address payable feeReceiver ) BEP20(name, symbol) ServicePayer(feeReceiver, "SimpleBEP20") payable { require(initialBalance > 0, "SimpleBEP20: supply cannot be zero"); _mint(_msgSender(), initialBalance); } }
* @title SimpleBEP20 @dev Implementation of the SimpleBEP20/
contract SimpleBEP20 is BEP20, ServicePayer, GeneratorCopyright("v2.0.0") { constructor ( string memory name, string memory symbol, uint256 initialBalance, address payable feeReceiver ) BEP20(name, symbol) ServicePayer(feeReceiver, "SimpleBEP20") payable { require(initialBalance > 0, "SimpleBEP20: supply cannot be zero"); _mint(_msgSender(), initialBalance); } }
14,124,071
[ 1, 5784, 5948, 52, 3462, 225, 25379, 434, 326, 4477, 5948, 52, 3462, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4477, 5948, 52, 3462, 353, 9722, 52, 3462, 16, 1956, 52, 1773, 16, 10159, 2951, 4083, 2932, 90, 22, 18, 20, 18, 20, 7923, 288, 203, 203, 565, 3885, 261, 203, 3639, 533, 3778, 508, 16, 203, 3639, 533, 3778, 3273, 16, 203, 3639, 2254, 5034, 2172, 13937, 16, 203, 3639, 1758, 8843, 429, 14036, 12952, 203, 565, 262, 203, 3639, 9722, 52, 3462, 12, 529, 16, 3273, 13, 203, 3639, 1956, 52, 1773, 12, 21386, 12952, 16, 315, 5784, 5948, 52, 3462, 7923, 203, 3639, 8843, 429, 203, 203, 565, 288, 203, 3639, 2583, 12, 6769, 13937, 405, 374, 16, 315, 5784, 5948, 52, 3462, 30, 14467, 2780, 506, 3634, 8863, 203, 203, 3639, 389, 81, 474, 24899, 3576, 12021, 9334, 2172, 13937, 1769, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; contract Cicada_3301 { struct Obj { uint _prev; uint _next; } // User // defination enum UserType {user, admin, super_admin} struct Person { string name; // Name uint adr; // Aadhar number UserType utype; // User type // Properties Associated with a user mapping(uint => Obj) properties; uint propertiesTop; // Property buyRequest mapping(uint => Obj) requestList; uint requestListTop; } // User decleration bool super_admin_created = false; // Create the first User as SuperAdmin mapping(address => Person) users; mapping(uint => address) aadhaarmap; // Property // defination struct PropertyDetail { string _info; // information about the property // string _data_hash; // ipfs hash of associated data uint _trans_id; // Transaction id } // defination // mapping all properties mapping(uint => PropertyDetail) properties; uint private property_counter = 1; // Tranction enum TranctionState {requested, approved, rejected} // Tranction block struct Tranction { address _from; // sender address _to; // buyer uint256 _prev; // previous Tranction block id uint256 _prop; // property id { any property } TranctionState _state; // state of Tranction address approved_by; string _ipfs_hash; } // mapping all the Tranction records mapping(uint256 => Tranction) recordlist; mapping(uint256 => Obj) requestList; uint256 requestListTop = 0; uint256 requestListCounter = 1; // drver functions // Admin require modifier isAdmin() { if(users[msg.sender].utype == UserType.admin || users[msg.sender].utype == UserType.super_admin) _; } // Super Admin require modifier isSuperAdmin() { if(users[msg.sender].utype == UserType.super_admin) _; } //User Logic // adding the user with services function addUser(string memory _name, uint _adr, address _userId) public { // check if the user is previously registerd if(_adr != uint(0) && aadhaarmap[_adr] == address(0)) { users[_userId].name = _name; users[_userId].adr = _adr; users[_userId].utype = UserType.user; // set initial pointers users[_userId].requestListTop = 0; users[_userId].propertiesTop = 0; aadhaarmap[_adr] = _userId; // make the first user super admin if(super_admin_created == false) { users[_userId].utype = UserType.super_admin; super_admin_created = true; } } } function changeUserDomain(address _userId, UserType _utype) public isSuperAdmin { require(_utype != UserType.super_admin); users[_userId].utype = _utype; } // add property in requestList {if the user is requested to sell there property} function addPropertyRequest(address _buyer_id, uint _prop_id, string memory ipfs_hash) public { uint _req_id = addRecord(msg.sender, _buyer_id, _prop_id, ipfs_hash); // add the pointer of the transection request to the requestList users[_buyer_id].requestList[users[_buyer_id].requestListTop]._next = _req_id; // link the top requestList block to the previous block users[_buyer_id].requestList[_req_id]._prev = users[_buyer_id].requestListTop; // make the top pointer as the end of the list users[_buyer_id].requestList[_req_id]._next = 0; // save the pointer to the top of the requestList users[_buyer_id].requestListTop = _req_id; } // remove the property request from the requestList function removePropertyRequest(address _userId, uint _req_id) public { // shift the pointer to the previous block if - removing the top block if(users[_userId].requestListTop == _req_id) users[_userId].requestListTop = users[_userId].requestList[_req_id]._prev; // link the previous and next block users[_userId].requestList[users[_userId].requestList[_req_id]._prev]._next = users[_userId].requestList[_req_id]._next; users[_userId].requestList[users[_userId].requestList[_req_id]._next]._prev = users[_userId].requestList[_req_id]._prev; // clear the current block users[_userId].requestList[_req_id]._next = 0; users[_userId].requestList[_req_id]._prev = 0; } // add new Tranction requested {Tranction requested! not a final Tranction} function addRecord(address _from_address, address _to_address, uint256 _prop_id, string memory ipfs_hash) public returns(uint256) { recordlist[requestListCounter]._from = _from_address; recordlist[requestListCounter]._to = _to_address; recordlist[requestListCounter]._prop = _prop_id; recordlist[requestListCounter]._state = TranctionState.requested; recordlist[requestListCounter]._ipfs_hash = ipfs_hash; // link the new block to the previous block recordlist[requestListCounter]._prev = properties[_prop_id]._trans_id; // point the new request properties[_prop_id]._trans_id = requestListCounter; notify(requestListCounter); return (requestListCounter++); } // add new property on list function addProperty(address _userId, uint _req_id) public { // add new property on top of the list users[_userId].properties[users[_userId].propertiesTop]._next = _req_id; // link the top block with the previous block users[_userId].properties[_req_id]._prev = users[_userId].propertiesTop; // mark the top as the end block users[_userId].properties[_req_id]._next = 0; // set the pointer to the top block / latest block users[_userId].propertiesTop = _req_id; } function removeProperty(address _userId, uint _req_id) public { // sift the pointer to the previous block if - removing the top block if(users[_userId].propertiesTop == _req_id) users[_userId].propertiesTop = users[_userId].properties[_req_id]._prev; // link the top block with the previous block users[_userId].properties[users[_userId].properties[_req_id]._prev]._next = users[_userId].properties[_req_id]._next; users[_userId].properties[users[_userId].properties[_req_id]._next]._prev = users[_userId].properties[_req_id]._prev; // clear the current block users[_userId].properties[_req_id]._next = 0; users[_userId].properties[_req_id]._prev = 0; } // notify admin function notify(uint _req_id) public { // add the pointer of the transection request to the requestList requestList[requestListTop]._next = _req_id; // link the top requestList block to the previous block requestList[_req_id]._prev = requestListTop; // make the top pointer as the end of the list requestList[_req_id]._next = 0; // save the pointer to the top of the requestList requestListTop = _req_id; } // Views // get User information function getUser(address _userId) view public returns(string memory, uint, UserType) { // return username, aadhaar-number, user-domain return (users[_userId].name, users[_userId].adr, users[_userId].utype); } function viewPropertyDetail(uint _prop_id)view public returns(string memory, uint) { return (properties[_prop_id]._info, properties[_prop_id]._trans_id); } function viewTranction(uint _trans_id)view public returns(address, address, uint, uint, TranctionState, address, string memory) { return (recordlist[_trans_id]._from, recordlist[_trans_id]._to, recordlist[_trans_id]._prev, recordlist[_trans_id]._prop, recordlist[_trans_id]._state, recordlist[_trans_id].approved_by, recordlist[_trans_id]._ipfs_hash); } //////////////////////////////////////////////////////////// // approve the Tranction request function approve(uint256 _record_id) public isSuperAdmin { recordlist[_record_id]._state = TranctionState.approved; recordlist[_record_id].approved_by = msg.sender; // remove notification from user removePropertyRequest(recordlist[_record_id]._to, _record_id); // remove notification from admin removeNotification(_record_id); addProperty(recordlist[_record_id]._to, _record_id); removeProperty(recordlist[_record_id]._to, _record_id); } // reject the Tranction request function reject(uint256 _record_id) public isSuperAdmin { removeProperty(recordlist[_record_id]._to, _record_id); // remove notification from user removePropertyRequest(recordlist[_record_id]._to, _record_id); // remove notification from admin removeNotification(_record_id); } /////////////////////////////////////////////////////////// function removeNotification(uint _req_id) public { // sift the pointer to the previous block if - removing the top block if(requestListTop == _req_id) requestListTop = requestList[_req_id]._prev; // link the top block with the previous block requestList[requestList[_req_id]._next]._prev = requestList[_req_id]._prev; requestList[requestList[_req_id]._prev]._next = requestList[_req_id]._next; // clear the current block requestList[_req_id]._next = 0; requestList[_req_id]._prev = 0; } // send one property id at a time { default is 0 } function getNextPropertyId(address _userId, uint _ptr) view public returns(uint) { return users[_userId].properties[_ptr]._next; } // send one property id at a time { default is 0 } function getNextRequestedPropertyId(address _userId, uint _ptr) view public returns(uint) { return users[_userId].requestList[_ptr]._next; } // send one notification id at a time { default is 0 } function getNextNotificationId(uint _ptr) view public returns(uint) { return requestList[_ptr]._next; } // create new property function createNewProperty(address _to, string memory _info, string memory _data_hash) public returns (uint) { properties[property_counter] = PropertyDetail(_info, requestListCounter); recordlist[requestListCounter] = Tranction(address(0), _to, uint(0), property_counter, TranctionState.approved, msg.sender, _data_hash); addProperty(_to, requestListCounter); requestListCounter++; //return property_id return (property_counter++); } }
sift the pointer to the previous block if - removing the top block link the top block with the previous block clear the current block
function removeNotification(uint _req_id) public { if(requestListTop == _req_id) requestListTop = requestList[_req_id]._prev; requestList[requestList[_req_id]._next]._prev = requestList[_req_id]._prev; requestList[requestList[_req_id]._prev]._next = requestList[_req_id]._next; requestList[_req_id]._next = 0; requestList[_req_id]._prev = 0; }
5,342,649
[ 1, 87, 2136, 326, 4407, 358, 326, 2416, 1203, 309, 300, 9427, 326, 1760, 1203, 1692, 326, 1760, 1203, 598, 326, 2416, 1203, 2424, 326, 783, 1203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 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, 1206, 4386, 12, 11890, 389, 3658, 67, 350, 13, 1071, 288, 203, 3639, 309, 12, 2293, 682, 3401, 422, 389, 3658, 67, 350, 13, 590, 682, 3401, 273, 590, 682, 63, 67, 3658, 67, 350, 65, 6315, 10001, 31, 203, 540, 203, 3639, 590, 682, 63, 2293, 682, 63, 67, 3658, 67, 350, 65, 6315, 4285, 65, 6315, 10001, 273, 590, 682, 63, 67, 3658, 67, 350, 65, 6315, 10001, 31, 203, 3639, 590, 682, 63, 2293, 682, 63, 67, 3658, 67, 350, 65, 6315, 10001, 65, 6315, 4285, 273, 590, 682, 63, 67, 3658, 67, 350, 65, 6315, 4285, 31, 203, 540, 203, 3639, 590, 682, 63, 67, 3658, 67, 350, 65, 6315, 4285, 273, 374, 31, 203, 3639, 590, 682, 63, 67, 3658, 67, 350, 65, 6315, 10001, 273, 374, 31, 203, 565, 289, 203, 377, 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 ]
//pragma experimental ABIEncoderV2; pragma solidity >= 0.6.2 < 0.7.0; import "./StandardToken.sol"; import "./Controlled.sol"; import "./Authority.sol"; //ctoken利息凭证代币 contract CToken is StandardToken, Controlled, Authority { mapping(address =>mapping(address =>uint256)) internal allowed; //销毁代币成功的事件 event BurnTokenSuccess(address indexed _from, address indexed _to, uint256 _value); //初始化代币参数 constructor(uint256 _initialAmount, string memory _tokenName, uint8 _decimalUnits, string memory _tokenSymbol) public { totalSupply = _initialAmount; //0 name = _tokenName; symbol = _tokenSymbol; decimals = _decimalUnits; balanceOf[msg.sender] = totalSupply; addrList[(addrListLength - 1)] = msg.sender; } // uint256[] creatTimes;//创建时间,数组,时间顺序排列 // uint256 creatTimeslength=0; //此地址此用户ctoken种类数 mapping(address =>uint256) public typesCount; //从1开始 //此地址此用户ctoken种类数的index,对应的时间,从1开始 mapping(address =>mapping(uint256 =>cTokenOneInfo)) public cTokenAddrInfos; struct cTokenOneInfo { uint256 balanceOf; uint256 creatTime; //创建时间 uint256 rate; //生成时的利率,单位为 1,000,000倍,即 5000= 5000/1000000=0.005%,大写 } uint256 rate = 273; //最终返利计算时,乘以参数(5*10**(-8)),实时利率,//生成时的利率,单位为 1,000,000倍,即 5000= 5000/1000000=0.005%,大写 function getName() public view returns(string memory) { return name; } function getSymbol() public view returns(string memory) { return symbol; } function getDecimals() public view returns(uint8) { return decimals; } function getTotalSupply() public view returns(uint) { return totalSupply; } function getBalanceOf(address _target) public view returns(uint256) { return balanceOf[_target]; } function setRate(uint256 _rate) public onlyGovenors1 returns(bool _success) { rate = _rate; return true; } //查询当前利率 function getRate() public view returns(uint256 _rate) { return rate; } //查询用户持币利率信息,index查询,index start 1; function getCTokenAddrInfos(uint256 _index, address _target) public view returns(uint256 _balanceOf, uint256 _creatTime, uint256 _rate) { return (cTokenAddrInfos[_target][_index].balanceOf, cTokenAddrInfos[_target][_index].creatTime, cTokenAddrInfos[_target][_index].rate); } //查询用户持币利率种类个数 function getTypesCount(address _target) public view returns(uint256 _typesCount) { return typesCount[_target]; } //带利率的销毁代币 function _burnCoinWithRate(address target, uint256 burnAmount) internal { uint256 leftcount = burnAmount; uint256 removeNum = 0; // uint256 typecount = typesCount[target]; for (uint i = 1; i <= typecount; i++) { if (leftcount >= cTokenAddrInfos[target][i].balanceOf) { leftcount = leftcount - cTokenAddrInfos[target][i].balanceOf; removeNum += 1; continue; } else { cTokenAddrInfos[target][i].balanceOf -= leftcount; break; } } for (uint256 index = removeNum; index > 0; index--) { // if (index >= typecount) ; for (uint m = index; m < typecount; m++) { cTokenAddrInfos[target][m] = cTokenAddrInfos[target][m + 1]; } typecount--; typesCount[target] -= 1; } } //发送代币,带利率 function _transferCoinWithRate(address _from, address _to, uint256 _value) internal transferAllowed(msg.sender) { uint256 leftcount = _value; uint256 removeNum = 0; // uint256 typecount = typesCount[_from]; for (uint k = 1; k <= typecount; k++) { if (leftcount >= cTokenAddrInfos[_from][k].balanceOf) { _transferWithRateIndexOne(_from, k, _to, cTokenAddrInfos[_from][k].balanceOf); leftcount = leftcount - cTokenAddrInfos[_from][k].balanceOf; removeNum += 1; // continue; } else { cTokenAddrInfos[_from][k].balanceOf -= leftcount; // uint256 leftcount2 = cTokenAddrInfos[_from][k].balanceOf-leftcount ; _transferWithRateIndexOne(_from, k, _to, leftcount); break; } } for (uint256 index = removeNum; index > 0; index--) { // if (index >= typecount) ; for (uint m = index; m < typecount; m++) { cTokenAddrInfos[_from][m] = cTokenAddrInfos[_from][m + 1]; } typecount--; typesCount[_from] -= 1; } } //计算添加工具,thisOneTime比较的时间,_to添加进的地址,_from从哪个地址添加 function _transferWithRateIndexOne(address _from, uint256 k, address _to, uint256 _value) internal transferAllowed(msg.sender) { uint256 typecount_to = typesCount[_to]; uint256 thisOneTime = cTokenAddrInfos[_from][k].creatTime; if (typecount_to == 0) { cTokenAddrInfos[_to][1].balanceOf = _value; cTokenAddrInfos[_to][1].creatTime = thisOneTime; cTokenAddrInfos[_to][1].rate = cTokenAddrInfos[_from][k].rate; typesCount[_to] += 1; } else { for (uint i = 1; i <= typecount_to; i++) { //小,则插入i位置 if (thisOneTime < cTokenAddrInfos[_to][i].creatTime) { for (uint j = typecount_to; j >= i; j--) { cTokenAddrInfos[_to][j + 1] = cTokenAddrInfos[_to][j]; } cTokenAddrInfos[_to][i].balanceOf = _value; cTokenAddrInfos[_to][i].creatTime = thisOneTime; cTokenAddrInfos[_to][i].rate = cTokenAddrInfos[_from][k].rate; typesCount[_to] += 1; break; } else if (thisOneTime == cTokenAddrInfos[_to][i].creatTime) { cTokenAddrInfos[_to][i].balanceOf += _value; break; } else { if (i == (typecount_to)) { cTokenAddrInfos[_to][i + 1].balanceOf = _value; cTokenAddrInfos[_to][i + 1].creatTime = thisOneTime; cTokenAddrInfos[_to][i + 1].rate = cTokenAddrInfos[_from][k].rate; typesCount[_to] += 1; break; } } } } } //删除k值 function _deleteRateIndexK(address _from, uint256 k) internal transferAllowed(msg.sender) { uint256 typecount = typesCount[_from]; // require(k<=typecount,'index can not bigger than typesCount size'); for (uint m = k; m < typecount; m++) { cTokenAddrInfos[_from][m] = cTokenAddrInfos[_from][m + 1]; } typesCount[_from] -= 1; } //带利率的增发代币 function _mintCoinWithRate(address target, uint256 mintedAmount) internal { uint256 nowtime = block.timestamp; uint256 typecount = typesCount[target] + 1; typesCount[target] += 1; cTokenAddrInfos[target][typecount].balanceOf = mintedAmount; cTokenAddrInfos[target][typecount].creatTime = nowtime; cTokenAddrInfos[target][typecount].rate = rate; } //增发代币 function mintToken(address target, uint256 mintedAmount) public onlyGovenors1 { balanceOf[target] = balanceOf[target].add(mintedAmount); totalSupply = totalSupply.add(mintedAmount); addAddressToAddrList(target); _mintCoinWithRate(target, mintedAmount); emit Transfer(address(0), owner, mintedAmount); emit Transfer(owner, target, mintedAmount); } //带利率,(销毁)减少代币,销毁该地址添加一定数量的代币,同样需要修改totalSupply代币总量值。 function burnToken(address target, uint256 burnAmount) public onlyGovenors1 { require(target != address(0), "ERC20: burn from the zero address"); require(balanceOf[target] >= burnAmount, "ERC20: burn amount insufficient"); balanceOf[target] = balanceOf[target].sub(burnAmount); totalSupply = totalSupply.sub(burnAmount); _burnCoinWithRate(target, burnAmount); emit BurnTokenSuccess(target, address(0), burnAmount); } //销毁的另一种形式,需要批准,A 批准 B 10个代币的转移权,B 可销毁 A 账户下10个代币,同时也要减少 A 对B 的批准转移数量。 function burnFrom(address account, uint256 amount) public { require(amount <= allowed[account][msg.sender], "MyERROR: approve amount insufficient"); burnToken(account, amount); allowed[account][msg.sender] = allowed[account][msg.sender].sub(amount); _burnCoinWithRate(account, amount); } function transfer(address _to, uint256 _value) public transferAllowed(msg.sender) returns(bool success) { //require(_to != address(0)); require(_to != address(0), "ERC20: approve from the zero address"); require(_value <= balanceOf[msg.sender]); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); addAddressToAddrList(_to); _transferCoinWithRate(msg.sender, _to, _value); emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public transferAllowed(_from) returns(bool success) { //require(_to != address(0)); require(_to != address(0), "ERC20: approve from the zero address"); require(_value <= balanceOf[_from]); require(_value <= allowed[_from][msg.sender]); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); addAddressToAddrList(_to); _transferCoinWithRate(_from, _to, _value); emit Transfer(_from, _to, _value); return true; } //授权 function approve(address _spender, uint256 _value) public returns(bool success) { allowed[msg.sender][_spender] = _value; addAddressToAddrList(_spender); emit Approval(msg.sender, _spender, _value); return true; } //查看剩余授权数量代币 function allowance(address _owner, address _spender) public view returns(uint256 remaining) { return allowed[_owner][_spender]; } }
删除k值 require(k<=typecount,'index can not bigger than typesCount size');
function _deleteRateIndexK(address _from, uint256 k) internal transferAllowed(msg.sender) { uint256 typecount = typesCount[_from]; for (uint m = k; m < typecount; m++) { cTokenAddrInfos[_from][m] = cTokenAddrInfos[_from][m + 1]; } typesCount[_from] -= 1; }
6,346,735
[ 1, 166, 235, 259, 170, 252, 102, 79, 166, 227, 125, 202, 565, 2583, 12, 79, 32, 33, 723, 1883, 11189, 1615, 848, 486, 18983, 2353, 1953, 1380, 963, 8284, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 3733, 4727, 1016, 47, 12, 2867, 389, 2080, 16, 2254, 5034, 417, 13, 2713, 7412, 5042, 12, 3576, 18, 15330, 13, 288, 203, 3639, 2254, 5034, 618, 1883, 273, 1953, 1380, 63, 67, 2080, 15533, 203, 3639, 364, 261, 11890, 312, 273, 417, 31, 312, 411, 618, 1883, 31, 312, 27245, 288, 203, 5411, 276, 1345, 3178, 7655, 63, 67, 2080, 6362, 81, 65, 273, 276, 1345, 3178, 7655, 63, 67, 2080, 6362, 81, 397, 404, 15533, 203, 3639, 289, 203, 3639, 1953, 1380, 63, 67, 2080, 65, 3947, 404, 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 ]
./full_match/1/0xd920556b0f3522bB1257923292A256F1e3023e07/sources/SimpleFarm.sol
* @dev Allows to claim accumulated rewards up to date/
function claimReward() public updateFarm() updateUser() returns (uint256 rewardAmount) { address senderAddress = msg.sender; rewardAmount = earned( senderAddress ); require( rewardAmount > 0, "SimpleFarm: NOTHING_TO_CLAIM" ); userRewards[senderAddress] = 0; safeTransfer( rewardToken, senderAddress, rewardAmount ); emit RewardPaid( senderAddress, rewardAmount ); }
9,746,329
[ 1, 19132, 358, 7516, 24893, 283, 6397, 731, 358, 1509, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7516, 17631, 1060, 1435, 203, 3639, 1071, 203, 3639, 1089, 42, 4610, 1435, 203, 3639, 28213, 1435, 203, 3639, 1135, 261, 11890, 5034, 19890, 6275, 13, 203, 565, 288, 203, 3639, 1758, 5793, 1887, 273, 1234, 18, 15330, 31, 203, 203, 3639, 19890, 6275, 273, 425, 1303, 329, 12, 203, 5411, 5793, 1887, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 203, 5411, 19890, 6275, 405, 374, 16, 203, 5411, 315, 5784, 42, 4610, 30, 4269, 44, 1360, 67, 4296, 67, 15961, 3445, 6, 203, 3639, 11272, 203, 203, 3639, 729, 17631, 14727, 63, 15330, 1887, 65, 273, 374, 31, 203, 203, 3639, 4183, 5912, 12, 203, 5411, 19890, 1345, 16, 203, 5411, 5793, 1887, 16, 203, 5411, 19890, 6275, 203, 3639, 11272, 203, 203, 3639, 3626, 534, 359, 1060, 16507, 350, 12, 203, 5411, 5793, 1887, 16, 203, 5411, 19890, 6275, 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 ]
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "../rewards/AavePodCall.sol"; import "../../interfaces/IPodOption.sol"; import "../../interfaces/IOptionBuilder.sol"; /** * @title AavePodCallBuilder * @author Pods Finance * @notice Builds AavePodCall options */ contract AavePodCallBuilder is IOptionBuilder { /** * @notice creates a new AavePodCall Contract * @param name The option token name. Eg. "Pods Call WBTC-USDC 5000 2020-02-23" * @param symbol The option token symbol. Eg. "podWBTC:20AA" * @param exerciseType The option exercise type. Eg. "0 for European, 1 for American" * @param underlyingAsset The underlying asset. Eg. "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" * @param strikeAsset The strike asset. Eg. "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48" * @param strikePrice The option strike price including decimals. e.g. 5000000000 * @param expiration The Expiration Option date in seconds. e.g. 1600178324 * @param exerciseWindowSize The Expiration Window Size duration in seconds. E.g 24*60*60 (24h) */ function buildOption( string memory name, string memory symbol, IPodOption.ExerciseType exerciseType, address underlyingAsset, address strikeAsset, uint256 strikePrice, uint256 expiration, uint256 exerciseWindowSize, IConfigurationManager configurationManager ) external override returns (IPodOption) { AavePodCall option = new AavePodCall( name, symbol, exerciseType, underlyingAsset, strikeAsset, strikePrice, expiration, exerciseWindowSize, configurationManager ); return option; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "../PodCall.sol"; import "./AaveIncentives.sol"; /** * @title AavePodCall * @author Pods Finance * * @notice Represents a tokenized Call option series that handles and distributes liquidity * mining rewards to minters (sellers) proportionally to their amount of shares */ contract AavePodCall is PodCall, AaveIncentives { constructor( string memory name, string memory symbol, IPodOption.ExerciseType exerciseType, address underlyingAsset, address strikeAsset, uint256 strikePrice, uint256 expiration, uint256 exerciseWindowSize, IConfigurationManager configurationManager ) public PodCall( name, symbol, exerciseType, underlyingAsset, strikeAsset, strikePrice, expiration, exerciseWindowSize, configurationManager ) AaveIncentives(configurationManager) {} // solhint-disable-line no-empty-blocks /** * @notice Unlocks collateral by burning option tokens. * * Options can only be burned while the series is NOT expired. * * @param amountOfOptions The amount option tokens to be burned */ function unmint(uint256 amountOfOptions) external override unmintWindow { _claimRewards(_getClaimableAssets()); uint256 rewardsToSend = (shares[msg.sender].mul(amountOfOptions).div(mintedOptions[msg.sender])).mul(_rewardBalance()).div(totalShares); (uint256 strikeToSend, uint256 underlyingToSend) = _unmintOptions(amountOfOptions, msg.sender); IERC20(underlyingAsset()).safeTransfer(msg.sender, underlyingToSend); emit Unmint(msg.sender, amountOfOptions, strikeToSend, underlyingToSend); if (rewardsToSend > 0) { IERC20(rewardAsset).safeTransfer(msg.sender, rewardsToSend); emit RewardsClaimed(msg.sender, rewardsToSend); } } /** * @notice After series expiration in case of American or after exercise window for European, * allow minters who have locked their strike asset tokens to withdraw them proportionally * to their minted options. * * @dev If assets had been exercised during the option series the minter may withdraw * the exercised assets or a combination of exercised and strike asset tokens. */ function withdraw() external override withdrawWindow { _claimRewards(_getClaimableAssets()); uint256 rewardsToSend = shares[msg.sender].mul(_rewardBalance()).div(totalShares); (uint256 strikeToSend, uint256 underlyingToSend) = _withdraw(); IERC20(underlyingAsset()).safeTransfer(msg.sender, underlyingToSend); if (strikeToSend > 0) { IERC20(strikeAsset()).safeTransfer(msg.sender, strikeToSend); } emit Withdraw(msg.sender, strikeToSend, underlyingToSend); if (rewardsToSend > 0) { IERC20(rewardAsset).safeTransfer(msg.sender, rewardsToSend); emit RewardsClaimed(msg.sender, rewardsToSend); } } /** * @dev Returns an array of staked assets which may be eligible for claiming rewards */ function _getClaimableAssets() internal view returns (address[] memory) { address[] memory assets = new address[](1); assets[0] = underlyingAsset(); return assets; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IPodOption is IERC20 { /** Enums */ // @dev 0 for Put, 1 for Call enum OptionType { PUT, CALL } // @dev 0 for European, 1 for American enum ExerciseType { EUROPEAN, AMERICAN } /** Events */ event Mint(address indexed minter, uint256 amount); event Unmint(address indexed minter, uint256 optionAmount, uint256 strikeAmount, uint256 underlyingAmount); event Exercise(address indexed exerciser, uint256 amount); event Withdraw(address indexed minter, uint256 strikeAmount, uint256 underlyingAmount); /** Functions */ /** * @notice Locks collateral and write option tokens. * * @dev The issued amount ratio is 1:1, i.e., 1 option token for 1 underlying token. * * The collateral could be the strike or the underlying asset depending on the option type: Put or Call, * respectively * * It presumes the caller has already called IERC20.approve() on the * strike/underlying token contract to move caller funds. * * Options can only be minted while the series is NOT expired. * * It is also important to notice that options will be sent back * to `msg.sender` and not the `owner`. This behavior is designed to allow * proxy contracts to mint on others behalf. The `owner` will be able to remove * the deposited collateral after series expiration or by calling unmint(), even * if a third-party minted options on its behalf. * * @param amountOfOptions The amount option tokens to be issued * @param owner Which address will be the owner of the options */ function mint(uint256 amountOfOptions, address owner) external; /** * @notice Allow option token holders to use them to exercise the amount of units * of the locked tokens for the equivalent amount of the exercisable assets. * * @dev It presumes the caller has already called IERC20.approve() exercisable asset * to move caller funds. * * On American options, this function can only called anytime before expiration. * For European options, this function can only be called during the exerciseWindow. * Meaning, after expiration and before the end of exercise window. * * @param amountOfOptions The amount option tokens to be exercised */ function exercise(uint256 amountOfOptions) external; /** * @notice After series expiration in case of American or after exercise window for European, * allow minters who have locked their collateral to withdraw them proportionally * to their minted options. * * @dev If assets had been exercised during the option series the minter may withdraw * the exercised assets or a combination of exercised and collateral. */ function withdraw() external; /** * @notice Unlocks collateral by burning option tokens. * * Options can only be burned while the series is NOT expired. * * @param amountOfOptions The amount option tokens to be burned */ function unmint(uint256 amountOfOptions) external; function optionType() external view returns (OptionType); function exerciseType() external view returns (ExerciseType); function underlyingAsset() external view returns (address); function underlyingAssetDecimals() external view returns (uint8); function strikeAsset() external view returns (address); function strikeAssetDecimals() external view returns (uint8); function strikePrice() external view returns (uint256); function strikePriceDecimals() external view returns (uint8); function expiration() external view returns (uint256); function startOfExerciseWindow() external view returns (uint256); function hasExpired() external view returns (bool); function isTradeWindow() external view returns (bool); function isExerciseWindow() external view returns (bool); function isWithdrawWindow() external view returns (bool); function strikeToTransfer(uint256 amountOfOptions) external view returns (uint256); function getSellerWithdrawAmounts(address owner) external view returns (uint256 strikeAmount, uint256 underlyingAmount); function underlyingReserves() external view returns (uint256); function strikeReserves() external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "./IPodOption.sol"; import "./IConfigurationManager.sol"; interface IOptionBuilder { function buildOption( string memory _name, string memory _symbol, IPodOption.ExerciseType _exerciseType, address _underlyingAsset, address _strikeAsset, uint256 _strikePrice, uint256 _expiration, uint256 _exerciseWindowSize, IConfigurationManager _configurationManager ) external returns (IPodOption); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "./PodOption.sol"; /** * @title PodCall * @author Pods Finance * * @notice Represents a tokenized Call option series for some long/short token pair. * * @dev Call options represents the right, not the obligation to buy the underlying asset * for strike price units of the strike asset. * * There are four main actions that can be done with an option: * * * Sellers can mint fungible call option tokens by locking 1:1 units * of underlying asset until expiration. Buyers can exercise their call, meaning * buying the locked underlying asset for strike price units of strike asset. * At the end, seller can retrieve back its collateral, that could be the underlying asset * AND/OR strike based on the contract's current ratio of underlying and strike assets. * * There are many option's style, but the most usual are: American and European. * The difference between them are the moments that the buyer is allowed to exercise and * the moment that seller can retrieve its locked collateral. * * Exercise: * American -> any moment until expiration * European -> only after expiration and until the end of the exercise window * * Withdraw: * American -> after expiration * European -> after end of exercise window * * Let's take an example: there is such an European call option series where buyers * may buy 1 WETH for 300 USDC until Dec 31, 2021. * * In this case: * * - Expiration date: Dec 31, 2021 * - Underlying asset: WETH * - Strike asset: USDC * - Strike price: 300 USDC * * ETH holders may call mint() until the expiration date, which in turn: * * - Will lock their WETH into this contract * - Will issue option tokens corresponding to this WETH amount * - This contract is agnostic about where options could be bought or sold and how much the * the option premium should be. * * WETH holders who also hold the option tokens may call unmint() until the * expiration date, which in turn: * * - Will unlock their WETH from this contract * - Will burn the corresponding amount of options tokens * * Option token holders may call exercise() after the expiration date and * end of before exercise window, to exercise their option, which in turn: * * - Will buy 1 ETH for 300 USDC (the strike price) each. * - Will burn the corresponding amount of option tokens. * * WETH holders that minted options initially can call withdraw() after the * end of exercise window, which in turn: * * - Will give back its amount of collateral locked. That could be o mix of * underlying asset and strike asset based if and how the pool was exercised. * * IMPORTANT: Note that after expiration, option tokens are worthless since they can not * be exercised and it price should worth 0 in a healthy market. * */ contract PodCall is PodOption { constructor( string memory name, string memory symbol, IPodOption.ExerciseType exerciseType, address underlyingAsset, address strikeAsset, uint256 strikePrice, uint256 expiration, uint256 exerciseWindowSize, IConfigurationManager configurationManager ) public PodOption( name, symbol, IPodOption.OptionType.CALL, exerciseType, underlyingAsset, strikeAsset, strikePrice, expiration, exerciseWindowSize, configurationManager ) {} // solhint-disable-line no-empty-blocks /** * @notice Locks underlying asset and write option tokens. * * @dev The issued amount ratio is 1:1, i.e., 1 option token for 1 underlying token. * * It presumes the caller has already called IERC20.approve() on the * underlying token contract to move caller funds. * * This function is meant to be called by underlying token holders wanting * to write option tokens. Calling it will lock `amountOfOptions` units of * `underlyingToken` into this contract * * Options can only be minted while the series is NOT expired. * * It is also important to notice that options will be sent back * to `msg.sender` and not the `owner`. This behavior is designed to allow * proxy contracts to mint on others behalf. The `owner` will be able to remove * the deposited collateral after series expiration or by calling unmint(), even * if a third-party minted options on its behalf. * * @param amountOfOptions The amount option tokens to be issued * @param owner Which address will be the owner of the options */ function mint(uint256 amountOfOptions, address owner) external override tradeWindow { require(amountOfOptions > 0, "PodCall: you can not mint zero options"); _mintOptions(amountOfOptions, amountOfOptions, owner); IERC20(underlyingAsset()).safeTransferFrom(msg.sender, address(this), amountOfOptions); emit Mint(owner, amountOfOptions); } /** * @notice Unlocks collateral by burning option tokens. * * Options can only be burned while the series is NOT expired. * * @param amountOfOptions The amount option tokens to be burned */ function unmint(uint256 amountOfOptions) external virtual override unmintWindow { (uint256 strikeToSend, uint256 underlyingToSend) = _unmintOptions(amountOfOptions, msg.sender); // Sends underlying asset IERC20(underlyingAsset()).safeTransfer(msg.sender, underlyingToSend); emit Unmint(msg.sender, amountOfOptions, strikeToSend, underlyingToSend); } /** * @notice Allow Call token holders to use them to buy some amount of units * of underlying token for the amountOfOptions * strike price units of the * strike token. * * @dev It presumes the caller has already called IERC20.approve() on the * strike token contract to move caller funds. * * During the process: * * - The amountOfOptions units of underlying tokens are transferred to the caller * - The amountOfOptions option tokens are burned. * - The amountOfOptions * strikePrice units of strike tokens are transferred into * this contract as a payment for the underlying tokens. * * On American options, this function can only called anytime before expiration. * For European options, this function can only be called during the exerciseWindow. * Meaning, after expiration and before the end of exercise window. * * @param amountOfOptions The amount option tokens to be exercised */ function exercise(uint256 amountOfOptions) external virtual override exerciseWindow { require(amountOfOptions > 0, "PodCall: you can not exercise zero options"); // Calculate the strike amount equivalent to pay for the underlying requested uint256 amountStrikeToReceive = _strikeToTransfer(amountOfOptions); // Burn the exercised options _burn(msg.sender, amountOfOptions); // Retrieve the strike asset from caller IERC20(strikeAsset()).safeTransferFrom(msg.sender, address(this), amountStrikeToReceive); // Releases the underlying asset to caller, completing the exchange IERC20(underlyingAsset()).safeTransfer(msg.sender, amountOfOptions); emit Exercise(msg.sender, amountOfOptions); } /** * @notice After series expiration in case of American or after exercise window for European, * allow minters who have locked their underlying asset tokens to withdraw them proportionally * to their minted options. * * @dev If assets had been exercised during the option series the minter may withdraw * the exercised assets or a combination of exercised and underlying asset tokens. */ function withdraw() external virtual override withdrawWindow { (uint256 strikeToSend, uint256 underlyingToSend) = _withdraw(); IERC20(underlyingAsset()).safeTransfer(msg.sender, underlyingToSend); if (strikeToSend > 0) { IERC20(strikeAsset()).safeTransfer(msg.sender, strikeToSend); } emit Withdraw(msg.sender, strikeToSend, underlyingToSend); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../interfaces/IAaveIncentivesController.sol"; import "../../interfaces/IConfigurationManager.sol"; import "../../lib/Conversion.sol"; abstract contract AaveIncentives is Conversion { address public immutable rewardAsset; address public immutable rewardContract; event RewardsClaimed(address indexed claimer, uint256 rewardAmount); constructor(IConfigurationManager configurationManager) public { rewardAsset = _parseAddressFromUint(configurationManager.getParameter("REWARD_ASSET")); rewardContract = _parseAddressFromUint(configurationManager.getParameter("REWARD_CONTRACT")); } /** * @notice Gets the current reward claimed */ function _rewardBalance() internal view returns (uint256) { return IERC20(rewardAsset).balanceOf(address(this)); } /** * @notice Claim pending rewards */ function _claimRewards(address[] memory assets) internal { IAaveIncentivesController distributor = IAaveIncentivesController(rewardContract); uint256 amountToClaim = distributor.getRewardsBalance(assets, address(this)); distributor.claimRewards(assets, amountToClaim, address(this)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/IPodOption.sol"; import "../lib/CappedOption.sol"; import "../lib/RequiredDecimals.sol"; import "../interfaces/IConfigurationManager.sol"; /** * @title PodOption * @author Pods Finance * * @notice This contract represents the basic structure of the financial instrument * known as Option, sharing logic between both a PUT or a CALL types. * * @dev There are four main actions that can be called in an Option: * * A) mint => A minter can lock collateral and create new options before expiration. * B) unmint => The minter who previously minted can choose for leaving its position any given time * until expiration. * C) exercise => The option bearer the can exchange its option for the collateral at the strike price. * D) withdraw => The minter can retrieve collateral at the end of the series. * * Depending on the type (PUT / CALL) or the exercise (AMERICAN / EUROPEAN), those functions have * different behave and should be override accordingly. */ abstract contract PodOption is IPodOption, ERC20, RequiredDecimals, CappedOption { using SafeERC20 for IERC20; /** * @dev Minimum allowed exercise window: 24 hours */ uint256 public constant MIN_EXERCISE_WINDOW_SIZE = 86400; OptionType private immutable _optionType; ExerciseType private immutable _exerciseType; IConfigurationManager public immutable configurationManager; address private immutable _underlyingAsset; uint8 private immutable _underlyingAssetDecimals; address private immutable _strikeAsset; uint8 private immutable _strikeAssetDecimals; uint256 private immutable _strikePrice; uint256 private immutable _expiration; uint256 private _startOfExerciseWindow; /** * @notice Reserve share balance * @dev Tracks the shares of the total asset reserve by address */ mapping(address => uint256) public shares; /** * @notice Minted option balance * @dev Tracks amount of minted options by address */ mapping(address => uint256) public mintedOptions; /** * @notice Total reserve shares */ uint256 public totalShares = 0; constructor( string memory name, string memory symbol, OptionType optionType, ExerciseType exerciseType, address underlyingAsset, address strikeAsset, uint256 strikePrice, uint256 expiration, uint256 exerciseWindowSize, IConfigurationManager _configurationManager ) public ERC20(name, symbol) CappedOption(_configurationManager) { require(Address.isContract(underlyingAsset), "PodOption: underlying asset is not a contract"); require(Address.isContract(strikeAsset), "PodOption: strike asset is not a contract"); require(underlyingAsset != strikeAsset, "PodOption: underlying asset and strike asset must differ"); require(expiration > block.timestamp, "PodOption: expiration should be in the future"); require(strikePrice > 0, "PodOption: strike price must be greater than zero"); if (exerciseType == ExerciseType.EUROPEAN) { require( exerciseWindowSize >= MIN_EXERCISE_WINDOW_SIZE, "PodOption: exercise window must be greater than or equal 86400" ); _startOfExerciseWindow = expiration.sub(exerciseWindowSize); } else { require(exerciseWindowSize == 0, "PodOption: exercise window size must be equal to zero"); _startOfExerciseWindow = block.timestamp; } configurationManager = _configurationManager; _optionType = optionType; _exerciseType = exerciseType; _expiration = expiration; _underlyingAsset = underlyingAsset; _strikeAsset = strikeAsset; uint8 underlyingDecimals = tryDecimals(IERC20(underlyingAsset)); _underlyingAssetDecimals = underlyingDecimals; _strikeAssetDecimals = tryDecimals(IERC20(strikeAsset)); _strikePrice = strikePrice; _setupDecimals(underlyingDecimals); } /** * @notice Checks if the options series has already expired. */ function hasExpired() external override view returns (bool) { return _hasExpired(); } /** * @notice External function to calculate the amount of strike asset * needed given the option amount */ function strikeToTransfer(uint256 amountOfOptions) external override view returns (uint256) { return _strikeToTransfer(amountOfOptions); } /** * @notice Checks if the options trade window has opened. */ function isTradeWindow() external override view returns (bool) { return _isTradeWindow(); } /** * @notice Checks if the options exercise window has opened. */ function isExerciseWindow() external override view returns (bool) { return _isExerciseWindow(); } /** * @notice Checks if the options withdraw window has opened. */ function isWithdrawWindow() external override view returns (bool) { return _isWithdrawWindow(); } /** * @notice The option type. eg: CALL, PUT */ function optionType() external override view returns (OptionType) { return _optionType; } /** * @notice Exercise type. eg: AMERICAN, EUROPEAN */ function exerciseType() external override view returns (ExerciseType) { return _exerciseType; } /** * @notice The sell price of each unit of underlyingAsset; given in units * of strikeAsset, e.g. 0.99 USDC */ function strikePrice() external override view returns (uint256) { return _strikePrice; } /** * @notice The number of decimals of strikePrice */ function strikePriceDecimals() external override view returns (uint8) { return _strikeAssetDecimals; } /** * @notice The timestamp in seconds that represents the series expiration */ function expiration() external override view returns (uint256) { return _expiration; } /** * @notice How many decimals does the strike token have? E.g.: 18 */ function strikeAssetDecimals() public override view returns (uint8) { return _strikeAssetDecimals; } /** * @notice The asset used as the strike asset, e.g. USDC, DAI */ function strikeAsset() public override view returns (address) { return _strikeAsset; } /** * @notice How many decimals does the underlying token have? E.g.: 18 */ function underlyingAssetDecimals() public override view returns (uint8) { return _underlyingAssetDecimals; } /** * @notice The asset used as the underlying token, e.g. WETH, WBTC, UNI */ function underlyingAsset() public override view returns (address) { return _underlyingAsset; } /** * @notice getSellerWithdrawAmounts returns the seller position based on his amount of shares * and the current option position * * @param owner address of the user to check the withdraw amounts * * @return strikeAmount current amount of strike the user will receive. It may change until maturity * @return underlyingAmount current amount of underlying the user will receive. It may change until maturity */ function getSellerWithdrawAmounts(address owner) public override view returns (uint256 strikeAmount, uint256 underlyingAmount) { uint256 ownerShares = shares[owner]; strikeAmount = ownerShares.mul(strikeReserves()).div(totalShares); underlyingAmount = ownerShares.mul(underlyingReserves()).div(totalShares); return (strikeAmount, underlyingAmount); } /** * @notice The timestamp in seconds that represents the start of exercise window */ function startOfExerciseWindow() public override view returns (uint256) { return _startOfExerciseWindow; } /** * @notice Utility function to check the amount of the underlying tokens * locked inside this contract */ function underlyingReserves() public override view returns (uint256) { return IERC20(_underlyingAsset).balanceOf(address(this)); } /** * @notice Utility function to check the amount of the strike tokens locked * inside this contract */ function strikeReserves() public override view returns (uint256) { return IERC20(_strikeAsset).balanceOf(address(this)); } /** * @dev Modifier with the conditions to be able to mint * based on option exerciseType. */ modifier tradeWindow() { require(_isTradeWindow(), "PodOption: trade window has closed"); _; } /** * @dev Modifier with the conditions to be able to unmint * based on option exerciseType. */ modifier unmintWindow() { require(_isTradeWindow() || _isExerciseWindow(), "PodOption: not in unmint window"); _; } /** * @dev Modifier with the conditions to be able to exercise * based on option exerciseType. */ modifier exerciseWindow() { require(_isExerciseWindow(), "PodOption: not in exercise window"); _; } /** * @dev Modifier with the conditions to be able to withdraw * based on exerciseType. */ modifier withdrawWindow() { require(_isWithdrawWindow(), "PodOption: option has not expired yet"); _; } /** * @dev Internal function to check expiration */ function _hasExpired() internal view returns (bool) { return block.timestamp >= _expiration; } /** * @dev Internal function to check trade window */ function _isTradeWindow() internal view returns (bool) { if (_hasExpired()) { return false; } else if (_exerciseType == ExerciseType.EUROPEAN) { return !_isExerciseWindow(); } return true; } /** * @dev Internal function to check window exercise started */ function _isExerciseWindow() internal view returns (bool) { return !_hasExpired() && block.timestamp >= _startOfExerciseWindow; } /** * @dev Internal function to check withdraw started */ function _isWithdrawWindow() internal view returns (bool) { return _hasExpired(); } /** * @dev Internal function to calculate the amount of strike asset needed given the option amount * @param amountOfOptions Intended amount to options to mint */ function _strikeToTransfer(uint256 amountOfOptions) internal view returns (uint256) { uint256 strikeAmount = amountOfOptions.mul(_strikePrice).div(10**uint256(underlyingAssetDecimals())); require(strikeAmount > 0, "PodOption: amount of options is too low"); return strikeAmount; } /** * @dev Calculate number of reserve shares based on the amount of collateral locked by the minter */ function _calculatedShares(uint256 amountOfCollateral) internal view returns (uint256 ownerShares) { uint256 currentStrikeReserves = strikeReserves(); uint256 currentUnderlyingReserves = underlyingReserves(); uint256 numerator = amountOfCollateral.mul(totalShares); uint256 denominator; if (_optionType == OptionType.PUT) { denominator = currentStrikeReserves.add( currentUnderlyingReserves.mul(_strikePrice).div(uint256(10)**underlyingAssetDecimals()) ); } else { denominator = currentUnderlyingReserves.add( currentStrikeReserves.mul(uint256(10)**underlyingAssetDecimals()).div(_strikePrice) ); } ownerShares = numerator.div(denominator); return ownerShares; } /** * @dev Mint options, creating the shares accordingly to the amount of collateral provided * @param amountOfOptions The amount option tokens to be issued * @param amountOfCollateral The amount of collateral provided to mint options * @param owner Which address will be the owner of the options */ function _mintOptions( uint256 amountOfOptions, uint256 amountOfCollateral, address owner ) internal capped(amountOfOptions) { require(owner != address(0), "PodOption: zero address cannot be the owner"); if (totalShares > 0) { uint256 ownerShares = _calculatedShares(amountOfCollateral); shares[owner] = shares[owner].add(ownerShares); totalShares = totalShares.add(ownerShares); } else { shares[owner] = amountOfCollateral; totalShares = amountOfCollateral; } mintedOptions[owner] = mintedOptions[owner].add(amountOfOptions); _mint(msg.sender, amountOfOptions); } /** * @dev Unmints options, burning the option tokens removing shares accordingly and releasing a certain * amount of collateral. * @param amountOfOptions The amount option tokens to be burned * @param owner Which address options will be burned from */ function _unmintOptions(uint256 amountOfOptions, address owner) internal returns (uint256 strikeToSend, uint256 underlyingToSend) { require(shares[owner] > 0, "PodOption: you do not have minted options"); require(amountOfOptions <= mintedOptions[owner], "PodOption: not enough minted options"); uint256 burnedShares = shares[owner].mul(amountOfOptions).div(mintedOptions[owner]); if (_optionType == IPodOption.OptionType.PUT) { uint256 strikeAssetDeposited = totalSupply().mul(_strikePrice).div(10**uint256(decimals())); uint256 totalInterest = 0; if (strikeReserves() > strikeAssetDeposited) { totalInterest = strikeReserves().sub(strikeAssetDeposited); } strikeToSend = amountOfOptions.mul(_strikePrice).div(10**uint256(decimals())).add( totalInterest.mul(burnedShares).div(totalShares) ); // In the case we lost some funds due to precision, the last user to unmint will still be able to perform. if (strikeToSend > strikeReserves()) { strikeToSend = strikeReserves(); } } else { uint256 underlyingAssetDeposited = totalSupply(); uint256 currentUnderlyingAmount = underlyingReserves().add(strikeReserves().div(_strikePrice)); uint256 totalInterest = 0; if (currentUnderlyingAmount > underlyingAssetDeposited) { totalInterest = currentUnderlyingAmount.sub(underlyingAssetDeposited); } underlyingToSend = amountOfOptions.add(totalInterest.mul(burnedShares).div(totalShares)); } shares[owner] = shares[owner].sub(burnedShares); mintedOptions[owner] = mintedOptions[owner].sub(amountOfOptions); totalShares = totalShares.sub(burnedShares); _burn(owner, amountOfOptions); } /** * @dev Removes all shares, returning the amounts that would be withdrawable */ function _withdraw() internal returns (uint256 strikeToSend, uint256 underlyingToSend) { uint256 ownerShares = shares[msg.sender]; require(ownerShares > 0, "PodOption: you do not have balance to withdraw"); (strikeToSend, underlyingToSend) = getSellerWithdrawAmounts(msg.sender); shares[msg.sender] = 0; mintedOptions[msg.sender] = 0; totalShares = totalShares.sub(ownerShares); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.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: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/IConfigurationManager.sol"; import "../interfaces/ICapProvider.sol"; /** * @title CappedOption * @author Pods Finance * * @notice Controls a maximum cap for a guarded release */ abstract contract CappedOption is IERC20 { using SafeMath for uint256; IConfigurationManager private immutable _configurationManager; constructor(IConfigurationManager configurationManager) public { _configurationManager = configurationManager; } /** * @dev Modifier to stop transactions that exceed the cap */ modifier capped(uint256 amountOfOptions) { uint256 cap = capSize(); if (cap > 0) { require(this.totalSupply().add(amountOfOptions) <= cap, "CappedOption: amount exceed cap"); } _; } /** * @dev Get the cap size */ function capSize() public view returns (uint256) { ICapProvider capProvider = ICapProvider(_configurationManager.getCapProvider()); return capProvider.getCap(address(this)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract RequiredDecimals { uint256 private constant _MAX_TOKEN_DECIMALS = 38; /** * Tries to fetch the decimals of a token, if not existent, fails with a require statement * * @param token An instance of IERC20 * @return The decimals of a token */ function tryDecimals(IERC20 token) internal view returns (uint8) { // solhint-disable-line private-vars-leading-underscore bytes memory payload = abi.encodeWithSignature("decimals()"); // solhint-disable avoid-low-level-calls (bool success, bytes memory returnData) = address(token).staticcall(payload); require(success, "RequiredDecimals: required decimals"); uint8 decimals = abi.decode(returnData, (uint8)); require(decimals < _MAX_TOKEN_DECIMALS, "RequiredDecimals: token decimals should be lower than 38"); return decimals; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity >=0.6.12; interface IConfigurationManager { function setParameter(bytes32 name, uint256 value) external; function setEmergencyStop(address emergencyStop) external; function setPricingMethod(address pricingMethod) external; function setIVGuesser(address ivGuesser) external; function setIVProvider(address ivProvider) external; function setPriceProvider(address priceProvider) external; function setCapProvider(address capProvider) external; function setAMMFactory(address ammFactory) external; function setOptionFactory(address optionFactory) external; function setOptionHelper(address optionHelper) external; function setOptionPoolRegistry(address optionPoolRegistry) external; function getParameter(bytes32 name) external view returns (uint256); function owner() external view returns (address); function getEmergencyStop() external view returns (address); function getPricingMethod() external view returns (address); function getIVGuesser() external view returns (address); function getIVProvider() external view returns (address); function getPriceProvider() external view returns (address); function getCapProvider() external view returns (address); function getAMMFactory() external view returns (address); function getOptionFactory() external view returns (address); function getOptionHelper() external view returns (address); function getOptionPoolRegistry() 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: 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: agpl-3.0 pragma solidity 0.6.12; interface ICapProvider { function setCap(address target, uint256 value) external; function getCap(address target) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; interface IAaveIncentivesController { function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; contract Conversion { /** * @notice Parses the address represented by an uint */ function _parseAddressFromUint(uint256 x) internal pure returns (address) { bytes memory data = new bytes(32); assembly { mstore(add(data, 32), x) } return abi.decode(data, (address)); } }
* @notice Unlocks collateral by burning option tokens. Options can only be burned while the series is NOT expired. @param amountOfOptions The amount option tokens to be burned/
function unmint(uint256 amountOfOptions) external override unmintWindow { _claimRewards(_getClaimableAssets()); uint256 rewardsToSend = (shares[msg.sender].mul(amountOfOptions).div(mintedOptions[msg.sender])).mul(_rewardBalance()).div(totalShares); (uint256 strikeToSend, uint256 underlyingToSend) = _unmintOptions(amountOfOptions, msg.sender); IERC20(underlyingAsset()).safeTransfer(msg.sender, underlyingToSend); emit Unmint(msg.sender, amountOfOptions, strikeToSend, underlyingToSend); if (rewardsToSend > 0) { IERC20(rewardAsset).safeTransfer(msg.sender, rewardsToSend); emit RewardsClaimed(msg.sender, rewardsToSend); } }
14,562,837
[ 1, 7087, 87, 4508, 2045, 287, 635, 18305, 310, 1456, 2430, 18, 5087, 848, 1338, 506, 18305, 329, 1323, 326, 4166, 353, 4269, 7708, 18, 225, 3844, 951, 1320, 1021, 3844, 1456, 2430, 358, 506, 18305, 329, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 27701, 474, 12, 11890, 5034, 3844, 951, 1320, 13, 3903, 3849, 27701, 474, 3829, 288, 203, 3639, 389, 14784, 17631, 14727, 24899, 588, 9762, 429, 10726, 10663, 203, 3639, 2254, 5034, 283, 6397, 28878, 273, 261, 30720, 63, 3576, 18, 15330, 8009, 16411, 12, 8949, 951, 1320, 2934, 2892, 12, 81, 474, 329, 1320, 63, 3576, 18, 15330, 5717, 2934, 16411, 24899, 266, 2913, 13937, 1435, 2934, 2892, 12, 4963, 24051, 1769, 203, 203, 3639, 261, 11890, 5034, 609, 2547, 28878, 16, 2254, 5034, 6808, 28878, 13, 273, 389, 318, 81, 474, 1320, 12, 8949, 951, 1320, 16, 1234, 18, 15330, 1769, 203, 203, 3639, 467, 654, 39, 3462, 12, 9341, 6291, 6672, 1435, 2934, 4626, 5912, 12, 3576, 18, 15330, 16, 6808, 28878, 1769, 203, 203, 3639, 3626, 1351, 81, 474, 12, 3576, 18, 15330, 16, 3844, 951, 1320, 16, 609, 2547, 28878, 16, 6808, 28878, 1769, 203, 203, 3639, 309, 261, 266, 6397, 28878, 405, 374, 13, 288, 203, 5411, 467, 654, 39, 3462, 12, 266, 2913, 6672, 2934, 4626, 5912, 12, 3576, 18, 15330, 16, 283, 6397, 28878, 1769, 203, 5411, 3626, 534, 359, 14727, 9762, 329, 12, 3576, 18, 15330, 16, 283, 6397, 28878, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.4; import "./burnattestor.sol"; /// Management contract for a BurnAttestor which can hold extra funds /// @title Custodian /// @dev this contract is mainly to correct issues in case things have gone horribly wrong. /// @author SeqSEE contract Custodian is BurnAttestor { uint256 public balance; uint256 public minLock; /// Deploy a Custodial contract that is also a BurnAttestor constructor(uint256 _attestationsRequired) BurnAttestor(_attestationsRequired){ } /// An owner only method to change the WrappedAsset this VendorRegistry is associated with, use WrappedAsset.setVendorRegistry() to make the required reciprical change on WrappedAsset. /// @param _minLock The minimum amount of MRX in satoshi that a manager may lock function setMinLock(uint256 _minLock) public isOwner { require(_minLock >= 0, "minLock cannot be less than 0"); minLock = _minLock; } /// A management only method to add extra funds that can be manually added by a manager to a vendor's allowance function lockFunds() public payable isManager { require(msg.value >= minLock, "Value less than minLock"); balance = balance + msg.value; } /// A management only method to add to a vendor's available MRX balance, this should only be used to correct balances in case something has gone horribly wrong function addAllowance(address recipient, uint256 amount) public isManager { require(amount > 0, "Amount cannot be less than 0"); pendingWithdraws[recipient] = pendingWithdraws[recipient] + amount; balance = balance - amount; } /// A method to withdraw any available unwrapped vendor funds function withdraw() public virtual override returns (uint256) { require(pendingWithdraws[msg.sender] > 0, "No available balance"); uint256 amount = super.withdraw(); return amount; } }
A management only method to add to a vendor's available MRX balance, this should only be used to correct balances in case something has gone horribly wrong
function addAllowance(address recipient, uint256 amount) public isManager { require(amount > 0, "Amount cannot be less than 0"); pendingWithdraws[recipient] = pendingWithdraws[recipient] + amount; balance = balance - amount; }
2,577,144
[ 1, 37, 11803, 1338, 707, 358, 527, 358, 279, 8556, 1807, 2319, 490, 54, 60, 11013, 16, 333, 1410, 1338, 506, 1399, 358, 3434, 324, 26488, 316, 648, 5943, 711, 22296, 29404, 1533, 715, 7194, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 7009, 1359, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 1071, 353, 1318, 288, 203, 3639, 2583, 12, 8949, 405, 374, 16, 315, 6275, 2780, 506, 5242, 2353, 374, 8863, 203, 3639, 4634, 1190, 9446, 87, 63, 20367, 65, 273, 4634, 1190, 9446, 87, 63, 20367, 65, 397, 3844, 31, 203, 3639, 11013, 273, 11013, 300, 3844, 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 ]
./full_match/97/0x61F2f5ce1C364a15755900859f1021AB49959a2F/sources/project_/contracts/factory.sol
* @dev Creates a beacon proxy, sets user's details and deposits ether into the beacon proxy. External function with access restriction. Emits a {NewProxyAddress} event./
function createEscrowProxy(string memory _dealId) external payable notOwnerOrCommissionWallet { BeaconProxy proxy = new BeaconProxy( beacon, abi.encodeWithSelector( Escrow.initialize.selector, commissionWallet, minimumEscrowAmount, commissionRate, owner(), msg.sender ) ); emit NewProxyAddress(address(proxy), _dealId, commissionRate); setUserDealDetails(_dealId, address(proxy)); }
5,030,192
[ 1, 2729, 279, 29203, 2889, 16, 1678, 729, 1807, 3189, 471, 443, 917, 1282, 225, 2437, 1368, 326, 29203, 2889, 18, 11352, 445, 598, 2006, 9318, 18, 7377, 1282, 279, 288, 1908, 3886, 1887, 97, 871, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 752, 6412, 492, 3886, 12, 1080, 3778, 389, 323, 287, 548, 13, 203, 3639, 3903, 203, 3639, 8843, 429, 203, 3639, 486, 5541, 1162, 799, 3951, 16936, 203, 565, 288, 203, 3639, 4823, 16329, 3886, 2889, 273, 394, 4823, 16329, 3886, 12, 203, 5411, 29203, 16, 203, 5411, 24126, 18, 3015, 1190, 4320, 12, 203, 7734, 512, 1017, 492, 18, 11160, 18, 9663, 16, 203, 7734, 1543, 19710, 16936, 16, 203, 7734, 5224, 6412, 492, 6275, 16, 203, 7734, 1543, 19710, 4727, 16, 203, 7734, 3410, 9334, 203, 7734, 1234, 18, 15330, 203, 5411, 262, 203, 3639, 11272, 203, 3639, 3626, 1166, 3886, 1887, 12, 2867, 12, 5656, 3631, 389, 323, 287, 548, 16, 1543, 19710, 4727, 1769, 203, 3639, 14365, 758, 287, 3790, 24899, 323, 287, 548, 16, 1758, 12, 5656, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-04-01 */ /* BTCult - Stealth Launch Max Wallet: 1.5% Max TX: 1.0% Taxes: 5% on buys, 10% on sells Join us on Telegram: https://t.me/BTCult */ // SPDX-License-Identifier: MIT pragma solidity 0.8.9; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; return msg.data; } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event 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; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract BTCult is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 0; bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("BTCult", "BTCult") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 5; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 10; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 1 * 1e12 * 1e18; maxTransactionAmount = totalSupply * 10 / 1000; // 1.0% Max Transaction maxWallet = totalSupply * 15 / 1000; // 1.5% Max Wallet swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(owner()); // set as marketing wallet devWallet = address(owner()); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable { } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 100000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success,) = address(devWallet).call{value: ethForDev}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } (success,) = address(marketingWallet).call{value: address(this).balance}(""); } function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner { require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes"); require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%"); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool){ lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
Anti-bot and anti-whale mappings and variables exlcude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract BTCult is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 0; bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("BTCult", "BTCult") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 5; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 10; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 1 * 1e12 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply); } receive() external payable { } function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 100000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){ autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, deadAddress, block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } if(contractBalance == 0 || totalTokensToSwap == 0) {return;} function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; (success,) = address(devWallet).call{value: ethForDev}(""); function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } (success,) = address(marketingWallet).call{value: address(this).balance}(""); function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner { require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes"); require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%"); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool){ lastLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit AutoNukeLP(); return true; } function autoBurnLiquidityPairTokens() internal returns (bool){ lastLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000); if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit AutoNukeLP(); return true; } IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit ManualNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){ require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish"); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); if (amountToBurn > 0){ super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } pair.sync(); emit ManualNukeLP(); return true; } IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); }
15,096,350
[ 1, 14925, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 431, 17704, 1317, 628, 1656, 281, 471, 943, 2492, 3844, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 605, 15988, 406, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 11732, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 565, 1758, 1071, 5381, 8363, 1887, 273, 1758, 12, 20, 92, 22097, 1769, 203, 203, 565, 1426, 3238, 7720, 1382, 31, 203, 203, 565, 1758, 1071, 13667, 310, 16936, 31, 203, 565, 1758, 1071, 4461, 16936, 31, 203, 377, 203, 565, 2254, 5034, 1071, 943, 3342, 6275, 31, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 31, 203, 377, 203, 565, 2254, 5034, 1071, 5551, 1290, 14461, 38, 321, 273, 374, 31, 203, 565, 1426, 1071, 12423, 38, 321, 1526, 273, 638, 31, 203, 565, 2254, 5034, 1071, 12423, 38, 321, 13865, 273, 12396, 3974, 31, 203, 565, 2254, 5034, 1071, 1142, 48, 84, 38, 321, 950, 31, 203, 377, 203, 565, 2254, 5034, 1071, 11297, 38, 321, 13865, 273, 5196, 6824, 31, 203, 565, 2254, 5034, 1071, 1142, 25139, 48, 84, 38, 321, 950, 31, 203, 203, 565, 1426, 1071, 8181, 382, 12477, 273, 638, 31, 203, 565, 1426, 1071, 1284, 7459, 3896, 273, 629, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 629, 31, 203, 377, 203, 565, 1426, 1071, 7412, 6763, 1526, 273, 638, 31, 203, 203, 565, 2254, 5034, 1071, 30143, 5269, 2954, 281, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.9; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; /** * @title TeleportrDisburser */ contract TeleportrDisburser is Ownable { /** * @notice A struct holding the address and amount to disbursement. */ struct Disbursement { uint256 amount; address addr; } /// The total number of disbursements processed. uint256 public totalDisbursements; /** * @notice Emitted any time the balance is withdrawn by the owner. * @param owner The current owner and recipient of the funds. * @param balance The current contract balance paid to the owner. */ event BalanceWithdrawn(address indexed owner, uint256 balance); /** * @notice Emitted any time a disbursement is successfuly sent. * @param depositId The unique sequence number identifying the deposit. * @param to The recipient of the disbursement. * @param amount The amount sent to the recipient. */ event DisbursementSuccess(uint256 indexed depositId, address indexed to, uint256 amount); /** * @notice Emitted any time a disbursement fails to send. * @param depositId The unique sequence number identifying the deposit. * @param to The intended recipient of the disbursement. * @param amount The amount intended to be sent to the recipient. */ event DisbursementFailed(uint256 indexed depositId, address indexed to, uint256 amount); /** * @notice Initializes a new TeleportrDisburser contract. */ constructor() { totalDisbursements = 0; } /** * @notice Accepts a list of Disbursements and forwards the amount paid to * the contract to each recipient. The method reverts if there are zero * disbursements, the total amount to forward differs from the amount sent * in the transaction, or the _nextDepositId is unexpected. Failed * disbursements will not cause the method to revert, but will instead be * held by the contract and availabe for the owner to withdraw. * @param _nextDepositId The depositId of the first Dispursement. * @param _disbursements A list of Disbursements to process. */ function disburse(uint256 _nextDepositId, Disbursement[] calldata _disbursements) external payable onlyOwner { // Ensure there are disbursements to process. uint256 _numDisbursements = _disbursements.length; require(_numDisbursements > 0, "No disbursements"); // Ensure the _nextDepositId matches our expected value. uint256 _depositId = totalDisbursements; require(_depositId == _nextDepositId, "Unexpected next deposit id"); unchecked { totalDisbursements += _numDisbursements; } // Ensure the amount sent in the transaction is equal to the sum of the // disbursements. uint256 _totalDisbursed = 0; for (uint256 i = 0; i < _numDisbursements; i++) { _totalDisbursed += _disbursements[i].amount; } require(_totalDisbursed == msg.value, "Disbursement total != amount sent"); // Process disbursements. for (uint256 i = 0; i < _numDisbursements; i++) { uint256 _amount = _disbursements[i].amount; address _addr = _disbursements[i].addr; // Deliver the dispursement amount to the receiver. If the // disbursement fails, the amount will be kept by the contract // rather than reverting to prevent blocking progress on other // disbursements. // slither-disable-next-line calls-loop,reentrancy-events (bool success, ) = _addr.call{ value: _amount, gas: 2300 }(""); if (success) emit DisbursementSuccess(_depositId, _addr, _amount); else emit DisbursementFailed(_depositId, _addr, _amount); unchecked { _depositId += 1; } } } /** * @notice Sends the contract's current balance to the owner. */ function withdrawBalance() external onlyOwner { address _owner = owner(); uint256 balance = address(this).balance; emit BalanceWithdrawn(_owner, balance); payable(_owner).transfer(balance); } }
* @notice Emitted any time the balance is withdrawn by the owner. @param owner The current owner and recipient of the funds. @param balance The current contract balance paid to the owner./
event BalanceWithdrawn(address indexed owner, uint256 balance);
1,010,830
[ 1, 1514, 11541, 1281, 813, 326, 11013, 353, 598, 9446, 82, 635, 326, 3410, 18, 225, 3410, 1021, 783, 3410, 471, 8027, 434, 326, 284, 19156, 18, 225, 11013, 1021, 783, 6835, 11013, 30591, 358, 326, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 871, 30918, 1190, 9446, 82, 12, 2867, 8808, 3410, 16, 2254, 5034, 11013, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-09-13 */ pragma solidity ^0.5.0; /** * @title Proxy * @dev Gives the possibility to delegate any call to a foreign implementation. */ contract Proxy { /** * @dev Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ function() external payable { address _impl = implementation(); require(_impl != address(0)); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize) let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0) let size := returndatasize returndatacopy(ptr, 0, size) switch result case 0 {revert(ptr, size)} default {return (ptr, size)} } } /** * @dev Tells the address of the implementation where every call will be delegated. * @return address of the implementation to which it will be delegated */ function implementation() public view returns (address); } /** * @title UpgradeabilityProxy * @dev This contract represents a proxy where the implementation address to which it will delegate can be upgraded */ contract UpgradeabilityProxy is Proxy { /** * @dev This event will be emitted every time the implementation gets upgraded * @param implementation representing the address of the upgraded implementation */ event Upgraded(address indexed implementation); // Storage position of the address of the current implementation bytes32 private constant IMPLEMENTATION_POSITION = keccak256("fixed.price.trade.1155.proxy.implementation"); /** * @dev Constructor function */ constructor() public {} /** * @dev Tells the address of the current implementation * @return address of the current implementation */ function implementation() public view returns (address impl) { bytes32 position = IMPLEMENTATION_POSITION; assembly { impl := sload(position) } } /** * @dev Sets the address of the current implementation * @param _newImplementation address representing the new implementation to be set */ function _setImplementation(address _newImplementation) internal { bytes32 position = IMPLEMENTATION_POSITION; assembly { sstore(position, _newImplementation) } } /** * @dev Upgrades the implementation address * @param _newImplementation representing the address of the new implementation to be set */ function _upgradeTo(address _newImplementation) internal { address currentImplementation = implementation(); require(currentImplementation != _newImplementation); _setImplementation(_newImplementation); emit Upgraded(_newImplementation); } } /** * @title OwnedUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with basic authorization control functionalities */ contract OwnedUpgradeabilityProxy is UpgradeabilityProxy { /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event ProxyOwnershipTransferred(address previousOwner, address newOwner); // Storage position of the owner of the contract bytes32 private constant PROXY_OWNER_POSITION = keccak256("fixed.price.trade.1155.proxy.owner"); /** * @dev the constructor sets the original owner of the contract to the sender account. */ constructor(address _implementation) public { _setUpgradeabilityOwner(msg.sender); _upgradeTo(_implementation); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyProxyOwner() { require(msg.sender == proxyOwner()); _; } /** * @dev Tells the address of the owner * @return the address of the owner */ function proxyOwner() public view returns (address owner) { bytes32 position = PROXY_OWNER_POSITION; assembly { owner := sload(position) } } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferProxyOwnership(address _newOwner) public onlyProxyOwner { require(_newOwner != address(0)); _setUpgradeabilityOwner(_newOwner); emit ProxyOwnershipTransferred(proxyOwner(), _newOwner); } /** * @dev Allows the proxy owner to upgrade the current version of the proxy. * @param _implementation representing the address of the new implementation to be set. */ function upgradeTo(address _implementation) public onlyProxyOwner { _upgradeTo(_implementation); } /** * @dev Sets the address of the owner */ function _setUpgradeabilityOwner(address _newProxyOwner) internal { bytes32 position = PROXY_OWNER_POSITION; assembly { sstore(position, _newProxyOwner) } } }
* @title OwnedUpgradeabilityProxy @dev This contract combines an upgradeability proxy with basic authorization control functionalities/ Storage position of the owner of the contract
contract OwnedUpgradeabilityProxy is UpgradeabilityProxy { event ProxyOwnershipTransferred(address previousOwner, address newOwner); bytes32 private constant PROXY_OWNER_POSITION = keccak256("fixed.price.trade.1155.proxy.owner"); constructor(address _implementation) public { _setUpgradeabilityOwner(msg.sender); _upgradeTo(_implementation); } modifier onlyProxyOwner() { require(msg.sender == proxyOwner()); _; } function proxyOwner() public view returns (address owner) { bytes32 position = PROXY_OWNER_POSITION; assembly { owner := sload(position) } } function proxyOwner() public view returns (address owner) { bytes32 position = PROXY_OWNER_POSITION; assembly { owner := sload(position) } } function transferProxyOwnership(address _newOwner) public onlyProxyOwner { require(_newOwner != address(0)); _setUpgradeabilityOwner(_newOwner); emit ProxyOwnershipTransferred(proxyOwner(), _newOwner); } function upgradeTo(address _implementation) public onlyProxyOwner { _upgradeTo(_implementation); } function _setUpgradeabilityOwner(address _newProxyOwner) internal { bytes32 position = PROXY_OWNER_POSITION; assembly { sstore(position, _newProxyOwner) } } function _setUpgradeabilityOwner(address _newProxyOwner) internal { bytes32 position = PROXY_OWNER_POSITION; assembly { sstore(position, _newProxyOwner) } } }
7,956,823
[ 1, 5460, 329, 10784, 2967, 3886, 225, 1220, 6835, 30933, 392, 8400, 2967, 2889, 598, 5337, 6093, 3325, 18699, 1961, 19, 5235, 1754, 434, 326, 3410, 434, 326, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 14223, 11748, 10784, 2967, 3886, 353, 17699, 2967, 3886, 288, 203, 565, 871, 7659, 5460, 12565, 1429, 4193, 12, 2867, 2416, 5541, 16, 1758, 394, 5541, 1769, 203, 203, 565, 1731, 1578, 3238, 5381, 26910, 67, 29602, 67, 15258, 273, 417, 24410, 581, 5034, 2932, 12429, 18, 8694, 18, 20077, 18, 2499, 2539, 18, 5656, 18, 8443, 8863, 203, 203, 565, 3885, 12, 2867, 389, 30810, 13, 1071, 288, 203, 3639, 389, 542, 10784, 2967, 5541, 12, 3576, 18, 15330, 1769, 203, 3639, 389, 15097, 774, 24899, 30810, 1769, 203, 565, 289, 203, 203, 565, 9606, 1338, 3886, 5541, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 2889, 5541, 10663, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 2889, 5541, 1435, 1071, 1476, 1135, 261, 2867, 3410, 13, 288, 203, 3639, 1731, 1578, 1754, 273, 26910, 67, 29602, 67, 15258, 31, 203, 3639, 19931, 288, 203, 5411, 3410, 519, 272, 945, 12, 3276, 13, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 2889, 5541, 1435, 1071, 1476, 1135, 261, 2867, 3410, 13, 288, 203, 3639, 1731, 1578, 1754, 273, 26910, 67, 29602, 67, 15258, 31, 203, 3639, 19931, 288, 203, 5411, 3410, 519, 272, 945, 12, 3276, 13, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 7412, 3886, 5460, 12565, 12, 2867, 389, 2704, 5541, 13, 1071, 1338, 3886, 5541, 288, 203, 3639, 2583, 24899, 2704, 5541, 480, 1758, 12, 20, 10019, 203, 3639, 389, 542, 10784, 2967, 5541, 24899, 2704, 5541, 1769, 203, 2 ]
./full_match/80001/0x538AeF2BeaDC13009f94aaF82255050ECF222252/sources/FloristMarket.sol
commucinating by key
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
9,474,044
[ 1, 5702, 5286, 267, 1776, 635, 498, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5666, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 2316, 19, 654, 39, 2499, 2539, 19, 654, 39, 2499, 2539, 18, 18281, 14432, 1377, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x9965cCd16803432C6a0842f1D5690f32E427aEDd/sources/contracts/ERC721MP.sol
* @dev See {IERC721-setApprovalForAll}./
function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); }
8,470,555
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 17, 542, 23461, 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, 565, 445, 444, 23461, 1290, 1595, 12, 2867, 3726, 16, 1426, 20412, 13, 1071, 5024, 3849, 288, 203, 3639, 309, 261, 9497, 422, 389, 3576, 12021, 10756, 15226, 1716, 685, 537, 774, 11095, 5621, 203, 3639, 389, 9497, 12053, 4524, 63, 67, 3576, 12021, 1435, 6362, 9497, 65, 273, 20412, 31, 203, 3639, 3626, 1716, 685, 1125, 1290, 1595, 24899, 3576, 12021, 9334, 3726, 16, 20412, 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 ]
./partial_match/1/0x7119e8fe4a050CC267d5830F99adb309430F8a85/sources/Mogladys.sol
* @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]; }
3,717,298
[ 1, 13652, 358, 1135, 326, 460, 3627, 598, 1375, 856, 8338, 225, 531, 12, 21, 2934, 9637, 486, 15226, 309, 1375, 856, 68, 353, 486, 316, 326, 852, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 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, 389, 698, 967, 12, 203, 3639, 1635, 2502, 852, 16, 203, 3639, 1731, 1578, 498, 203, 565, 262, 3238, 1476, 1135, 261, 6430, 16, 1731, 1578, 13, 288, 203, 3639, 2254, 5034, 498, 1016, 273, 852, 6315, 11265, 63, 856, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xbEE493A1Ab404D3F1995e9fE0Bd21EAFD88827a2/sources/contracts/AnkyTest8.sol
Check if there is still supply available Check the amount of eth sent Check if the address already owns an Anky Mint the anky that comes now Prepare for the next mint
function mint() public payable { require(_lastMinted <= MAX_SUPPLY, "The Ankyverse is complete"); require(PRICE <= msg.value, "You need to send a bit more of eth."); require(balanceOf(msg.sender) == 0, "You already have an Anky"); _mint(msg.sender, _lastMinted); _lastMinted++; }
1,953,687
[ 1, 1564, 309, 1915, 353, 4859, 14467, 2319, 2073, 326, 3844, 434, 13750, 3271, 2073, 309, 326, 1758, 1818, 29065, 392, 1922, 18465, 490, 474, 326, 392, 18465, 716, 14535, 2037, 7730, 364, 326, 1024, 312, 474, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1435, 1071, 8843, 429, 288, 203, 3639, 2583, 24899, 2722, 49, 474, 329, 1648, 225, 4552, 67, 13272, 23893, 16, 315, 1986, 1922, 18465, 2476, 353, 3912, 8863, 203, 3639, 2583, 12, 7698, 1441, 1648, 1234, 18, 1132, 16, 315, 6225, 1608, 358, 1366, 279, 2831, 1898, 434, 13750, 1199, 1769, 203, 3639, 2583, 12, 12296, 951, 12, 3576, 18, 15330, 13, 422, 374, 16, 315, 6225, 1818, 1240, 392, 1922, 18465, 8863, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 389, 2722, 49, 474, 329, 1769, 203, 3639, 389, 2722, 49, 474, 329, 9904, 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 ]
pragma solidity 0.5.12; import "./interface/IHandler.sol"; import "./library/DSAuth.sol"; import "./library/SafeMath.sol"; contract Dispatcher is DSAuth { using SafeMath for uint256; /** * @dev List all handler contract address. */ address[] public handlers; address public defaultHandler; /** * @dev Deposit ratio of each handler contract. * Notice: the sum of all deposit ratio should be 1000000. */ mapping(address => uint256) public proportions; uint256 public constant totalProportion = 1000000; /** * @dev map: handlerAddress -> true/false, * Whether the handler has been added or not. */ mapping(address => bool) public isHandlerActive; /** * @dev Set original handler contract and its depoist ratio. * Notice: the sum of all deposit ratio should be 1000000. * @param _handlers The original support handler contract. * @param _proportions The original depoist ratio of support handler. */ constructor(address[] memory _handlers, uint256[] memory _proportions) public { setHandlers(_handlers, _proportions); } /** * @dev Sort handlers in descending order of the liquidity in each market. * @param _data The data to sort, which are the handlers here. * @param _left The index of data to start sorting. * @param _right The index of data to end sorting. * @param _token Asset address. */ function sortByLiquidity( address[] memory _data, int256 _left, int256 _right, address _token ) internal { int256 i = _left; int256 j = _right; if (i == j) return; uint256 _pivot = IHandler(_data[uint256(_left + (_right - _left) / 2)]) .getRealLiquidity(_token); while (i <= j) { while ( IHandler(_data[uint256(i)]).getRealLiquidity(_token) > _pivot ) i++; while ( _pivot > IHandler(_data[uint256(j)]).getRealLiquidity(_token) ) j--; if (i <= j) { (_data[uint256(i)], _data[uint256(j)]) = ( _data[uint256(j)], _data[uint256(i)] ); i++; j--; } } if (_left < j) sortByLiquidity(_data, _left, j, _token); if (i < _right) sortByLiquidity(_data, i, _right, _token); } /************************/ /*** Admin Operations ***/ /************************/ /** * @dev Replace current handlers with _handlers and corresponding _proportions, * @param _handlers The list of new handlers, the 1st one will act as default hanlder. * @param _proportions The list of corresponding proportions. */ function setHandlers( address[] memory _handlers, uint256[] memory _proportions ) private { require( _handlers.length == _proportions.length && _handlers.length > 0, "setHandlers: handlers & proportions should not have 0 or different lengths" ); // The 1st will act as the default handler. defaultHandler = _handlers[0]; uint256 _sum = 0; for (uint256 i = 0; i < _handlers.length; i++) { require( _handlers[i] != address(0), "setHandlers: handler address invalid" ); // Do not allow to set the same handler twice require( !isHandlerActive[_handlers[i]], "setHandlers: handler address already exists" ); _sum = _sum.add(_proportions[i]); handlers.push(_handlers[i]); proportions[_handlers[i]] = _proportions[i]; isHandlerActive[_handlers[i]] = true; } // The sum of proportions should be 1000000. require( _sum == totalProportion, "the sum of proportions must be 1000000" ); } /** * @dev Update proportions of the handlers. * @param _handlers List of the handlers to update. * @param _proportions List of the corresponding proportions to update. */ function updateProportions( address[] memory _handlers, uint256[] memory _proportions ) public auth { require( _handlers.length == _proportions.length && handlers.length == _proportions.length, "updateProportions: handlers & proportions must match the current length" ); uint256 _sum = 0; for (uint256 i = 0; i < _proportions.length; i++) { for (uint256 j = 0; j < i; j++) { require( _handlers[i] != _handlers[j], "updateProportions: input handler contract address is duplicate" ); } require( isHandlerActive[_handlers[i]], "updateProportions: the handler contract address does not exist" ); _sum = _sum.add(_proportions[i]); proportions[_handlers[i]] = _proportions[i]; } // The sum of `proportions` should be 1000000. require( _sum == totalProportion, "the sum of proportions must be 1000000" ); } /** * @dev Add new handler. * Notice: the corresponding proportion of the new handler is 0. * @param _handlers List of the new handlers to add. */ function addHandlers(address[] memory _handlers) public auth { for (uint256 i = 0; i < _handlers.length; i++) { require( !isHandlerActive[_handlers[i]], "addHandlers: handler address already exists" ); require( _handlers[i] != address(0), "addHandlers: handler address invalid" ); handlers.push(_handlers[i]); proportions[_handlers[i]] = 0; isHandlerActive[_handlers[i]] = true; } } /** * @dev Reset handlers and corresponding proportions, will delete the old ones. * @param _handlers The list of new handlers. * @param _proportions the list of corresponding proportions. */ function resetHandlers( address[] calldata _handlers, uint256[] calldata _proportions ) external auth { address[] memory _oldHandlers = handlers; for (uint256 i = 0; i < _oldHandlers.length; i++) { delete proportions[_oldHandlers[i]]; delete isHandlerActive[_oldHandlers[i]]; } defaultHandler = address(0); delete handlers; setHandlers(_handlers, _proportions); } /** * @dev Update the default handler. * @param _defaultHandler The default handler to update. */ function updateDefaultHandler(address _defaultHandler) public auth { require( _defaultHandler != address(0), "updateDefaultHandler: New defaultHandler should not be zero address" ); address _oldDefaultHandler = defaultHandler; require( _defaultHandler != _oldDefaultHandler, "updateDefaultHandler: Old and new address cannot be the same." ); handlers[0] = _defaultHandler; proportions[_defaultHandler] = proportions[_oldDefaultHandler]; isHandlerActive[_defaultHandler] = true; delete proportions[_oldDefaultHandler]; delete isHandlerActive[_oldDefaultHandler]; defaultHandler = _defaultHandler; } /***********************/ /*** User Operations ***/ /***********************/ /** * @dev Query the current handlers and the corresponding proportions. * @return Return two arrays, the current handlers, * and the corresponding proportions. */ function getHandlers() external view returns (address[] memory, uint256[] memory) { address[] memory _handlers = handlers; uint256[] memory _proportions = new uint256[](_handlers.length); for (uint256 i = 0; i < _proportions.length; i++) _proportions[i] = proportions[_handlers[i]]; return (_handlers, _proportions); } /** * @dev According to the proportion, calculate deposit amount for each handler. * @param _amount The amount to deposit. * @return Return two arrays, the current handlers, * and the corresponding deposit amounts. */ function getDepositStrategy(uint256 _amount) external view returns (address[] memory, uint256[] memory) { address[] memory _handlers = handlers; uint256[] memory _amounts = new uint256[](_handlers.length); uint256 _sum = 0; uint256 _res = _amount; uint256 _lastIndex = _amounts.length.sub(1); for (uint256 i = 0; ; i++) { // Return empty strategy if any handler is paused for abnormal case, // resulting further failure with mint and burn if (IHandler(_handlers[i]).paused()) { delete _handlers; delete _amounts; break; } // The last handler gets the remaining amount without check proportion. if (i == _lastIndex) { _amounts[i] = _res.sub(_sum); break; } // Calculate deposit amount according to the proportion, _amounts[i] = _res.mul(proportions[_handlers[i]]) / totalProportion; _sum = _sum.add(_amounts[i]); } return (_handlers, _amounts); } /** * @dev Provide a strategy to withdraw, now sort handlers in descending order of the liquidity. * @param _token The token to withdraw. * @param _amount The amount to withdraw, including exchange fees between tokens. * @return Return two arrays, the handlers, * and the corresponding withdraw amount. */ function getWithdrawStrategy(address _token, uint256 _amount) external returns (address[] memory, uint256[] memory) { address[] memory _handlers = handlers; // Sort handlers in descending order of the liquidity. if (_handlers.length > 2) sortByLiquidity( _handlers, int256(1), int256(_handlers.length - 1), _token ); uint256[] memory _amounts = new uint256[](_handlers.length); uint256 _balance; uint256 _res = _amount; uint256 _lastIndex = _amounts.length.sub(1); for (uint256 i = 0; i < _handlers.length; i++) { // Return empty strategy if any handler is paused for abnormal case, // resulting further failure with mint and burn if (IHandler(_handlers[i]).paused()) { delete _handlers; delete _amounts; break; } // Continue to check whether all handlers are unpaused if (_res == 0) continue; if (i == _lastIndex) { _amounts[i] = _res; break; } // The maximum amount can be withdrown from market. _balance = IHandler(_handlers[i]).getRealLiquidity(_token); _amounts[i] = _balance > _res ? _res : _balance; _res = _res.sub(_amounts[i]); } return (_handlers, _amounts); } }
The maximum amount can be withdrown from market.
_balance = IHandler(_handlers[i]).getRealLiquidity(_token);
6,431,039
[ 1, 1986, 4207, 3844, 848, 506, 598, 72, 26253, 628, 13667, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 389, 12296, 273, 467, 1503, 24899, 11046, 63, 77, 65, 2934, 588, 6955, 48, 18988, 24237, 24899, 2316, 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 ]
//SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155Holder.sol"; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "../interfaces/IEscrow.sol"; import "../interfaces/IdOTC.sol"; import "../interfaces/INFTdOTC.sol"; contract SwarmDOTCEscrow is ERC1155Holder, IEscrow, AccessControl { using SafeMath for uint256; uint256 public constant BPSNUMBER = 10**27; bool public isFrozen = false; address internal dOTC; address internal nftDOTC; bytes32 public constant ESCROW_MANAGER_ROLE = keccak256("ESCROW_MANAGER_ROLE"); bytes32 public constant NFT_ESCROW_MANAGER_ROLE = keccak256("NFT_ESCROW_MANAGER_ROLE"); struct Deposit { uint256 offerId; address maker; uint256 amountDeposited; uint256[] nftIds; uint256[] nftAmounts; bool isFrozen; } // This determine is the escrow is frozen mapping(uint256 => Deposit) private deposits; mapping(uint256 => Deposit) private nftDeposits; event offerFrozen(uint256 indexed offerId, address indexed offerOwner, address frozenBy); event offerUnFrozen(uint256 indexed offerId, address indexed offerOwner, address frozenBy); event EscrowFrozen(address indexed frozenBy, address calledBy); event UnFreezeEscrow(address indexed unFreezeBy, address calledBy); event offerRemove(uint256 indexed offerId, address indexed offerOwner, uint256 amountReverted, address frozenBy); event Withdraw(uint256 indexed offerId, uint256 indexed orderId, address indexed taker, uint256 amount); event WithdrawNFT(uint256 indexed nftOfferId, uint256 indexed nftOrderId, address indexed taker); event canceledNftDeposit(uint256 indexed nftOfferId, address nftAddress, address canceledBy); constructor() { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** * @dev Grants ESCROW_MANAGER_ROLE to `_escrowManager`. * * Requirements: * * - the caller must have ``role``'s admin role. */ function setEscrowManager(address _escrowManager) public { grantRole(ESCROW_MANAGER_ROLE, _escrowManager); } /** * @dev Grants ESCROW_MANAGER_ROLE to `_escrowManager`. * * Requirements: * * - the caller must have ``role``'s admin role. */ function setNFTEscrowManager(address _escrowManager) public { grantRole(NFT_ESCROW_MANAGER_ROLE, _escrowManager); } /** * @dev setMakerDeposit initial the deposit of the maker. * @param _offerId uint256 the offer ID */ function setMakerDeposit(uint256 _offerId) external override isEscrowFrozen onlyEscrowManager { uint256[] memory emptyArray; deposits[_offerId] = Deposit( _offerId, IdOTC(dOTC).getOfferOwner(_offerId), IdOTC(dOTC).getOffer(_offerId).amountIn, emptyArray, emptyArray, false ); } /** * @dev setNFTDeposit initial the deposit of the maker. * @param _offerId uint256 the offer ID */ function setNFTDeposit(uint256 _offerId) external override isEscrowFrozen onlyNftEscrowManager { nftDeposits[_offerId] = Deposit( _offerId, INFTdOTC(nftDOTC).getNftOfferOwner(_offerId), 0, INFTdOTC(nftDOTC).getNftOffer(_offerId).nftIds, INFTdOTC(nftDOTC).getNftOffer(_offerId).nftAmounts, false ); } /** * @dev withdrawDeposit from the Escrow to to the taker address * @param offerId the Id of the offer * @param orderId the order id */ function withdrawDeposit(uint256 offerId, uint256 orderId) external override isEscrowFrozen isDepositFrozen(offerId) onlyEscrowManager { address token = IdOTC(dOTC).getOffer(offerId).tokenInAddress; address _receiver = IdOTC(dOTC).getTakerOrders(orderId).takerAddress; uint256 standardAmount = IdOTC(dOTC).getTakerOrders(orderId).amountToReceive; uint256 minExpectedAmount = IdOTC(dOTC).getTakerOrders(orderId).minExpectedAmount; uint256 _amount = unstandardisedNumber(standardAmount, token); require(deposits[offerId].amountDeposited >= standardAmount, "Invalid Amount"); require(minExpectedAmount <= standardAmount, "Invalid Transaction"); deposits[offerId].amountDeposited -= standardAmount; safeInternalTransfer(token, _receiver, _amount); emit Withdraw(offerId, orderId, _receiver, _amount); } /** * @dev withdrawNftDeposit from the Escrow to to the taker address * @param _nftOfferId the Id of the offer * @param _nftOrderId the order id */ function withdrawNftDeposit(uint256 _nftOfferId, uint256 _nftOrderId) external override isEscrowFrozen isNftDepositFrozen(_nftOfferId) onlyNftEscrowManager { address _receiver = INFTdOTC(nftDOTC).getNftOrders(_nftOrderId).takerAddress; address _nftAddress = INFTdOTC(nftDOTC).getNftOffer(_nftOfferId).nftAddress; IERC1155(_nftAddress).setApprovalForAll(nftDOTC, true); emit WithdrawNFT(_nftOfferId, _nftOrderId, _receiver); } function cancelNftDeposit(uint256 nftOfferId) external override isEscrowFrozen onlyNftEscrowManager { address nftAddress = INFTdOTC(nftDOTC).getNftOffer(nftOfferId).nftAddress; IERC1155(nftAddress).setApprovalForAll(nftDOTC, true); emit canceledNftDeposit(nftOfferId, nftAddress, msg.sender); } /** * @dev cancelDeposit */ function cancelDeposit( uint256 offerId, address token, address maker, uint256 _amountToSend ) external override onlyEscrowManager returns (bool status) { deposits[offerId].amountDeposited = 0; safeInternalTransfer(token, maker, _amountToSend); return true; } /** * @dev safeInternalTransfer Asset from the escrow; revert transaction if failed * @param token address * @param _receiver address * @param _amount uint256 */ function safeInternalTransfer( address token, address _receiver, uint256 _amount ) internal { require(_amount != 0, "Amount is 0"); require(ERC20(token).transfer(_receiver, _amount), "Transfer failed and reverted."); } /** * @dev freezeEscrow this hibernate the escrow smart contract * Requirements: * Sender must be assinged ESCROW_MANAGER_ROLE and Also DOTC_ADMIN_ROLE * @return status bool */ function freezeEscrow(address _account) external override onlyEscrowManager returns (bool status) { isFrozen = true; emit EscrowFrozen(msg.sender, _account); return true; } /** * @dev unFreezeEscrow this set the escorw to active * Requirments: * Sender must be assinged ESCROW_MANAGER_ROLE and Also DOTC_ADMIN_ROLE * @param _account address * @return status bool */ function unFreezeEscrow(address _account) external override onlyEscrowManager returns (bool status) { isFrozen = false; emit UnFreezeEscrow(msg.sender, _account); return true; } /** * @dev setdOTCAddress * Requirements: * Sender must be assinged ESCROW_MANAGER_ROLE * @return status bool */ function setdOTCAddress(address _token) external override onlyEscrowManager returns (bool status) { dOTC = _token; return true; } /** * @dev setNFTDOTCAddress * Requirements: * Sender must be assinged ESCROW_MANAGER_ROLE * @return status bool */ function setNFTDOTCAddress(address _token) external override onlyNftEscrowManager returns (bool status) { nftDOTC = _token; return true; } /** * @dev freezeOneDeposit this freeze a singular offer on the escrow smart contract * Requirements: * Sender must be assinged ESCROW_MANAGER_ROLE * @param offerId uin2t256 * @return status bool */ function freezeOneDeposit(uint256 offerId, address _account) external override onlyEscrowManager returns (bool status) { deposits[offerId].isFrozen = true; emit offerFrozen(offerId, deposits[offerId].maker, _account); return true; } /** * @dev unFreezeOneDeposit this unfreeze a singular offer on the escrow smart contract * Requirements: * Sender must be assinged ESCROW_MANAGER_ROLE * @param offerId uin2t256 * @return status bool */ function unFreezeOneDeposit(uint256 offerId, address _account) external override onlyEscrowManager returns (bool status) { deposits[offerId].isFrozen = false; emit offerUnFrozen(offerId, deposits[offerId].maker, _account); return true; } /** * @dev removeOffer this return the funds from the escrow to the maker * Requirements: * Sender must be assinged ESCROW_MANAGER_ROLE * @param offerId uin2t256 * @return status bool */ function removeOffer(uint256 offerId, address _account) external override onlyEscrowManager returns (bool status) { uint256 _amount = deposits[offerId].amountDeposited; deposits[offerId].isFrozen = true; deposits[offerId].amountDeposited = 0; safeInternalTransfer(IdOTC(dOTC).getOffer(offerId).tokenInAddress, deposits[offerId].maker, _amount); emit offerRemove(offerId, deposits[offerId].maker, _amount, _account); return true; } function standardiseNumber(uint256 amount, address _token) internal view returns (uint256) { uint8 decimal = ERC20(_token).decimals(); return amount.mul(BPSNUMBER).div(10**decimal); } function unstandardisedNumber(uint256 _amount, address _token) internal view returns (uint256) { uint8 decimal = ERC20(_token).decimals(); return _amount.mul(10**decimal).div(BPSNUMBER); } modifier isEscrowFrozen() { require(isFrozen == false, "Escrow is Frozen"); _; } modifier onlyEscrowManager() { require(hasRole(ESCROW_MANAGER_ROLE, _msgSender()), "must have escrow manager role"); _; } modifier onlyNftEscrowManager() { require(hasRole(NFT_ESCROW_MANAGER_ROLE, _msgSender()), "must have escrow manager role"); _; } modifier isDepositFrozen(uint256 offerId) { require(deposits[offerId].isFrozen == false, "offer is frozen"); _; } modifier isNftDepositFrozen(uint256 offerId) { require(nftDeposits[offerId].isFrozen == false, "offer is frozen"); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./ERC1155Receiver.sol"; /** * @dev _Available since v3.1._ */ contract ERC1155Holder is ERC1155Receiver { function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived(address, address, uint256[] memory, uint256[] memory, bytes memory) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/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: GPL-3.0-only pragma solidity ^0.7.0; /** * @title IEscrow * @author Protofire * @dev Ilamini Dagogo for Protofire. * */ interface IEscrow { function setMakerDeposit(uint256 _offerId) external; function setNFTDeposit(uint256 _offerId) external; function withdrawDeposit(uint256 offerId, uint256 orderId) external; function withdrawNftDeposit(uint256 _nftOfferId, uint256 _nftOrderId) external; function freezeEscrow(address _account) external returns (bool); function setdOTCAddress(address _token) external returns (bool); function freezeOneDeposit(uint256 offerId, address _account) external returns (bool); function unFreezeOneDeposit(uint256 offerId, address _account) external returns (bool); function unFreezeEscrow(address _account) external returns (bool status); function cancelDeposit( uint256 offerId, address token, address maker, uint256 _amountToSend ) external returns (bool status); function cancelNftDeposit(uint256 nftOfferId) external; function removeOffer(uint256 offerId, address _account) external returns (bool status); function setNFTDOTCAddress(address _token) external returns (bool status); } //SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; /** * @title IEscrow * @author Protofire * @dev Ilamini Dagogo for Protofire. * */ interface IdOTC { /** @dev Offer Stucture */ struct Offer { bool isNft; address maker; uint256 offerId; uint256[] nftIds; // list nft ids bool fullyTaken; uint256 amountIn; // offer amount uint256 offerFee; uint256 unitPrice; uint256 amountOut; // the amount to be receive by the maker address nftAddress; uint256 expiryTime; uint256 offerPrice; OfferType offerType; // can be PARTIAL or FULL uint256[] nftAmounts; address escrowAddress; address specialAddress; // makes the offer avaiable for one account. address tokenInAddress; // Token to exchange for another uint256 availableAmount; // available amount address tokenOutAddress; // Token to receive by the maker } struct Order { uint256 offerId; uint256 amountToSend; // the amount the taker sends to the maker address takerAddress; uint256 amountToReceive; uint256 minExpectedAmount; // the amount the taker is to recieve } enum OfferType { PARTIAL, FULL } function getOfferOwner(uint256 offerId) external view returns (address owner); function getOffer(uint256 offerId) external view returns (Offer memory offer); function getTaker(uint256 orderId) external view returns (address taker); function getTakerOrders(uint256 orderId) external view returns (Order memory order); } //SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; /** * @title IEscrow * @author Protofire * @dev Ilamini Dagogo for Protofire. * */ interface INFTdOTC { /** @dev Offer Stucture */ struct Offer { bool isNft; address maker; uint256 offerId; uint256[] nftIds; // list nft ids bool fullyTaken; uint256 amountIn; // offer amount uint256 offerFee; uint256 unitPrice; uint256 amountOut; // the amount to be receive by the maker address nftAddress; uint256 expiryTime; uint256 offerPrice; OfferType offerType; // can be PARTIAL or FULL uint256[] nftAmounts; address escrowAddress; address specialAddress; // makes the offer avaiable for one account. address tokenInAddress; // Token to exchange for another uint256 availableAmount; // available amount address tokenOutAddress; // Token to receive by the maker } struct NftOrder { uint256 offerId; uint256[] nftIds; uint256 amountPaid; uint256[] nftAmounts; address takerAddress; } enum OfferType { PARTIAL, FULL } function getNftOfferOwner(uint256 _nftOfferId) external view returns (address owner); function getNftOffer(uint256 _nftOfferId) external view returns (Offer memory offer); function getNftTaker(uint256 _nftOrderId) external view returns (address taker); function getNftOrders(uint256 _nftOrderId) external view returns (NftOrder memory order); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC1155Receiver.sol"; import "../../introspection/ERC165.sol"; /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { constructor() { _registerInterface( ERC1155Receiver(0).onERC1155Received.selector ^ ERC1155Receiver(0).onERC1155BatchReceived.selector ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../introspection/IERC165.sol"; /** * _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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 () { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.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(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
SPDX-License-Identifier: GPL-3.0-only* @title IEscrow @author Protofire @dev Ilamini Dagogo for Protofire./
interface INFTdOTC { @dev Offer Stucture function getOfferOwner(uint256 offerId) external view returns (address owner); function getOffer(uint256 offerId) external view returns (Offer memory offer); function getTaker(uint256 orderId) external view returns (address taker); function getTakerOrders(uint256 orderId) external view returns (Order memory order); } pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; struct Offer { bool isNft; address maker; uint256 offerId; bool fullyTaken; uint256 offerFee; uint256 unitPrice; address nftAddress; uint256 expiryTime; uint256 offerPrice; uint256[] nftAmounts; address escrowAddress; } struct NftOrder { uint256 offerId; uint256[] nftIds; uint256 amountPaid; uint256[] nftAmounts; address takerAddress; } enum OfferType { PARTIAL, FULL } }
1,143,771
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 4948, 48, 17, 23, 18, 20, 17, 3700, 225, 467, 6412, 492, 225, 1186, 88, 792, 577, 225, 467, 28448, 8767, 463, 346, 717, 83, 364, 1186, 88, 792, 577, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 2120, 4464, 72, 1974, 39, 288, 203, 3639, 632, 5206, 25753, 934, 853, 594, 7010, 203, 565, 445, 336, 10513, 5541, 12, 11890, 5034, 10067, 548, 13, 3903, 1476, 1135, 261, 2867, 3410, 1769, 203, 203, 565, 445, 336, 10513, 12, 11890, 5034, 10067, 548, 13, 3903, 1476, 1135, 261, 10513, 3778, 10067, 1769, 203, 203, 565, 445, 3181, 6388, 12, 11890, 5034, 20944, 13, 3903, 1476, 1135, 261, 2867, 268, 6388, 1769, 203, 203, 565, 445, 3181, 6388, 16528, 12, 11890, 5034, 20944, 13, 3903, 1476, 1135, 261, 2448, 3778, 1353, 1769, 203, 97, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 27, 18, 20, 31, 203, 683, 9454, 23070, 10336, 45, 7204, 58, 22, 31, 203, 203, 565, 1958, 25753, 288, 203, 3639, 1426, 8197, 1222, 31, 203, 3639, 1758, 312, 6388, 31, 203, 3639, 2254, 5034, 10067, 548, 31, 203, 3639, 1426, 7418, 27486, 31, 203, 3639, 2254, 5034, 10067, 14667, 31, 203, 3639, 2254, 5034, 2836, 5147, 31, 203, 3639, 1758, 290, 1222, 1887, 31, 203, 3639, 2254, 5034, 10839, 950, 31, 203, 3639, 2254, 5034, 10067, 5147, 31, 203, 3639, 2254, 5034, 8526, 290, 1222, 6275, 87, 31, 203, 3639, 1758, 2904, 492, 1887, 31, 203, 565, 289, 203, 203, 565, 1958, 423, 1222, 2448, 288, 203, 3639, 2254, 5034, 10067, 548, 31, 203, 3639, 2254, 5034, 8526, 290, 1222, 2673, 31, 203, 3639, 2254, 5034, 3844, 16507, 350, 31, 203, 3639, 2254, 5034, 8526, 290, 1222, 6275, 87, 31, 203, 3639, 1758, 268, 6388, 1887, 31, 2 ]
// File: contracts/KFC.sol /** *Submitted for verification at Etherscan.io on 2022-01-22 */ /** *Submitted for verification at Etherscan.io on 2022-01-18 */ // File: contracts/KFC.sol /** *Submitted for verification at Etherscan.io on 2022-01-18 */ /** *Submitted for verification at Etherscan.io on 2022-01-18 */ // File: @openzeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // 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/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/interfaces/IERC20.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol) pragma solidity ^0.8.0; // 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 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/interfaces/IERC165.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; // File: @openzeppelin/contracts/interfaces/IERC2981.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC2981.sol) pragma solidity ^0.8.0; /** * @dev Interface for the NFT Royalty Standard */ interface IERC2981 is IERC165 { /** * @dev 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 salePrice - 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 `salePrice` */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // 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/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/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: contracts/ERC721A.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes the number of issuable tokens (collection size) is capped and fits in a uint128. * * Does not support burning tokens to address(0). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 private currentIndex = 0; uint256 internal immutable collectionSize; uint256 internal immutable maxBatchSize; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) private _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev * `maxBatchSize` refers to how much a minter can mint at a time. * `collectionSize_` refers to how many tokens are in the collection. */ constructor( string memory name_, string memory symbol_, uint256 maxBatchSize_, uint256 collectionSize_ ) { require( collectionSize_ > 0, "ERC721A: collection must have a nonzero supply" ); require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero"); _name = name_; _symbol = symbol_; maxBatchSize = maxBatchSize_; collectionSize = collectionSize_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < totalSupply(), "ERC721A: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { require(index < balanceOf(owner), "ERC721A: owner index out of bounds"); uint256 numMintedSoFar = totalSupply(); uint256 tokenIdsIdx = 0; address currOwnershipAddr = address(0); for (uint256 i = 0; i < numMintedSoFar; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } revert("ERC721A: unable to get token of owner by index"); } /** * @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 || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721A: balance query for the zero address"); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { require( owner != address(0), "ERC721A: number minted query for the zero address" ); return uint256(_addressData[owner].numberMinted); } function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { 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 override { address owner = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != _msgSender(), "ERC721A: 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 override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721A: 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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - there must be `quantity` tokens remaining unminted in the total collection. * - `to` cannot be the zero address. * - `quantity` cannot be larger than the max batch size. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); // We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering. require(!_exists(startTokenId), "ERC721A: token already minted"); require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); AddressData memory addressData = _addressData[to]; _addressData[to] = AddressData( addressData.balance + uint128(quantity), addressData.numberMinted + uint128(quantity) ); _ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp)); uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || getApproved(tokenId) == _msgSender() || isApprovedForAll(prevOwnership.addr, _msgSender())); require( isApprovedOrOwner, "ERC721A: transfer caller is not owner nor approved" ); require( prevOwnership.addr == from, "ERC721A: transfer from incorrect owner" ); require(to != address(0), "ERC721A: transfer to the zero address"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp)); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId] = TokenOwnership( prevOwnership.addr, prevOwnership.startTimestamp ); } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } uint256 public nextOwnerToExplicitlySet = 0; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). */ function _setOwnersExplicit(uint256 quantity) internal { uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet; require(quantity > 0, "quantity must be nonzero"); uint256 endIndex = oldNextOwnerToSet + quantity - 1; if (endIndex > collectionSize - 1) { endIndex = collectionSize - 1; } // We know if the last one in the group exists, all in the group exist, due to serial ordering. require(_exists(endIndex), "not enough minted yet for this cleanup"); for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) { if (_ownerships[i].addr == address(0)) { TokenOwnership memory ownership = ownershipOf(i); _ownerships[i] = TokenOwnership( ownership.addr, ownership.startTimestamp ); } } nextOwnerToExplicitlySet = endIndex + 1; } /** * @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(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: contracts/KFC.sol //SPDX-License-Identifier: MIT //Contract based on [https://docs.openzeppelin.com/contracts/3.x/erc721](https://docs.openzeppelin.com/contracts/3.x/erc721) pragma solidity ^0.8.0; contract KFCJobApplication is ERC721A, IERC2981, Ownable, ReentrancyGuard { using Counters for Counters.Counter; using Strings for uint256; Counters.Counter private tokenCounter; string private baseURI = "ipfs://QmRyCZ3ZpNbskAb5Y19NGLhRQHLFFtJcd3T7zPxL7gAD1H"; uint256 public constant MAX_MINTS_PER_TX = 10; uint256 public maxSupply = 1222; uint256 public constant PUBLIC_SALE_PRICE = 0.01 ether; uint256 public NUM_FREE_MINTS = 1000; bool public isPublicSaleActive = true; // ============ ACCESS CONTROL/SANITY MODIFIERS ============ modifier publicSaleActive() { require(isPublicSaleActive, "Public sale is not open"); _; } modifier maxMintsPerTX(uint256 numberOfTokens) { require( numberOfTokens <= MAX_MINTS_PER_TX, "Max mints per transaction exceeded" ); _; } modifier canMintNFTs(uint256 numberOfTokens) { require( totalSupply() + numberOfTokens <= maxSupply, "Not enough mints remaining to mint" ); _; } modifier freeMintsAvailable() { require( totalSupply() <= NUM_FREE_MINTS, "Not enough free mints remain" ); _; } modifier isCorrectPayment(uint256 price, uint256 numberOfTokens) { if(totalSupply()>NUM_FREE_MINTS){ require( (price * numberOfTokens) == msg.value, "Incorrect ETH value sent" ); } _; } constructor( ) ERC721A("KFCJobApplication", "KFCJOB", 100, maxSupply) { } // ============ PUBLIC FUNCTIONS FOR MINTING ============ function mint(uint256 numberOfTokens) external payable nonReentrant isCorrectPayment(PUBLIC_SALE_PRICE, numberOfTokens) publicSaleActive canMintNFTs(numberOfTokens) maxMintsPerTX(numberOfTokens) { _safeMint(msg.sender, numberOfTokens); } //A simple free mint function to avoid confusion //The normal mint function with a cost of 0 would work too function freeMint(uint256 numberOfTokens) external nonReentrant publicSaleActive canMintNFTs(numberOfTokens) maxMintsPerTX(numberOfTokens) freeMintsAvailable() { _safeMint(msg.sender, numberOfTokens); } // ============ PUBLIC READ-ONLY FUNCTIONS ============ function getBaseURI() external view returns (string memory) { return baseURI; } // ============ OWNER-ONLY ADMIN FUNCTIONS ============ function setBaseURI(string memory _baseURI) external onlyOwner { baseURI = _baseURI; } function setIsPublicSaleActive(bool _isPublicSaleActive) external onlyOwner { isPublicSaleActive = _isPublicSaleActive; } function setNumFreeMints(uint256 _numfreemints) external onlyOwner { NUM_FREE_MINTS = _numfreemints; } function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function withdrawTokens(IERC20 token) public onlyOwner { uint256 balance = token.balanceOf(address(this)); token.transfer(msg.sender, balance); } // ============ SUPPORTING FUNCTIONS ============ function nextTokenId() private returns (uint256) { tokenCounter.increment(); return tokenCounter.current(); } // ============ FUNCTION OVERRIDES ============ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721A, IERC165) returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "Nonexistent token"); return baseURI; } /** * @dev See {IERC165-royaltyInfo}. */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view override returns (address receiver, uint256 royaltyAmount) { require(_exists(tokenId), "Nonexistent token"); return (address(this), SafeMath.div(SafeMath.mul(salePrice, 5), 100)); } } // These contract definitions are used to create a reference to the OpenSea // ProxyRegistry contract by using the registry's address (see isApprovedForAll). contract OwnableDelegateProxy { } contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; }
File: contracts/KFC.solSPDX-License-Identifier: MITContract based on [https:docs.openzeppelin.com/contracts/3.x/erc721](https:docs.openzeppelin.com/contracts/3.x/erc721) ============ ACCESS CONTROL/SANITY MODIFIERS ============
contract KFCJobApplication is ERC721A, IERC2981, Ownable, ReentrancyGuard { using Counters for Counters.Counter; using Strings for uint256; Counters.Counter private tokenCounter; uint256 public constant MAX_MINTS_PER_TX = 10; uint256 public maxSupply = 1222; uint256 public constant PUBLIC_SALE_PRICE = 0.01 ether; uint256 public NUM_FREE_MINTS = 1000; bool public isPublicSaleActive = true; function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity } pragma solidity ^0.8.0; modifier publicSaleActive() { require(isPublicSaleActive, "Public sale is not open"); _; } modifier maxMintsPerTX(uint256 numberOfTokens) { require( numberOfTokens <= MAX_MINTS_PER_TX, "Max mints per transaction exceeded" ); _; } modifier canMintNFTs(uint256 numberOfTokens) { require( totalSupply() + numberOfTokens <= maxSupply, "Not enough mints remaining to mint" ); _; } modifier freeMintsAvailable() { require( totalSupply() <= NUM_FREE_MINTS, "Not enough free mints remain" ); _; } modifier isCorrectPayment(uint256 price, uint256 numberOfTokens) { if(totalSupply()>NUM_FREE_MINTS){ require( (price * numberOfTokens) == msg.value, "Incorrect ETH value sent" ); } _; } constructor( modifier isCorrectPayment(uint256 price, uint256 numberOfTokens) { if(totalSupply()>NUM_FREE_MINTS){ require( (price * numberOfTokens) == msg.value, "Incorrect ETH value sent" ); } _; } constructor( ) ERC721A("KFCJobApplication", "KFCJOB", 100, maxSupply) { } function mint(uint256 numberOfTokens) external payable nonReentrant isCorrectPayment(PUBLIC_SALE_PRICE, numberOfTokens) publicSaleActive canMintNFTs(numberOfTokens) maxMintsPerTX(numberOfTokens) { _safeMint(msg.sender, numberOfTokens); } function freeMint(uint256 numberOfTokens) external nonReentrant publicSaleActive canMintNFTs(numberOfTokens) maxMintsPerTX(numberOfTokens) freeMintsAvailable() { _safeMint(msg.sender, numberOfTokens); } function getBaseURI() external view returns (string memory) { return baseURI; } function setBaseURI(string memory _baseURI) external onlyOwner { baseURI = _baseURI; } function setIsPublicSaleActive(bool _isPublicSaleActive) external onlyOwner { isPublicSaleActive = _isPublicSaleActive; } function setNumFreeMints(uint256 _numfreemints) external onlyOwner { NUM_FREE_MINTS = _numfreemints; } function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } function withdrawTokens(IERC20 token) public onlyOwner { uint256 balance = token.balanceOf(address(this)); token.transfer(msg.sender, balance); } function nextTokenId() private returns (uint256) { tokenCounter.increment(); return tokenCounter.current(); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721A, IERC165) returns (bool) { return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "Nonexistent token"); return baseURI; } function royaltyInfo(uint256 tokenId, uint256 salePrice) external view override returns (address receiver, uint256 royaltyAmount) { require(_exists(tokenId), "Nonexistent token"); return (address(this), SafeMath.div(SafeMath.mul(salePrice, 5), 100)); } }
14,447,118
[ 1, 812, 30, 20092, 19, 47, 4488, 18, 18281, 3118, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 8924, 2511, 603, 306, 4528, 30, 8532, 18, 3190, 94, 881, 84, 292, 267, 18, 832, 19, 16351, 87, 19, 23, 18, 92, 19, 12610, 27, 5340, 29955, 4528, 30, 8532, 18, 3190, 94, 881, 84, 292, 267, 18, 832, 19, 16351, 87, 19, 23, 18, 92, 19, 12610, 27, 5340, 13, 422, 1432, 631, 13255, 8020, 13429, 19, 22721, 4107, 8663, 10591, 55, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 1475, 4488, 2278, 3208, 353, 4232, 39, 27, 5340, 37, 16, 467, 654, 39, 5540, 11861, 16, 14223, 6914, 16, 868, 8230, 12514, 16709, 288, 203, 565, 1450, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 565, 9354, 87, 18, 4789, 3238, 1147, 4789, 31, 203, 203, 203, 565, 2254, 5034, 1071, 5381, 4552, 67, 49, 3217, 55, 67, 3194, 67, 16556, 273, 1728, 31, 203, 565, 2254, 5034, 1071, 943, 3088, 1283, 273, 2593, 3787, 31, 203, 203, 565, 2254, 5034, 1071, 5381, 17187, 67, 5233, 900, 67, 7698, 1441, 273, 374, 18, 1611, 225, 2437, 31, 203, 565, 2254, 5034, 1071, 9443, 67, 28104, 67, 49, 3217, 55, 273, 4336, 31, 203, 565, 1426, 1071, 19620, 30746, 3896, 273, 638, 31, 203, 203, 203, 203, 203, 203, 225, 445, 389, 5771, 1345, 1429, 18881, 12, 203, 565, 1758, 628, 16, 203, 565, 1758, 358, 16, 203, 565, 2254, 5034, 787, 1345, 548, 16, 203, 565, 2254, 5034, 10457, 203, 203, 225, 445, 389, 5205, 1345, 1429, 18881, 12, 203, 565, 1758, 628, 16, 203, 565, 1758, 358, 16, 203, 565, 2254, 5034, 787, 1345, 548, 16, 203, 565, 2254, 5034, 10457, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 565, 9606, 1071, 30746, 3896, 1435, 288, 203, 3639, 2583, 12, 291, 4782, 30746, 3896, 16, 315, 4782, 272, 5349, 353, 486, 1696, 8863, 2 ]
pragma solidity ^0.5.8; library FlightSuretyLib { // Flight info struct Flight { uint nonce; bytes32 key; string code; string origin; uint256 departureTimestamp; string destination; uint256 arrivalTimestamp; uint8 statusCode; } // Airline info which includes mapping for associated flights struct Airline { uint nonce; // Airline nonce or unique # string name; bool registered; bool funded; uint votes; uint flightNonce; // to keep track of current # of registered flights for the Airline mapping(uint => bytes32) flightKeys; // mapping for flight index to flight key mapping(bytes32 => Flight) flights; } // Struct for managing Flight Insurance per Passenger // struct FlightInsurance { uint purchased; uint payout; bool isInsured; bool isCredited; bool isWithdrawn; } struct FlightSurety { // Mapping for airline account and all relevant info, including flights // Airline => Airline Struct // mapping(address => Airline) airlines; // Mapping for flight insurees // Airline => (Flight => (Passenger => FlightInsurance)) mapping(address => mapping(bytes32 => mapping(address => FlightSuretyLib.FlightInsurance))) flightInsurees; // Mapping for flight passengers with insurance mapping(address => mapping(bytes32 => address[])) insuredPassengers; } // Flight status codes function STATUS_CODE_UNKNOWN() external pure returns(uint8 code) { return 0; } function STATUS_CODE_ON_TIME() external pure returns(uint8 code) { return 10; } function STATUS_CODE_LATE_AIRLINE() external pure returns(uint8 code) { return 20; } function STATUS_CODE_LATE_WEATHER() external pure returns(uint8 code) { return 30; } function STATUS_CODE_LATE_TECHNICAL() external pure returns(uint8 code) { return 40; } function STATUS_CODE_LATE_OTHER() external pure returns(uint8 code) { return 50; } }
Airline info which includes mapping for associated flights
struct Airline { string name; bool registered; bool funded; uint votes; mapping(bytes32 => Flight) flights; }
1,814,293
[ 1, 29752, 1369, 1123, 1492, 6104, 2874, 364, 3627, 1183, 10730, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1958, 432, 481, 1369, 288, 203, 3639, 533, 508, 31, 203, 3639, 1426, 4104, 31, 203, 3639, 1426, 9831, 785, 31, 203, 3639, 2254, 19588, 31, 203, 3639, 2874, 12, 3890, 1578, 516, 3857, 750, 13, 1183, 10730, 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 ]
./partial_match/1/0x6dbE10BFC331CB8b7b1c17ce252a6f178D74E912/sources/contracts/arbitrage/BancorArbitrage.sol
* @dev handles the trade logic per route/ allow the network to withdraw the source tokens build the conversion path perform the trade allow the network to withdraw the source tokens perform the trade allow the router to withdraw the source tokens build the path perform the trade build the params Carbon accepts 2^128 - 1 max for minTargetAmount transfer any remaining source tokens to a dust wallet
function _trade( uint256 exchangeId, Token sourceToken, Token targetToken, uint256 sourceAmount, uint256 minTargetAmount, uint256 deadline, address customAddress, uint256 customInt, bytes memory customData ) private { if (exchangeId == EXCHANGE_ID_BANCOR_V2) { _setExchangeAllowance(sourceToken, address(_bancorNetworkV2), sourceAmount); address[] memory path = new address[](3); path[0] = address(sourceToken); path[2] = address(targetToken); uint256 val = sourceToken.isNative() ? sourceAmount : 0; path, sourceAmount, minTargetAmount, address(0x0), address(0x0), 0 ); return; } if (exchangeId == EXCHANGE_ID_BANCOR_V3) { _setExchangeAllowance(sourceToken, address(_bancorNetworkV3), sourceAmount); uint256 val = sourceToken.isNative() ? sourceAmount : 0; sourceToken, targetToken, sourceAmount, minTargetAmount, deadline, address(0x0) ); return; } if (exchangeId == EXCHANGE_ID_UNISWAP_V2 || exchangeId == EXCHANGE_ID_SUSHISWAP) { IUniswapV2Router02 router = exchangeId == EXCHANGE_ID_UNISWAP_V2 ? _uniswapV2Router : _sushiSwapRouter; _setExchangeAllowance(sourceToken, address(router), sourceAmount); address[] memory path = new address[](2); if (sourceToken.isNative()) { path[0] = address(_weth); path[1] = address(targetToken); path[0] = address(sourceToken); path[1] = address(_weth); router.swapExactTokensForETH(sourceAmount, minTargetAmount, path, address(this), deadline); path[0] = address(sourceToken); path[1] = address(targetToken); router.swapExactTokensForTokens(sourceAmount, minTargetAmount, path, address(this), deadline); } return; } if (exchangeId == EXCHANGE_ID_UNISWAP_V3) { address tokenIn = sourceToken.isNative() ? address(_weth) : address(sourceToken); address tokenOut = targetToken.isNative() ? address(_weth) : address(targetToken); if (tokenIn == address(_weth)) { } ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams({ tokenIn: tokenIn, tokenOut: tokenOut, recipient: address(this), deadline: deadline, amountIn: sourceAmount, amountOutMinimum: minTargetAmount, sqrtPriceLimitX96: uint160(0) }); if (tokenOut == address(_weth)) { IWETH(address(_weth)).withdraw(_weth.balanceOf(address(this))); } return; } if (exchangeId == EXCHANGE_ID_CARBON) { if (minTargetAmount > type(uint128).max) { revert MinTargetAmountTooHigh(); } uint256 val = sourceToken.isNative() ? sourceAmount : 0; sourceToken, targetToken, tradeActions, deadline, uint128(minTargetAmount) ); uint256 remainingSourceTokens = sourceToken.balanceOf(address(this)); if (remainingSourceTokens > 0) { sourceToken.safeTransfer(_dustWallet, remainingSourceTokens); } return; } revert InvalidExchangeId(); }
15,916,220
[ 1, 24111, 326, 18542, 4058, 1534, 1946, 19, 1699, 326, 2483, 358, 598, 9446, 326, 1084, 2430, 1361, 326, 4105, 589, 3073, 326, 18542, 1699, 326, 2483, 358, 598, 9446, 326, 1084, 2430, 3073, 326, 18542, 1699, 326, 4633, 358, 598, 9446, 326, 1084, 2430, 1361, 326, 589, 3073, 326, 18542, 1361, 326, 859, 13353, 8104, 576, 66, 10392, 300, 404, 943, 364, 1131, 2326, 6275, 7412, 1281, 4463, 1084, 2430, 358, 279, 302, 641, 9230, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 20077, 12, 203, 3639, 2254, 5034, 7829, 548, 16, 203, 3639, 3155, 1084, 1345, 16, 203, 3639, 3155, 1018, 1345, 16, 203, 3639, 2254, 5034, 1084, 6275, 16, 203, 3639, 2254, 5034, 1131, 2326, 6275, 16, 203, 3639, 2254, 5034, 14096, 16, 203, 3639, 1758, 1679, 1887, 16, 203, 3639, 2254, 5034, 1679, 1702, 16, 203, 3639, 1731, 3778, 1679, 751, 203, 565, 262, 3238, 288, 203, 3639, 309, 261, 16641, 548, 422, 5675, 14473, 67, 734, 67, 38, 1258, 9428, 67, 58, 22, 13, 288, 203, 5411, 389, 542, 11688, 7009, 1359, 12, 3168, 1345, 16, 1758, 24899, 21515, 3850, 3906, 58, 22, 3631, 1084, 6275, 1769, 203, 203, 5411, 1758, 8526, 3778, 589, 273, 394, 1758, 8526, 12, 23, 1769, 203, 5411, 589, 63, 20, 65, 273, 1758, 12, 3168, 1345, 1769, 203, 5411, 589, 63, 22, 65, 273, 1758, 12, 3299, 1345, 1769, 203, 203, 5411, 2254, 5034, 1244, 273, 1084, 1345, 18, 291, 9220, 1435, 692, 1084, 6275, 294, 374, 31, 203, 203, 7734, 589, 16, 203, 7734, 1084, 6275, 16, 203, 7734, 1131, 2326, 6275, 16, 203, 7734, 1758, 12, 20, 92, 20, 3631, 203, 7734, 1758, 12, 20, 92, 20, 3631, 203, 7734, 374, 203, 5411, 11272, 203, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 16641, 548, 422, 5675, 14473, 67, 734, 67, 38, 1258, 9428, 67, 58, 23, 13, 288, 203, 5411, 389, 542, 11688, 7009, 1359, 12, 3168, 1345, 16, 1758, 24899, 21515, 3850, 3906, 58, 23, 3631, 2 ]
./full_match/1/0x33A8d92B2BE84755441C2b6e39715c4b8938242c/sources/contracts/interfaces/ITrading.sol
* @title ITrading @notice Common events and refresher function for all Trading contracts/
interface ITrading is IComponent, IRewardableComponent { event MaxTradeSlippageSet(uint192 oldVal, uint192 newVal); event MinTradeVolumeSet(uint192 oldVal, uint192 newVal); event TradeStarted( ITrade indexed trade, IERC20 indexed sell, IERC20 indexed buy, uint256 sellAmount, uint256 minBuyAmount ); event TradeSettled( ITrade indexed trade, IERC20 indexed sell, IERC20 indexed buy, uint256 sellAmount, uint256 buyAmount ); function settleTrade(IERC20 sell) external returns (ITrade); function maxTradeSlippage() external view returns (uint192); function minTradeVolume() external view returns (uint192); function trades(IERC20 sell) external view returns (ITrade); function tradesOpen() external view returns (uint48); function tradesNonce() external view returns (uint256); pragma solidity 0.8.19; }
3,864,709
[ 1, 1285, 6012, 310, 225, 5658, 2641, 471, 1278, 455, 1614, 445, 364, 777, 2197, 7459, 20092, 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, 5831, 467, 1609, 7459, 353, 467, 1841, 16, 15908, 359, 1060, 429, 1841, 288, 203, 565, 871, 4238, 22583, 55, 3169, 2433, 694, 12, 11890, 15561, 1592, 3053, 16, 2254, 15561, 20957, 1769, 203, 565, 871, 5444, 22583, 4545, 694, 12, 11890, 15561, 1592, 3053, 16, 2254, 15561, 20957, 1769, 203, 203, 565, 871, 2197, 323, 9217, 12, 203, 3639, 467, 22583, 8808, 18542, 16, 203, 3639, 467, 654, 39, 3462, 8808, 357, 80, 16, 203, 3639, 467, 654, 39, 3462, 8808, 30143, 16, 203, 3639, 2254, 5034, 357, 80, 6275, 16, 203, 3639, 2254, 5034, 1131, 38, 9835, 6275, 203, 565, 11272, 203, 203, 565, 871, 2197, 323, 694, 88, 1259, 12, 203, 3639, 467, 22583, 8808, 18542, 16, 203, 3639, 467, 654, 39, 3462, 8808, 357, 80, 16, 203, 3639, 467, 654, 39, 3462, 8808, 30143, 16, 203, 3639, 2254, 5034, 357, 80, 6275, 16, 203, 3639, 2254, 5034, 30143, 6275, 203, 565, 11272, 203, 203, 565, 445, 444, 5929, 22583, 12, 45, 654, 39, 3462, 357, 80, 13, 3903, 1135, 261, 1285, 354, 323, 1769, 203, 203, 565, 445, 943, 22583, 55, 3169, 2433, 1435, 3903, 1476, 1135, 261, 11890, 15561, 1769, 203, 203, 565, 445, 1131, 22583, 4545, 1435, 3903, 1476, 1135, 261, 11890, 15561, 1769, 203, 203, 565, 445, 1284, 5489, 12, 45, 654, 39, 3462, 357, 80, 13, 3903, 1476, 1135, 261, 1285, 354, 323, 1769, 203, 203, 565, 445, 1284, 5489, 3678, 1435, 3903, 1476, 1135, 261, 11890, 8875, 1769, 203, 203, 565, 445, 1284, 5489, 13611, 2 ]
./partial_match/5/0xe2F9CFc794f7D3b2cA62654D098551474B6aB172/sources/Proxy.sol
solium-disable-next-line security/no-inline-assembly
function () external payable { uint grant = 0.005 ether; require(!enoughEther(), "Proxy needs more ETHER!"); require(msg.sender.send(grant), "Sending grant failed"); recipientList.length++; recipientList[recipientList.length-1] = msg.sender; assembly { let masterCopy := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff) calldatacopy(0, 0, calldatasize()) let success := delegatecall(gas, masterCopy, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) return(0, returndatasize()) } }
16,845,670
[ 1, 18281, 5077, 17, 8394, 17, 4285, 17, 1369, 4373, 19, 2135, 17, 10047, 17, 28050, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1832, 3903, 8843, 429, 203, 565, 288, 203, 3639, 2254, 7936, 273, 374, 18, 28564, 225, 2437, 31, 203, 3639, 2583, 12, 5, 275, 4966, 41, 1136, 9334, 315, 3886, 4260, 1898, 512, 19905, 4442, 1769, 203, 3639, 2583, 12, 3576, 18, 15330, 18, 4661, 12, 16243, 3631, 315, 16322, 7936, 2535, 8863, 203, 3639, 8027, 682, 18, 2469, 9904, 31, 203, 3639, 8027, 682, 63, 20367, 682, 18, 2469, 17, 21, 65, 273, 1234, 18, 15330, 31, 203, 3639, 19931, 288, 203, 5411, 2231, 4171, 2951, 519, 471, 12, 87, 945, 12, 20, 3631, 374, 5297, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 9460, 18217, 13, 203, 5411, 745, 892, 3530, 12, 20, 16, 374, 16, 745, 13178, 554, 10756, 203, 5411, 2231, 2216, 519, 7152, 1991, 12, 31604, 16, 4171, 2951, 16, 374, 16, 745, 13178, 554, 9334, 374, 16, 374, 13, 203, 5411, 327, 892, 3530, 12, 20, 16, 374, 16, 327, 13178, 554, 10756, 203, 5411, 327, 12, 20, 16, 327, 13178, 554, 10756, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.15; /** * @title Eliptic curve signature operations * * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d */ library ECRecovery { /** * @dev Recover signer address from a message by using his signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param sig bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes sig) public constant returns (address) { bytes32 r; bytes32 s; uint8 v; //Check the signature length if (sig.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { return ecrecover(hash, v, r, s); } } } //Papyrus State Channel Library //moved to separate library to save gas library ChannelLibrary { struct Data { uint close_timeout; uint settle_timeout; uint audit_timeout; uint opened; uint close_requested; uint closed; uint settled; uint audited; ChannelManagerContract manager; address sender; address receiver; address client; uint balance; address auditor; //state update for close uint nonce; uint completed_transfers; } struct StateUpdate { uint nonce; uint completed_transfers; } modifier notSettledButClosed(Data storage self) { require(self.settled <= 0 && self.closed > 0); _; } modifier notAuditedButClosed(Data storage self) { require(self.audited <= 0 && self.closed > 0); _; } modifier stillTimeout(Data storage self) { require(self.closed + self.settle_timeout >= block.number); _; } modifier timeoutOver(Data storage self) { require(self.closed + self.settle_timeout <= block.number); _; } modifier channelSettled(Data storage self) { require(self.settled != 0); _; } modifier senderOnly(Data storage self) { require(self.sender == msg.sender); _; } modifier receiverOnly(Data storage self) { require(self.receiver == msg.sender); _; } /// @notice Sender deposits amount to channel. /// must deposit before the channel is opened. /// @param amount The amount to be deposited to the address /// @return Success if the transfer was successful /// @return The new balance of the invoker function deposit(Data storage self, uint256 amount) senderOnly(self) returns (bool success, uint256 balance) { require(self.opened > 0); require(self.closed == 0); StandardToken token = self.manager.token(); require (token.balanceOf(msg.sender) >= amount); success = token.transferFrom(msg.sender, this, amount); if (success == true) { self.balance += amount; return (true, self.balance); } return (false, 0); } function request_close( Data storage self ) { require(msg.sender == self.sender || msg.sender == self.receiver); require(self.close_requested == 0); self.close_requested = block.number; } function close( Data storage self, address channel_address, uint nonce, uint completed_transfers, bytes signature ) { if (self.close_timeout > 0) { require(self.close_requested > 0); require(block.number - self.close_requested >= self.close_timeout); } require(nonce > self.nonce); require(completed_transfers >= self.completed_transfers); require(completed_transfers <= self.balance); if (msg.sender != self.sender) { //checking signature bytes32 signed_hash = hashState( channel_address, nonce, completed_transfers ); address sign_address = ECRecovery.recover(signed_hash, signature); require(sign_address == self.sender); } if (self.closed == 0) { self.closed = block.number; } self.nonce = nonce; self.completed_transfers = completed_transfers; } function hashState ( address channel_address, uint nonce, uint completed_transfers ) returns (bytes32) { return sha3 ( channel_address, nonce, completed_transfers ); } /// @notice Settles the balance between the two parties /// @dev Settles the balances of the two parties fo the channel /// @return The participants with netted balances function settle(Data storage self) notSettledButClosed(self) timeoutOver(self) { StandardToken token = self.manager.token(); if (self.completed_transfers > 0) { require(token.transfer(self.receiver, self.completed_transfers)); } if (self.completed_transfers < self.balance) { require(token.transfer(self.sender, self.balance - self.completed_transfers)); } self.settled = block.number; } function audit(Data storage self, address auditor) notAuditedButClosed(self) { require(self.auditor == auditor); require(block.number <= self.closed + self.audit_timeout); self.audited = block.number; } function validateTransfer( Data storage self, address transfer_id, address channel_address, uint sum, bytes lock_data, bytes signature ) returns (uint256) { bytes32 signed_hash = hashTransfer( transfer_id, channel_address, lock_data, sum ); address sign_address = ECRecovery.recover(signed_hash, signature); require(sign_address == self.client); } function hashTransfer( address transfer_id, address channel_address, bytes lock_data, uint sum ) returns (bytes32) { if (lock_data.length > 0) { return sha3 ( transfer_id, channel_address, sum, lock_data ); } else { return sha3 ( transfer_id, channel_address, sum ); } } } /// @title ERC20 interface /// @dev Full ERC20 interface described at https://github.com/ethereum/EIPs/issues/20. contract ERC20 { // EVENTS event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); // PUBLIC FUNCTIONS function transfer(address _to, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function balanceOf(address _owner) public constant returns (uint256); function allowance(address _owner, address _spender) public constant returns (uint256); // FIELDS uint256 public totalSupply; } /// @title SafeMath /// @dev Math operations with safety checks that throw on error. library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /// @title Standard ERC20 token /// @dev Implementation of the basic standard token. contract StandardToken is ERC20 { using SafeMath for uint256; // PUBLIC FUNCTIONS /// @dev Transfers tokens to a specified address. /// @param _to The address which you want to transfer to. /// @param _value The amount of tokens to be transferred. /// @return A boolean that indicates if the operation was successful. function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /// @dev Transfers tokens from one address to another. /// @param _from The address which you want to send tokens from. /// @param _to The address which you want to transfer to. /// @param _value The amount of tokens to be transferred. /// @return A boolean that indicates if the operation was successful. function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowances[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /// @dev Approves the specified 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 tokens. /// @param _value The amount of tokens to be spent. /// @return A boolean that indicates if the operation was successful. function approve(address _spender, uint256 _value) public returns (bool) { allowances[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /// @dev Gets the balance of the specified address. /// @param _owner The address to query the balance of. /// @return An uint256 representing the amount owned by the specified address. function balanceOf(address _owner) public constant returns (uint256) { return balances[_owner]; } /// @dev Function to check the amount of tokens that an owner allowances to a spender. /// @param _owner The address which owns tokens. /// @param _spender The address which will spend tokens. /// @return A uint256 specifying the amount of tokens still available for the spender. function allowance(address _owner, address _spender) public constant returns (uint256) { return allowances[_owner][_spender]; } // FIELDS mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowances; } contract ChannelApi { function applyRuntimeUpdate(address from, address to, uint impressionsCount, uint fraudCount); function applyAuditorsCheckUpdate(address from, address to, uint fraudCountDelta); } contract ChannelContract { using ChannelLibrary for ChannelLibrary.Data; ChannelLibrary.Data data; event ChannelNewBalance(address token_address, address participant, uint balance, uint block_number); event ChannelCloseRequested(address closing_address, uint block_number); event ChannelClosed(address closing_address, uint block_number); event TransferUpdated(address node_address, uint block_number); event ChannelSettled(uint block_number); event ChannelAudited(uint block_number); event ChannelSecretRevealed(bytes32 secret, address receiver_address); modifier onlyManager() { require(msg.sender == address(data.manager)); _; } function ChannelContract( address manager_address, address sender, address client, address receiver, uint close_timeout, uint settle_timeout, uint audit_timeout, address auditor ) { //allow creation only from manager contract require(msg.sender == manager_address); require (sender != receiver); require (client != receiver); require (audit_timeout >= 0); require (settle_timeout > 0); require (close_timeout >= 0); data.sender = sender; data.client = client; data.receiver = receiver; data.auditor = auditor; data.manager = ChannelManagerContract(manager_address); data.close_timeout = close_timeout; data.settle_timeout = settle_timeout; data.audit_timeout = audit_timeout; data.opened = block.number; } /// @notice Caller makes a deposit into their channel balance. /// @param amount The amount caller wants to deposit. /// @return True if deposit is successful. function deposit(uint256 amount) returns (bool) { bool success; uint256 balance; (success, balance) = data.deposit(amount); if (success == true) { ChannelNewBalance(data.manager.token(), msg.sender, balance, 0); } return success; } /// @notice Get the address and balance of both partners in a channel. /// @return The address and balance pairs. function addressAndBalance() constant returns ( address sender, address receiver, uint balance) { sender = data.sender; receiver = data.receiver; balance = data.balance; } /// @notice Request to close the channel. function request_close () { data.request_close(); ChannelCloseRequested(msg.sender, data.closed); } /// @notice Close the channel. function close ( uint nonce, uint256 completed_transfers, bytes signature ) { data.close(address(this), nonce, completed_transfers, signature); ChannelClosed(msg.sender, data.closed); } /// @notice Settle the transfers and balances of the channel and pay out to /// each participant. Can only be called after the channel is closed /// and only after the number of blocks in the settlement timeout /// have passed. function settle() { data.settle(); ChannelSettled(data.settled); } /// @notice Settle the transfers and balances of the channel and pay out to /// each participant. Can only be called after the channel is closed /// and only after the number of blocks in the settlement timeout /// have passed. function audit(address auditor) onlyManager { data.audit(auditor); ChannelAudited(data.audited); } function destroy() onlyManager { require(data.settled > 0); require(data.audited > 0 || block.number > data.closed + data.audit_timeout); selfdestruct(0); } function sender() constant returns (address) { return data.sender; } function receiver() constant returns (address) { return data.receiver; } function client() constant returns (address) { return data.client; } function auditor() constant returns (address) { return data.auditor; } function closeTimeout() constant returns (uint) { return data.close_timeout; } function settleTimeout() constant returns (uint) { return data.settle_timeout; } function auditTimeout() constant returns (uint) { return data.audit_timeout; } /// @return Returns the address of the manager. function manager() constant returns (address) { return data.manager; } function balance() constant returns (uint) { return data.balance; } function nonce() constant returns (uint) { return data.nonce; } function completedTransfers() constant returns (uint) { return data.completed_transfers; } /// @notice Returns the block number for when the channel was opened. /// @return The block number for when the channel was opened. function opened() constant returns (uint) { return data.opened; } function closeRequested() constant returns (uint) { return data.close_requested; } function closed() constant returns (uint) { return data.closed; } function settled() constant returns (uint) { return data.settled; } function audited() constant returns (uint) { return data.audited; } function () { revert(); } } contract ChannelManagerContract { event ChannelNew( address channel_address, address indexed sender, address client, address indexed receiver, uint close_timeout, uint settle_timeout, uint audit_timeout ); event ChannelDeleted( address channel_address, address indexed sender, address indexed receiver ); StandardToken public token; ChannelApi public channel_api; function ChannelManagerContract(address token_address, address channel_api_address) { require(token_address != 0); require(channel_api_address != 0); token = StandardToken(token_address); channel_api = ChannelApi(channel_api_address); } /// @notice Create a new channel from msg.sender to receiver /// @param receiver The address of the receiver /// @param settle_timeout The settle timeout in blocks /// @return The address of the newly created ChannelContract. function newChannel( address client, address receiver, uint close_timeout, uint settle_timeout, uint audit_timeout, address auditor ) returns (address) { address new_channel_address = new ChannelContract( this, msg.sender, client, receiver, close_timeout, settle_timeout, audit_timeout, auditor ); ChannelNew( new_channel_address, msg.sender, client, receiver, close_timeout, settle_timeout, audit_timeout ); return new_channel_address; } function auditReport(address contract_address, uint total, uint fraud) { ChannelContract ch = ChannelContract(contract_address); require(ch.manager() == address(this)); address auditor = msg.sender; ch.audit(auditor); channel_api.applyRuntimeUpdate(ch.sender(), ch.receiver(), total, fraud); } function destroyChannel(address channel_address) { ChannelContract ch = ChannelContract(channel_address); require(ch.manager() == address(this)); ChannelDeleted(channel_address,ch.sender(),ch.receiver()); ch.destroy(); } }
@notice Caller makes a deposit into their channel balance. @param amount The amount caller wants to deposit. @return True if deposit is successful.
function deposit(uint256 amount) returns (bool) { bool success; uint256 balance; (success, balance) = data.deposit(amount); if (success == true) { ChannelNewBalance(data.manager.token(), msg.sender, balance, 0); } return success; }
1,063,570
[ 1, 11095, 7297, 279, 443, 1724, 1368, 3675, 1904, 11013, 18, 225, 3844, 1021, 3844, 4894, 14805, 358, 443, 1724, 18, 327, 1053, 309, 443, 1724, 353, 6873, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 12, 11890, 5034, 3844, 13, 1135, 261, 6430, 13, 288, 203, 3639, 1426, 2216, 31, 203, 3639, 2254, 5034, 11013, 31, 203, 203, 3639, 261, 4768, 16, 11013, 13, 273, 501, 18, 323, 1724, 12, 8949, 1769, 203, 203, 3639, 309, 261, 4768, 422, 638, 13, 288, 203, 5411, 5307, 1908, 13937, 12, 892, 18, 4181, 18, 2316, 9334, 1234, 18, 15330, 16, 11013, 16, 374, 1769, 203, 3639, 289, 203, 203, 3639, 327, 2216, 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 ]
./full_match/43114/0x3D7E1C13D4e1327c958534b2e50Fb2e8C7C0C114/sources/contracts/SelfCompoudningYieldUpgradeable.sol
Add an account to the deposit whitelist. Unlike VaultUpgradeable, SelfCompoundingYieldUpgradeable doesn't allow accunts to deposit by default. @param _newDepositor The account to be added to the white list
function addWhitelistDeposit( address _newDepositor ) public adminPriviledged { whitelistDeposit.add(_newDepositor); }
4,632,821
[ 1, 986, 392, 2236, 358, 326, 443, 1724, 10734, 18, 25448, 17329, 10784, 429, 16, 18954, 16835, 310, 16348, 10784, 429, 3302, 1404, 1699, 4078, 318, 3428, 358, 443, 1724, 635, 805, 18, 225, 389, 2704, 758, 1724, 280, 1021, 2236, 358, 506, 3096, 358, 326, 9578, 666, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 18927, 758, 1724, 12, 203, 3639, 1758, 389, 2704, 758, 1724, 280, 203, 565, 262, 1071, 3981, 15475, 1411, 2423, 288, 203, 3639, 10734, 758, 1724, 18, 1289, 24899, 2704, 758, 1724, 280, 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 ]
./partial_match/1/0x82895fE2945A8B19c5E511E5AA90Da3Aa27331eA/sources/CCPCyborgs.sol
price for swapping roll
uint bRollCost;
2,700,657
[ 1, 8694, 364, 7720, 1382, 5824, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 324, 24194, 8018, 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 ]
pragma solidity ^0.4.18; /** * @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; } } /** * @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 Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale is Ownable { using SafeMath for uint256; // The token being sold MintableToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public preIcoStartTime; uint256 public icoStartTime; uint256 public preIcoEndTime; uint256 public icoEndTime; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint256 public preIcoRate; uint256 public icoRate; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale(uint256 _preIcoStartTime, uint256 _preIcoEndTime, uint256 _preIcoRate, uint256 _icoStartTime, uint256 _icoEndTime, uint256 _icoRate, address _wallet) public { require(_preIcoStartTime >= now); require(_preIcoEndTime >= _preIcoStartTime); require(_icoStartTime >= _preIcoEndTime); require(_icoEndTime >= _icoStartTime); require(_preIcoRate > 0); require(_icoRate > 0); require(_wallet != address(0)); token = createTokenContract(); preIcoStartTime = _preIcoStartTime; icoStartTime = _icoStartTime; preIcoEndTime = _preIcoEndTime; icoEndTime = _icoEndTime; preIcoRate = _preIcoRate; icoRate = _icoRate; wallet = _wallet; } // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); //send tokens to beneficiary. token.mint(beneficiary, tokens); //send same amount of tokens to owner. token.mint(wallet, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // @return true if pre-ico crowdsale event has ended function preIcoHasEnded() public view returns (bool) { return now > preIcoEndTime; } // @return true if ico crowdsale event has ended function icoHasEnded() public view returns (bool) { return now > icoEndTime; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (MintableToken) { return new MintableToken(); } // Override this method to have a way to add business logic to your crowdsale when buying function getTokenAmount(uint256 weiAmount) internal view returns(uint256) { if(!preIcoHasEnded()){ return weiAmount.mul(preIcoRate); }else{ return weiAmount.mul(icoRate); } } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = now >= preIcoStartTime && now <= preIcoEndTime || now >= icoStartTime && now <= icoEndTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // allows transfer of token to new owner function transferTokenOwnership(address _newOwner) public { require(msg.sender == owner); // Only the owner of the crowdsale contract should be able to call this function. //Now lets reference the token that we created.... token.transferOwnership(_newOwner); } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // 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; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @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 { 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); } } /** * @title SocialMediaIncomeCrowdsaleToken * @dev ERC20 Token that can be minted. * It is meant to be used in a crowdsale contract. */ contract SocialMediaIncomeCrowdsaleToken is MintableToken, BurnableToken { string public constant name = "Social Media Income"; // solium-disable-line uppercase string public constant symbol = "SMI"; // solium-disable-line uppercase uint8 public constant decimals = 18; // solium-disable-line uppercase } /** * @title SocialMediaIncomeCrowdsale * @dev This is a fully fledged crowdsale. * The way to add new features to a base crowdsale is by multiple inheritance. * * After adding multiple features it's good practice to run integration tests * to ensure that subcontracts works together as intended. */ contract SocialMediaIncomeCrowdsale is Crowdsale { function SocialMediaIncomeCrowdsale(uint256 _preIcoStartTime, uint256 _preIcoEndTime, uint256 _preIcoRate, uint256 _icoStartTime, uint256 _icoEndTime, uint256 _icoRate, address _wallet) public Crowdsale(_preIcoStartTime, _preIcoEndTime, _preIcoRate, _icoStartTime, _icoEndTime, _icoRate, _wallet) { } function createTokenContract() internal returns (MintableToken) { return new SocialMediaIncomeCrowdsaleToken(); } }
* @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: @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; }
164,807
[ 1, 12053, 537, 326, 2275, 1758, 358, 17571, 326, 1269, 3844, 434, 2430, 603, 12433, 6186, 434, 1234, 18, 15330, 18, 605, 359, 834, 716, 12770, 392, 1699, 1359, 598, 333, 707, 5186, 899, 326, 18404, 716, 18626, 2026, 999, 3937, 326, 1592, 471, 326, 394, 1699, 1359, 635, 640, 22618, 340, 2492, 9543, 18, 6942, 3323, 6959, 358, 20310, 360, 340, 333, 17996, 2269, 353, 358, 1122, 5459, 326, 17571, 264, 1807, 1699, 1359, 358, 374, 471, 444, 326, 6049, 460, 23838, 30, 225, 389, 87, 1302, 264, 1021, 1758, 1492, 903, 17571, 326, 284, 19156, 18, 225, 389, 1132, 1021, 3844, 434, 2430, 358, 506, 26515, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 1377, 445, 6617, 537, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 273, 389, 1132, 31, 203, 3639, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 389, 87, 1302, 264, 16, 389, 1132, 1769, 203, 3639, 327, 638, 31, 203, 1377, 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 ]
// File: contracts/vaults/IStrategy.sol pragma solidity 0.5.17; interface istrategy59 { //inject NONSTANDARD NAMING function GETNAME35() external pure returns (string memory); //inject NONSTANDARD NAMING function WANT31() external view returns (address); //inject NONSTANDARD NAMING function WITHDRAW24(address) external; //inject NONSTANDARD NAMING function WITHDRAW24(uint256) external; //inject NONSTANDARD NAMING function WITHDRAWALL24() external returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF3() external view returns (uint256); //inject NONSTANDARD NAMING } // File: contracts/IERC20.sol //SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.5.17; interface ierc2080 { //inject NONSTANDARD NAMING function TOTALSUPPLY74() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF3(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER92(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE58(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE17(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM23(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER57(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL94(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: contracts/ITreasury.sol pragma solidity 0.5.17; interface itreasury2 { //inject NONSTANDARD NAMING function DEFAULTTOKEN28() external view returns (ierc2080); //inject NONSTANDARD NAMING function DEPOSIT94(ierc2080 token, uint256 amount) external; //inject NONSTANDARD NAMING function WITHDRAW24(uint256 amount, address withdrawAddress) external; //inject NONSTANDARD NAMING } // File: contracts/vaults/IVault.sol pragma solidity 0.5.17; interface ivault53 { //inject NONSTANDARD NAMING function WANT31() external view returns (ierc2080); //inject NONSTANDARD NAMING function TRANSFERFUNDSTOSTRATEGY94(address strategy, uint256 amount) external; //inject NONSTANDARD NAMING function AVAILABLEFUNDS75() external view returns (uint256); //inject NONSTANDARD NAMING } // File: contracts/vaults/IVaultRewards.sol pragma solidity 0.5.17; interface ivaultrewards63 { //inject NONSTANDARD NAMING function WANT31() external view returns (ierc2080); //inject NONSTANDARD NAMING function NOTIFYREWARDAMOUNT2(uint256 reward) external; //inject NONSTANDARD NAMING } // File: contracts/vaults/IController.sol pragma solidity 0.5.17; interface icontroller20 { //inject NONSTANDARD NAMING function CURRENTEPOCHTIME27() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF3(address) external view returns (uint256); //inject NONSTANDARD NAMING function REWARDS0(address token) external view returns (ivaultrewards63); //inject NONSTANDARD NAMING function VAULT69(address token) external view returns (ivault53); //inject NONSTANDARD NAMING function ALLOWABLEAMOUNT15(address) external view returns (uint256); //inject NONSTANDARD NAMING function TREASURY79() external view returns (itreasury2); //inject NONSTANDARD NAMING function APPROVEDSTRATEGIES44(address, address) external view returns (bool); //inject NONSTANDARD NAMING function GETHARVESTINFO14(address strategy, address user) //inject NONSTANDARD NAMING external view returns ( uint256 vaultRewardPercentage, uint256 hurdleAmount, uint256 harvestPercentage ); function WITHDRAW24(address, uint256) external; //inject NONSTANDARD NAMING function EARN37(address, uint256) external; //inject NONSTANDARD NAMING function INCREASEHURDLERATE27(address token) external; //inject NONSTANDARD NAMING } // File: contracts/ISwapRouter.sol //SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.5.17; interface swaprouter18 { //inject NONSTANDARD NAMING function WETH90() external pure returns (address); //inject NONSTANDARD NAMING function SWAPEXACTTOKENSFORTOKENS91( //inject NONSTANDARD NAMING uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } // File: contracts/SafeMath.sol pragma solidity 0.5.17; // Note: This file has been modified to include the sqrt function for quadratic voting library math29 { //inject NONSTANDARD NAMING function MAX82(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a >= b ? a : b; } function MIN43(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a < b ? a : b; } function AVERAGE17(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } function SQRT87(uint256 x) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 n = x / 2; uint256 lstX = 0; while (n != lstX){ lstX = n; n = (n + x/n) / 2; } return uint256(n); } } library safemath85 { //inject NONSTANDARD NAMING function ADD14(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB75(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB75(a, b, "SafeMath: subtraction overflow"); } function SUB75(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 MUL41(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 DIV62(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV62(a, b, "SafeMath: division by zero"); } function DIV62(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 MOD3(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD3(a, b, "SafeMath: modulo by zero"); } function MOD3(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } // File: contracts/zeppelin/Address.sol pragma solidity 0.5.17; library address35 { //inject NONSTANDARD NAMING function ISCONTRACT42(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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); } function TOPAYABLE96(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE71(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: contracts/zeppelin/SafeERC20.sol pragma solidity 0.5.17; library safeerc2099 { //inject NONSTANDARD NAMING using safemath85 for uint256; using address35 for address; function SAFETRANSFER62(ierc2080 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.TRANSFER92.selector, to, value)); } function SAFETRANSFERFROM40(ierc2080 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.TRANSFERFROM23.selector, from, to, value)); } function SAFEAPPROVE5(ierc2080 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // 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.ALLOWANCE58(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.APPROVE17.selector, spender, value)); } function SAFEINCREASEALLOWANCE71(ierc2080 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE58(address(this), spender).ADD14(value); CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.APPROVE17.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE44(ierc2080 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE58(address(this), spender).SUB75(value, "SafeERC20: decreased allowance below zero"); CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.APPROVE17.selector, spender, newAllowance)); } function CALLOPTIONALRETURN65(ierc2080 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).ISCONTRACT42(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/vaults/strategy/MStableStrategy.sol //SPDX-License-Identifier: MIT pragma solidity 0.5.17; interface ibpt3 { //inject NONSTANDARD NAMING function TOTALSUPPLY74() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF3(address whom) external view returns (uint); //inject NONSTANDARD NAMING function GETSPOTPRICE26(address tokenIn, address tokenOut) external view returns (uint spotPrice); //inject NONSTANDARD NAMING function SWAPEXACTAMOUNTIN69(address, uint, address, uint, uint) external returns (uint, uint); //inject NONSTANDARD NAMING function SWAPEXACTAMOUNTOUT77(address, uint, address, uint, uint) external returns (uint, uint); //inject NONSTANDARD NAMING function JOINSWAPEXTERNAMOUNTIN73( //inject NONSTANDARD NAMING address tokenIn, uint tokenAmountIn, uint minPoolAmountOut ) external returns (uint poolAmountOut); function EXITSWAPEXTERNAMOUNTOUT85( //inject NONSTANDARD NAMING address tokenOut, uint tokenAmountOut, uint maxPoolAmountIn ) external returns (uint poolAmountIn); function EXITSWAPPOOLAMOUNTIN6( //inject NONSTANDARD NAMING address tokenOut, uint poolAmountIn, uint minAmountOut ) external returns (uint tokenAmountOut); } interface impool6 { //inject NONSTANDARD NAMING function BALANCEOF3(address _account) external view returns (uint256); //inject NONSTANDARD NAMING function EARNED23(address _account) external view returns (uint256, uint256); //inject NONSTANDARD NAMING function STAKE12(uint256 _amount) external; //inject NONSTANDARD NAMING function CLAIMREWARD81() external; //inject NONSTANDARD NAMING function EXIT39() external; //inject NONSTANDARD NAMING } interface imtagov79 { //inject NONSTANDARD NAMING function BALANCEOF3(address _account) external view returns (uint256); //inject NONSTANDARD NAMING function EARNED23(address _account) external view returns (uint256); //inject NONSTANDARD NAMING function CREATELOCK73(uint256 _value, uint256 _unlockTime) external; //inject NONSTANDARD NAMING function WITHDRAW24() external; //inject NONSTANDARD NAMING function INCREASELOCKAMOUNT91(uint256 _value) external; //inject NONSTANDARD NAMING function CLAIMREWARD81() external; //inject NONSTANDARD NAMING } contract mstablestrat66 is istrategy59 { //inject NONSTANDARD NAMING using safeerc2099 for ierc2080; using address35 for address; using safemath85 for uint256; uint256 public constant performance_fee63 = 500; // 5% //inject NONSTANDARD NAMING uint256 public constant denom43 = 10000; //inject NONSTANDARD NAMING uint256 public hurdleLastUpdateTime; uint256 public harvestAmountThisEpoch; uint256 public strategistCollectedFee; uint256 public numPools = 1; ierc2080 internal usdc = ierc2080(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); ierc2080 internal musd = ierc2080(0xe2f2a5C287993345a840Db3B0845fbC70f5935a5); ierc2080 internal mta = ierc2080(0xa3BeD4E1c75D00fa6f4E5E6922DB7261B5E9AcD2); ibpt3 internal musdcBpt = ibpt3(0x72Cd8f4504941Bf8c5a21d1Fd83A96499FD71d2C); swaprouter18 public swapRouter = swaprouter18(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); impool6 internal mPool = impool6(0x881c72D1e6317f10a1cDCBe05040E7564E790C80); imtagov79 internal mtaGov = imtagov79(0xaE8bC96DA4F9A9613c323478BE181FDb2Aa0E1BF); ierc2080 public want = usdc; // should be set only in constructor or hardcoded icontroller20 public controller; // should be set only in constructor address public strategist; // mutable, but only by strategist // want must be equal to an underlying vault token (Eg. USDC) constructor(icontroller20 _controller) public { controller = _controller; strategist = msg.sender; } function GETNAME35() external pure returns (string memory) { //inject NONSTANDARD NAMING return "MstableStrategy"; } function SETSTRATEGIST71(address _strategist) external { //inject NONSTANDARD NAMING require(msg.sender == strategist, "!strategist"); strategist = _strategist; } function SETNUMPOOLSFORSWAP74(uint256 _numPools) external { //inject NONSTANDARD NAMING require(msg.sender == strategist, "!strategist"); numPools = _numPools; } function SETALLOWANCES18(ierc2080 token, address[] calldata recipients, bool isIncrease) external { //inject NONSTANDARD NAMING require(msg.sender == strategist, "!strategist"); for (uint i = 0; i < recipients.length; i++) { require( recipients[i] == address(musdcBpt) || recipients[i] == address(swapRouter) || recipients[i] == address(mPool) || recipients[i] == address(mtaGov), "bad recipient" ); uint256 allowance = isIncrease ? uint256(-1) : 0; token.SAFEAPPROVE5(recipients[i], allowance); } } // Assumed that caller checks against available funds in vault function DEPOSIT94(uint256 amount) public { //inject NONSTANDARD NAMING uint256 availFunds = controller.ALLOWABLEAMOUNT15(address(this)); require(amount <= availFunds, "exceed contAllowance"); controller.EARN37(address(this), amount); // deposit into musdcBpt uint256 bptTokenAmt = musdcBpt.JOINSWAPEXTERNAMOUNTIN73(address(want), amount, 0); // deposit into mstable pool mPool.STAKE12(bptTokenAmt); // deposit any MTA token in this contract into mStaking contract DEPOSITMTAINSTAKING28(); } function BALANCEOF3() external view returns (uint256) { //inject NONSTANDARD NAMING // get balance in mPool uint256 bptStakeAmt = mPool.BALANCEOF3(address(this)); // get usdc + musd amts in BPT, and total BPT uint256 usdcAmt = usdc.BALANCEOF3(address(musdcBpt)); uint256 musdAmt = musd.BALANCEOF3(address(musdcBpt)); uint256 totalBptAmt = musdcBpt.TOTALSUPPLY74(); // convert musd to usdc usdcAmt = usdcAmt.ADD14( musdAmt.MUL41(1e18).DIV62(musdcBpt.GETSPOTPRICE26(address(musd), address(usdc))) ); return bptStakeAmt.MUL41(usdcAmt).DIV62(totalBptAmt); } function EARNED23() external view returns (uint256) { //inject NONSTANDARD NAMING (uint256 earnedAmt,) = mPool.EARNED23(address(this)); return earnedAmt.ADD14(mtaGov.EARNED23(address(this))); } function WITHDRAW24(address token) external { //inject NONSTANDARD NAMING ierc2080 erc20Token = ierc2080(token); require(msg.sender == address(controller), "!controller"); erc20Token.SAFETRANSFER62(address(controller), erc20Token.BALANCEOF3(address(this))); } function WITHDRAW24(uint256 amount) external { //inject NONSTANDARD NAMING require(msg.sender == address(controller), "!controller"); // exit fully mPool.EXIT39(); // convert to desired amount musdcBpt.EXITSWAPEXTERNAMOUNTOUT85(address(want), amount, uint256(-1)); // deposit whatever remaining bpt back into mPool mPool.STAKE12(musdcBpt.BALANCEOF3(address(this))); // send funds to vault want.SAFETRANSFER62(address(controller.VAULT69(address(want))), amount); } function WITHDRAWALL24() external returns (uint256 balance) { //inject NONSTANDARD NAMING require(msg.sender == address(controller), "!controller"); // exit fully mPool.EXIT39(); // convert reward to want tokens // in case swap fails, continue (bool success, ) = address(this).call( abi.encodeWithSignature( "exchangeRewardForWant(bool)", true ) ); // to remove compiler warning success; // convert bpt to want tokens musdcBpt.EXITSWAPPOOLAMOUNTIN6( address(want), musdcBpt.BALANCEOF3(address(this)), 0 ); // exclude collected strategist fee balance = want.BALANCEOF3(address(this)).SUB75(strategistCollectedFee); // send funds to vault want.SAFETRANSFER62(address(controller.VAULT69(address(want))), balance); } function HARVEST87(bool claimMPool, bool claimGov) external { //inject NONSTANDARD NAMING if (claimMPool) mPool.CLAIMREWARD81(); if (claimGov) mtaGov.CLAIMREWARD81(); // convert 80% reward to want tokens // in case swap fails, return (bool success, ) = address(this).call( abi.encodeWithSignature( "exchangeRewardForWant(bool)", false ) ); // to remove compiler warning if (!success) return; uint256 amount = want.BALANCEOF3(address(this)).SUB75(strategistCollectedFee); uint256 vaultRewardPercentage; uint256 hurdleAmount; uint256 harvestPercentage; uint256 epochTime; (vaultRewardPercentage, hurdleAmount, harvestPercentage) = controller.GETHARVESTINFO14(address(this), msg.sender); // check if harvest amount has to be reset if (hurdleLastUpdateTime < epochTime) { // reset collected amount harvestAmountThisEpoch = 0; } // update variables hurdleLastUpdateTime = block.timestamp; harvestAmountThisEpoch = harvestAmountThisEpoch.ADD14(amount); // first, take harvester fee uint256 harvestFee = amount.MUL41(harvestPercentage).DIV62(denom43); want.SAFETRANSFER62(msg.sender, harvestFee); uint256 fee; // then, if hurdle amount has been exceeded, take performance fee if (harvestAmountThisEpoch >= hurdleAmount) { fee = amount.MUL41(performance_fee63).DIV62(denom43); strategistCollectedFee = strategistCollectedFee.ADD14(fee); } // do the subtraction of harvester and strategist fees amount = amount.SUB75(harvestFee).SUB75(fee); // calculate how much is to be re-invested // fee = vault reward amount, reusing variable fee = amount.MUL41(vaultRewardPercentage).DIV62(denom43); want.SAFETRANSFER62(address(controller.REWARDS0(address(want))), fee); controller.REWARDS0(address(want)).NOTIFYREWARDAMOUNT2(fee); amount = amount.SUB75(fee); // finally, use remaining want amount for reinvestment amount = musdcBpt.JOINSWAPEXTERNAMOUNTIN73(address(want), amount, 0); // deposit into mstable pool mPool.STAKE12(amount); // deposit any MTA token in this contract into mStaking contract DEPOSITMTAINSTAKING28(); } function WITHDRAWSTRATEGISTFEE97() external { //inject NONSTANDARD NAMING strategistCollectedFee = 0; want.SAFETRANSFER62(strategist, strategistCollectedFee); } function EXITMGOV72() external { //inject NONSTANDARD NAMING mtaGov.WITHDRAW24(); // convert to want tokens // in case swap fails, continue (bool success, ) = address(this).call( abi.encodeWithSignature( "exchangeRewardForWant(bool)", true ) ); // to remove compiler warning success; want.SAFETRANSFER62( address(controller.REWARDS0(address(want))), want.BALANCEOF3(address(this)).SUB75(strategistCollectedFee) ); } function EXCHANGEREWARDFORWANT67(bool exchangeAll) public { //inject NONSTANDARD NAMING uint256 swapAmt = mta.BALANCEOF3(address(this)); if (swapAmt == 0) return; // do the exchange address[] memory routeDetails = new address[](3); routeDetails[0] = address(mta); routeDetails[1] = swapRouter.WETH90(); routeDetails[2] = address(want); swapRouter.SWAPEXACTTOKENSFORTOKENS91( exchangeAll ? swapAmt : swapAmt.MUL41(8000).DIV62(denom43), 0, routeDetails, address(this), block.timestamp + 100 ); } function DEPOSITMTAINSTAKING28() internal { //inject NONSTANDARD NAMING uint256 mtaBal = mta.BALANCEOF3(address(this)); if (mtaBal == 0) return; if (mtaGov.BALANCEOF3(address(this)) == 0) { // create lock with max time mtaGov.CREATELOCK73(mtaBal, 1632580257); } else { // increase amount mtaGov.INCREASELOCKAMOUNT91(mtaBal); } } }
inject NONSTANDARD NAMING
function EARNED23(address _account) external view returns (uint256);
1,825,129
[ 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, 445, 512, 4391, 2056, 4366, 12, 2867, 389, 4631, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.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: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFundDeployer Interface /// @author Enzyme Council <[email protected]> interface IFundDeployer { function getOwner() external view returns (address); function hasReconfigurationRequest(address) external view returns (bool); function isAllowedBuySharesOnBehalfCaller(address) external view returns (bool); function isAllowedVaultCall( address, bytes4, bytes32 ) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IIntegrationManager interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the IntegrationManager interface IIntegrationManager { enum SpendAssetsHandleType {None, Approve, Transfer} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../IIntegrationManager.sol"; /// @title Integration Adapter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all integration adapters interface IIntegrationAdapter { function parseAssetsForAction( address _vaultProxy, bytes4 _selector, bytes calldata _encodedCallArgs ) external view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../../../utils/FundDeployerOwnerMixin.sol"; import "../utils/actions/ZeroExV2ActionsMixin.sol"; import "../utils/AdapterBase.sol"; /// @title ZeroExV2Adapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter to 0xV2 Exchange Contract contract ZeroExV2Adapter is AdapterBase, FundDeployerOwnerMixin, ZeroExV2ActionsMixin { event AllowedMakerAdded(address indexed account); event AllowedMakerRemoved(address indexed account); mapping(address => bool) private makerToIsAllowed; // Gas could be optimized for the end-user by also storing an immutable ZRX_ASSET_DATA, // for example, but in the narrow OTC use-case of this adapter, taker fees are unlikely. constructor( address _integrationManager, address _exchange, address _fundDeployer, address[] memory _allowedMakers ) public AdapterBase(_integrationManager) FundDeployerOwnerMixin(_fundDeployer) ZeroExV2ActionsMixin(_exchange) { if (_allowedMakers.length > 0) { __addAllowedMakers(_allowedMakers); } } // EXTERNAL FUNCTIONS /// @notice Take an order on 0x /// @param _vaultProxy The VaultProxy of the calling fund /// @param _actionData Data specific to this action /// @param _assetData Parsed spend assets and incoming assets data for this action function takeOrder( address _vaultProxy, bytes calldata _actionData, bytes calldata _assetData ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _assetData) { ( bytes memory encodedZeroExOrderArgs, uint256 takerAssetFillAmount ) = __decodeTakeOrderCallArgs(_actionData); IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs); (, , , bytes memory signature) = __decodeZeroExOrderArgs(encodedZeroExOrderArgs); __zeroExV2TakeOrder(order, takerAssetFillAmount, signature); } ///////////////////////////// // PARSE ASSETS FOR METHOD // ///////////////////////////// /// @notice Parses the expected assets in a particular action /// @param _selector The function selector for the callOnIntegration /// @param _actionData Data specific to this action /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForAction( address, bytes4 _selector, bytes calldata _actionData ) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForAction: _selector invalid"); ( bytes memory encodedZeroExOrderArgs, uint256 takerAssetFillAmount ) = __decodeTakeOrderCallArgs(_actionData); IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs); require( isAllowedMaker(order.makerAddress), "parseAssetsForAction: Order maker is not allowed" ); require( takerAssetFillAmount <= order.takerAssetAmount, "parseAssetsForAction: Taker asset fill amount greater than available" ); address makerAsset = __getAssetAddress(order.makerAssetData); address takerAsset = __getAssetAddress(order.takerAssetData); // Format incoming assets incomingAssets_ = new address[](1); incomingAssets_[0] = makerAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = __calcRelativeQuantity( order.takerAssetAmount, order.makerAssetAmount, takerAssetFillAmount ); if (order.takerFee > 0) { address takerFeeAsset = __getAssetAddress( IZeroExV2(getZeroExV2Exchange()).ZRX_ASSET_DATA() ); uint256 takerFeeFillAmount = __calcRelativeQuantity( order.takerAssetAmount, order.takerFee, takerAssetFillAmount ); // fee calculated relative to taker fill amount if (takerFeeAsset == makerAsset) { require( order.takerFee < order.makerAssetAmount, "parseAssetsForAction: Fee greater than makerAssetAmount" ); spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount; minIncomingAssetAmounts_[0] = minIncomingAssetAmounts_[0].sub(takerFeeFillAmount); } else if (takerFeeAsset == takerAsset) { spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount.add(takerFeeFillAmount); } else { spendAssets_ = new address[](2); spendAssets_[0] = takerAsset; spendAssets_[1] = takerFeeAsset; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = takerAssetFillAmount; spendAssetAmounts_[1] = takerFeeFillAmount; } } else { spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount; } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } // PRIVATE FUNCTIONS /// @dev Decode the parameters of a takeOrder call /// @param _actionData Encoded parameters passed from client side /// @return encodedZeroExOrderArgs_ Encoded args of the 0x order /// @return takerAssetFillAmount_ Amount of taker asset to fill function __decodeTakeOrderCallArgs(bytes memory _actionData) private pure returns (bytes memory encodedZeroExOrderArgs_, uint256 takerAssetFillAmount_) { return abi.decode(_actionData, (bytes, uint256)); } ///////////////////////////// // ALLOWED MAKERS REGISTRY // ///////////////////////////// /// @notice Adds accounts to the list of allowed 0x order makers /// @param _accountsToAdd Accounts to add function addAllowedMakers(address[] calldata _accountsToAdd) external onlyFundDeployerOwner { __addAllowedMakers(_accountsToAdd); } /// @notice Removes accounts from the list of allowed 0x order makers /// @param _accountsToRemove Accounts to remove function removeAllowedMakers(address[] calldata _accountsToRemove) external onlyFundDeployerOwner { require(_accountsToRemove.length > 0, "removeAllowedMakers: Empty _accountsToRemove"); for (uint256 i; i < _accountsToRemove.length; i++) { require( isAllowedMaker(_accountsToRemove[i]), "removeAllowedMakers: Account is not an allowed maker" ); makerToIsAllowed[_accountsToRemove[i]] = false; emit AllowedMakerRemoved(_accountsToRemove[i]); } } /// @dev Helper to add accounts to the list of allowed makers function __addAllowedMakers(address[] memory _accountsToAdd) private { require(_accountsToAdd.length > 0, "__addAllowedMakers: Empty _accountsToAdd"); for (uint256 i; i < _accountsToAdd.length; i++) { require(!isAllowedMaker(_accountsToAdd[i]), "__addAllowedMakers: Value already set"); makerToIsAllowed[_accountsToAdd[i]] = true; emit AllowedMakerAdded(_accountsToAdd[i]); } } /// @dev Parses user inputs into a ZeroExV2.Order format function __constructOrderStruct(bytes memory _encodedOrderArgs) private pure returns (IZeroExV2.Order memory order_) { ( address[4] memory orderAddresses, uint256[6] memory orderValues, bytes[2] memory orderData, ) = __decodeZeroExOrderArgs(_encodedOrderArgs); return IZeroExV2.Order({ makerAddress: orderAddresses[0], takerAddress: orderAddresses[1], feeRecipientAddress: orderAddresses[2], senderAddress: orderAddresses[3], makerAssetAmount: orderValues[0], takerAssetAmount: orderValues[1], makerFee: orderValues[2], takerFee: orderValues[3], expirationTimeSeconds: orderValues[4], salt: orderValues[5], makerAssetData: orderData[0], takerAssetData: orderData[1] }); } /// @dev Decode the parameters of a 0x order /// @param _encodedZeroExOrderArgs Encoded parameters of the 0x order /// @return orderAddresses_ Addresses used in the order /// - [0] 0x Order param: makerAddress /// - [1] 0x Order param: takerAddress /// - [2] 0x Order param: feeRecipientAddress /// - [3] 0x Order param: senderAddress /// @return orderValues_ Values used in the order /// - [0] 0x Order param: makerAssetAmount /// - [1] 0x Order param: takerAssetAmount /// - [2] 0x Order param: makerFee /// - [3] 0x Order param: takerFee /// - [4] 0x Order param: expirationTimeSeconds /// - [5] 0x Order param: salt /// @return orderData_ Bytes data used in the order /// - [0] 0x Order param: makerAssetData /// - [1] 0x Order param: takerAssetData /// @return signature_ Signature of the order function __decodeZeroExOrderArgs(bytes memory _encodedZeroExOrderArgs) private pure returns ( address[4] memory orderAddresses_, uint256[6] memory orderValues_, bytes[2] memory orderData_, bytes memory signature_ ) { return abi.decode(_encodedZeroExOrderArgs, (address[4], uint256[6], bytes[2], bytes)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Checks whether an account is an allowed maker of 0x orders /// @param _who The account to check /// @return isAllowedMaker_ True if _who is an allowed maker function isAllowedMaker(address _who) public view returns (bool isAllowedMaker_) { return makerToIsAllowed[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../utils/AssetHelpers.sol"; import "../IIntegrationAdapter.sol"; import "./IntegrationSelectors.sol"; /// @title AdapterBase Contract /// @author Enzyme Council <[email protected]> /// @notice A base contract for integration adapters abstract contract AdapterBase is IIntegrationAdapter, IntegrationSelectors, AssetHelpers { using SafeERC20 for ERC20; address internal immutable INTEGRATION_MANAGER; /// @dev Provides a standard implementation for transferring incoming assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionIncomingAssetsTransferHandler( address _vaultProxy, bytes memory _assetData ) { _; (, , address[] memory incomingAssets) = __decodeAssetData(_assetData); __pushFullAssetBalances(_vaultProxy, incomingAssets); } /// @dev Provides a standard implementation for transferring unspent spend assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionSpendAssetsTransferHandler(address _vaultProxy, bytes memory _assetData) { _; (address[] memory spendAssets, , ) = __decodeAssetData(_assetData); __pushFullAssetBalances(_vaultProxy, spendAssets); } modifier onlyIntegrationManager { require( msg.sender == INTEGRATION_MANAGER, "Only the IntegrationManager can call this function" ); _; } constructor(address _integrationManager) public { INTEGRATION_MANAGER = _integrationManager; } // INTERNAL FUNCTIONS /// @dev Helper to decode the _assetData param passed to adapter call function __decodeAssetData(bytes memory _assetData) internal pure returns ( address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_ ) { return abi.decode(_assetData, (address[], uint256[], address[])); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `INTEGRATION_MANAGER` variable /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value function getIntegrationManager() external view returns (address integrationManager_) { return INTEGRATION_MANAGER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IntegrationSelectors Contract /// @author Enzyme Council <[email protected]> /// @notice Selectors for integration actions /// @dev Selectors are created from their signatures rather than hardcoded for easy verification abstract contract IntegrationSelectors { // Trading bytes4 public constant TAKE_ORDER_SELECTOR = bytes4( keccak256("takeOrder(address,bytes,bytes)") ); // Lending bytes4 public constant LEND_SELECTOR = bytes4(keccak256("lend(address,bytes,bytes)")); bytes4 public constant REDEEM_SELECTOR = bytes4(keccak256("redeem(address,bytes,bytes)")); // Staking bytes4 public constant STAKE_SELECTOR = bytes4(keccak256("stake(address,bytes,bytes)")); bytes4 public constant UNSTAKE_SELECTOR = bytes4(keccak256("unstake(address,bytes,bytes)")); // Rewards bytes4 public constant CLAIM_REWARDS_SELECTOR = bytes4( keccak256("claimRewards(address,bytes,bytes)") ); // Combined bytes4 public constant LEND_AND_STAKE_SELECTOR = bytes4( keccak256("lendAndStake(address,bytes,bytes)") ); bytes4 public constant UNSTAKE_AND_REDEEM_SELECTOR = bytes4( keccak256("unstakeAndRedeem(address,bytes,bytes)") ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../../../../interfaces/IZeroExV2.sol"; import "../../../../../utils/AssetHelpers.sol"; import "../../../../../utils/MathHelpers.sol"; /// @title ZeroExV2ActionsMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Mixin contract for interacting with the ZeroExV2 exchange functions abstract contract ZeroExV2ActionsMixin is AssetHelpers, MathHelpers { address private immutable ZERO_EX_V2_EXCHANGE; constructor(address _exchange) public { ZERO_EX_V2_EXCHANGE = _exchange; } /// @dev Helper to execute takeOrder function __zeroExV2TakeOrder( IZeroExV2.Order memory _order, uint256 _takerAssetFillAmount, bytes memory _signature ) internal { // Approve spend assets as needed __approveAssetMaxAsNeeded( __getAssetAddress(_order.takerAssetData), __getAssetProxy(_order.takerAssetData), _takerAssetFillAmount ); // Ignores whether makerAsset or takerAsset overlap with the takerFee asset for simplicity if (_order.takerFee > 0) { bytes memory zrxData = IZeroExV2(ZERO_EX_V2_EXCHANGE).ZRX_ASSET_DATA(); __approveAssetMaxAsNeeded( __getAssetAddress(zrxData), __getAssetProxy(zrxData), __calcRelativeQuantity( _order.takerAssetAmount, _order.takerFee, _takerAssetFillAmount ) // fee calculated relative to taker fill amount ); } // Execute order IZeroExV2(ZERO_EX_V2_EXCHANGE).fillOrder(_order, _takerAssetFillAmount, _signature); } /// @dev Parses the asset address from 0x assetData function __getAssetAddress(bytes memory _assetData) internal pure returns (address assetAddress_) { assembly { assetAddress_ := mload(add(_assetData, 36)) } } /// @dev Gets the 0x assetProxy address for an ERC20 token function __getAssetProxy(bytes memory _assetData) internal view returns (address assetProxy_) { bytes4 assetProxyId; assembly { assetProxyId := and( mload(add(_assetData, 32)), 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000 ) } assetProxy_ = IZeroExV2(getZeroExV2Exchange()).getAssetProxy(assetProxyId); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ZERO_EX_V2_EXCHANGE` variable value /// @return zeroExV2Exchange_ The `ZERO_EX_V2_EXCHANGE` variable value function getZeroExV2Exchange() public view returns (address zeroExV2Exchange_) { return ZERO_EX_V2_EXCHANGE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @dev Minimal interface for our interactions with the ZeroEx Exchange contract interface IZeroExV2 { struct Order { address makerAddress; address takerAddress; address feeRecipientAddress; address senderAddress; uint256 makerAssetAmount; uint256 takerAssetAmount; uint256 makerFee; uint256 takerFee; uint256 expirationTimeSeconds; uint256 salt; bytes makerAssetData; bytes takerAssetData; } struct OrderInfo { uint8 orderStatus; bytes32 orderHash; uint256 orderTakerAssetFilledAmount; } struct FillResults { uint256 makerAssetFilledAmount; uint256 takerAssetFilledAmount; uint256 makerFeePaid; uint256 takerFeePaid; } function ZRX_ASSET_DATA() external view returns (bytes memory); function filled(bytes32) external view returns (uint256); function cancelled(bytes32) external view returns (bool); function getOrderInfo(Order calldata) external view returns (OrderInfo memory); function getAssetProxy(bytes4) external view returns (address); function isValidSignature( bytes32, address, bytes calldata ) external view returns (bool); function preSign( bytes32, address, bytes calldata ) external; function cancelOrder(Order calldata) external; function fillOrder( Order calldata, uint256, bytes calldata ) external returns (FillResults memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /// @title AssetHelpers Contract /// @author Enzyme Council <[email protected]> /// @notice A util contract for common token actions abstract contract AssetHelpers { using SafeERC20 for ERC20; using SafeMath for uint256; /// @dev Helper to approve a target account with the max amount of an asset. /// This is helpful for fully trusted contracts, such as adapters that /// interact with external protocol like Uniswap, Compound, etc. function __approveAssetMaxAsNeeded( address _asset, address _target, uint256 _neededAmount ) internal { uint256 allowance = ERC20(_asset).allowance(address(this), _target); if (allowance < _neededAmount) { if (allowance > 0) { ERC20(_asset).safeApprove(_target, 0); } ERC20(_asset).safeApprove(_target, type(uint256).max); } } /// @dev Helper to transfer full asset balances from the current contract to a target function __pushFullAssetBalances(address _target, address[] memory _assets) internal returns (uint256[] memory amountsTransferred_) { amountsTransferred_ = new uint256[](_assets.length); for (uint256 i; i < _assets.length; i++) { ERC20 assetContract = ERC20(_assets[i]); amountsTransferred_[i] = assetContract.balanceOf(address(this)); if (amountsTransferred_[i] > 0) { assetContract.safeTransfer(_target, amountsTransferred_[i]); } } return amountsTransferred_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../core/fund-deployer/IFundDeployer.sol"; /// @title FundDeployerOwnerMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract that defers ownership to the owner of FundDeployer abstract contract FundDeployerOwnerMixin { address internal immutable FUND_DEPLOYER; modifier onlyFundDeployerOwner() { require( msg.sender == getOwner(), "onlyFundDeployerOwner: Only the FundDeployer owner can call this function" ); _; } constructor(address _fundDeployer) public { FUND_DEPLOYER = _fundDeployer; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the FundDeployer contract function getOwner() public view returns (address owner_) { return IFundDeployer(FUND_DEPLOYER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FUND_DEPLOYER` variable /// @return fundDeployer_ The `FUND_DEPLOYER` variable value function getFundDeployer() public view returns (address fundDeployer_) { return FUND_DEPLOYER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; /// @title MathHelpers Contract /// @author Enzyme Council <[email protected]> /// @notice Helper functions for common math operations abstract contract MathHelpers { using SafeMath for uint256; /// @dev Calculates a proportional value relative to a known ratio. /// Caller is responsible as-necessary for: /// 1. validating _quantity1 to be non-zero /// 2. validating relativeQuantity2_ to be non-zero function __calcRelativeQuantity( uint256 _quantity1, uint256 _quantity2, uint256 _relativeQuantity1 ) internal pure returns (uint256 relativeQuantity2_) { return _relativeQuantity1.mul(_quantity2).div(_quantity1); } }
@dev Parses user inputs into a ZeroExV2.Order format
function __constructOrderStruct(bytes memory _encodedOrderArgs) private pure returns (IZeroExV2.Order memory order_) { ( address[4] memory orderAddresses, uint256[6] memory orderValues, bytes[2] memory orderData, ) = __decodeZeroExOrderArgs(_encodedOrderArgs); return IZeroExV2.Order({ makerAddress: orderAddresses[0], takerAddress: orderAddresses[1], feeRecipientAddress: orderAddresses[2], senderAddress: orderAddresses[3], makerAssetAmount: orderValues[0], takerAssetAmount: orderValues[1], makerFee: orderValues[2], takerFee: orderValues[3], expirationTimeSeconds: orderValues[4], salt: orderValues[5], makerAssetData: orderData[0], takerAssetData: orderData[1] }); }
149,989
[ 1, 6656, 729, 4540, 1368, 279, 12744, 424, 58, 22, 18, 2448, 740, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1001, 10062, 2448, 3823, 12, 3890, 3778, 389, 10787, 2448, 2615, 13, 203, 3639, 3238, 203, 3639, 16618, 203, 3639, 1135, 261, 6867, 2439, 424, 58, 22, 18, 2448, 3778, 1353, 67, 13, 203, 565, 288, 203, 3639, 261, 203, 5411, 1758, 63, 24, 65, 3778, 1353, 7148, 16, 203, 5411, 2254, 5034, 63, 26, 65, 3778, 1353, 1972, 16, 203, 5411, 1731, 63, 22, 65, 3778, 1353, 751, 16, 203, 203, 3639, 262, 273, 1001, 3922, 7170, 424, 2448, 2615, 24899, 10787, 2448, 2615, 1769, 203, 203, 3639, 327, 203, 5411, 467, 7170, 424, 58, 22, 18, 2448, 12590, 203, 7734, 312, 6388, 1887, 30, 1353, 7148, 63, 20, 6487, 203, 7734, 268, 6388, 1887, 30, 1353, 7148, 63, 21, 6487, 203, 7734, 14036, 18241, 1887, 30, 1353, 7148, 63, 22, 6487, 203, 7734, 5793, 1887, 30, 1353, 7148, 63, 23, 6487, 203, 7734, 312, 6388, 6672, 6275, 30, 1353, 1972, 63, 20, 6487, 203, 7734, 268, 6388, 6672, 6275, 30, 1353, 1972, 63, 21, 6487, 203, 7734, 312, 6388, 14667, 30, 1353, 1972, 63, 22, 6487, 203, 7734, 268, 6388, 14667, 30, 1353, 1972, 63, 23, 6487, 203, 7734, 7686, 950, 6762, 30, 1353, 1972, 63, 24, 6487, 203, 7734, 4286, 30, 1353, 1972, 63, 25, 6487, 203, 7734, 312, 6388, 6672, 751, 30, 1353, 751, 63, 20, 6487, 203, 7734, 268, 6388, 6672, 751, 30, 1353, 751, 63, 21, 65, 203, 5411, 15549, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xF1C057717F4478878e14Bb5C6fd0D27F3CC85838/sources/dss-interfaces-master/src/dss/ChainlogAbstract.sol
ERROR: type should be string, got " https:github.com/makerdao/dss-chain-log"
interface ChainlogAbstract { function wards(address) external view returns (uint256); function rely(address) external; function deny(address) external; function keys() external view returns (bytes32[] memory); function version() external view returns (string memory); function ipfs() external view returns (string memory); function setVersion(string calldata) external; function setSha256sum(string calldata) external; function setIPFS(string calldata) external; function setAddress(bytes32,address) external; function removeAddress(bytes32) external; function count() external view returns (uint256); function get(uint256) external view returns (bytes32,address); function list() external view returns (bytes32[] memory); function getAddress(bytes32) external view returns (address); pragma solidity >=0.5.12; }
12,423,677
[ 1, 4528, 30, 6662, 18, 832, 19, 29261, 2414, 83, 19, 72, 1049, 17, 5639, 17, 1330, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 7824, 1330, 7469, 288, 203, 565, 445, 341, 14727, 12, 2867, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 565, 445, 21187, 12, 2867, 13, 3903, 31, 203, 565, 445, 17096, 12, 2867, 13, 3903, 31, 203, 565, 445, 1311, 1435, 3903, 1476, 1135, 261, 3890, 1578, 8526, 3778, 1769, 203, 565, 445, 1177, 1435, 3903, 1476, 1135, 261, 1080, 3778, 1769, 203, 565, 445, 2359, 2556, 1435, 3903, 1476, 1135, 261, 1080, 3778, 1769, 203, 565, 445, 16770, 12, 1080, 745, 892, 13, 3903, 31, 203, 565, 445, 444, 20375, 5034, 1364, 12, 1080, 745, 892, 13, 3903, 31, 203, 565, 445, 444, 2579, 4931, 12, 1080, 745, 892, 13, 3903, 31, 203, 565, 445, 444, 1887, 12, 3890, 1578, 16, 2867, 13, 3903, 31, 203, 565, 445, 1206, 1887, 12, 3890, 1578, 13, 3903, 31, 203, 565, 445, 1056, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 565, 445, 336, 12, 11890, 5034, 13, 3903, 1476, 1135, 261, 3890, 1578, 16, 2867, 1769, 203, 565, 445, 666, 1435, 3903, 1476, 1135, 261, 3890, 1578, 8526, 3778, 1769, 203, 565, 445, 14808, 12, 3890, 1578, 13, 3903, 1476, 1135, 261, 2867, 1769, 203, 683, 9454, 18035, 560, 1545, 20, 18, 25, 18, 2138, 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 ]
// SPDX-License-Identifier: MIT AND AGPLv3 // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // File: contracts/common/Constants.sol pragma solidity >=0.6.0 <0.7.0; contract Constants { uint8 public constant N_COINS = 3; uint8 public constant DEFAULT_DECIMALS = 18; // GToken and Controller use this decimals uint256 public constant DEFAULT_DECIMALS_FACTOR = uint256(10)**DEFAULT_DECIMALS; uint8 public constant CHAINLINK_PRICE_DECIMALS = 8; uint256 public constant CHAINLINK_PRICE_DECIMAL_FACTOR = uint256(10)**CHAINLINK_PRICE_DECIMALS; uint8 public constant PERCENTAGE_DECIMALS = 4; uint256 public constant PERCENTAGE_DECIMAL_FACTOR = uint256(10)**PERCENTAGE_DECIMALS; uint256 public constant CURVE_RATIO_DECIMALS = 6; uint256 public constant CURVE_RATIO_DECIMALS_FACTOR = uint256(10)**CURVE_RATIO_DECIMALS; } // File: contracts/interfaces/IToken.sol pragma solidity >=0.6.0 <0.7.0; interface IToken { function factor() external view returns (uint256); function factor(uint256 totalAssets) external view returns (uint256); function mint( address account, uint256 _factor, uint256 amount ) external; function burn( address account, uint256 _factor, uint256 amount ) external; function burnAll(address account) external; function totalAssets() external view returns (uint256); function getPricePerShare() external view returns (uint256); function getShareAssets(uint256 shares) external view returns (uint256); function getAssets(address account) external view returns (uint256); } // File: contracts/interfaces/IVault.sol pragma solidity >=0.6.0 <0.7.0; interface IVault { function withdraw(uint256 amount) external; function withdraw(uint256 amount, address recipient) external; function withdrawByStrategyOrder( uint256 amount, address recipient, bool reversed ) external; function withdrawByStrategyIndex( uint256 amount, address recipient, uint256 strategyIndex ) external; function deposit(uint256 amount) external; function updateStrategyRatio(uint256[] calldata strategyRetios) external; function totalAssets() external view returns (uint256); function getStrategiesLength() external view returns (uint256); function strategyHarvestTrigger(uint256 index, uint256 callCost) external view returns (bool); function strategyHarvest(uint256 index) external returns (bool); function getStrategyAssets(uint256 index) external view returns (uint256); function token() external view returns (address); function vault() external view returns (address); function investTrigger() external view returns (bool); function invest() external; } // File: contracts/common/FixedContracts.sol pragma solidity >=0.6.0 <0.7.0; contract FixedStablecoins is Constants { address public immutable DAI; // = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public immutable USDC; // = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public immutable USDT; // = 0xdAC17F958D2ee523a2206206994597C13D831ec7; uint256 public immutable DAI_DECIMALS; // = 1E18; uint256 public immutable USDC_DECIMALS; // = 1E6; uint256 public immutable USDT_DECIMALS; // = 1E6; constructor(address[N_COINS] memory _tokens, uint256[N_COINS] memory _decimals) public { DAI = _tokens[0]; USDC = _tokens[1]; USDT = _tokens[2]; DAI_DECIMALS = _decimals[0]; USDC_DECIMALS = _decimals[1]; USDT_DECIMALS = _decimals[2]; } function underlyingTokens() internal view returns (address[N_COINS] memory tokens) { tokens[0] = DAI; tokens[1] = USDC; tokens[2] = USDT; } function getToken(uint256 index) internal view returns (address) { if (index == 0) { return DAI; } else if (index == 1) { return USDC; } else { return USDT; } } function decimals() internal view returns (uint256[N_COINS] memory _decimals) { _decimals[0] = DAI_DECIMALS; _decimals[1] = USDC_DECIMALS; _decimals[2] = USDT_DECIMALS; } function getDecimal(uint256 index) internal view returns (uint256) { if (index == 0) { return DAI_DECIMALS; } else if (index == 1) { return USDC_DECIMALS; } else { return USDT_DECIMALS; } } } contract FixedGTokens { IToken public immutable pwrd; IToken public immutable gvt; constructor(address _pwrd, address _gvt) public { pwrd = IToken(_pwrd); gvt = IToken(_gvt); } function gTokens(bool _pwrd) internal view returns (IToken) { if (_pwrd) { return pwrd; } else { return gvt; } } } contract FixedVaults is Constants { address public immutable DAI_VAULT; address public immutable USDC_VAULT; address public immutable USDT_VAULT; constructor(address[N_COINS] memory _vaults) public { DAI_VAULT = _vaults[0]; USDC_VAULT = _vaults[1]; USDT_VAULT = _vaults[2]; } function getVault(uint256 index) internal view returns (address) { if (index == 0) { return DAI_VAULT; } else if (index == 1) { return USDC_VAULT; } else { return USDT_VAULT; } } function vaults() internal view returns (address[N_COINS] memory _vaults) { _vaults[0] = DAI_VAULT; _vaults[1] = USDC_VAULT; _vaults[2] = USDT_VAULT; } } // File: contracts/interfaces/ICurve.sol pragma solidity >=0.6.0 <0.7.0; interface ICurve3Pool { function coins(uint256 i) external view returns (address); function get_virtual_price() external view returns (uint256); function get_dy( int128 i, int128 j, uint256 dx ) external view returns (uint256); function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256); function calc_token_amount(uint256[3] calldata inAmounts, bool deposit) external view returns (uint256); function balances(uint256 i) external view returns (uint256); } interface ICurve3Deposit { function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function add_liquidity(uint256[3] calldata uamounts, uint256 min_mint_amount) external; function remove_liquidity(uint256 amount, uint256[3] calldata min_uamounts) external; function remove_liquidity_imbalance(uint256[3] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_uamount ) external; function get_dy( int128 i, int128 j, uint256 dx ) external view returns (uint256); } interface ICurveMetaPool { function coins(uint256 i) external view returns (address); function get_virtual_price() external view returns (uint256); function get_dy_underlying( int128 i, int128 j, uint256 dx ) external view returns (uint256); function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256); function calc_token_amount(uint256[2] calldata inAmounts, bool deposit) external view returns (uint256); function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function add_liquidity(uint256[2] calldata uamounts, uint256 min_mint_amount) external; function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_uamount ) external; } interface ICurveZap { function add_liquidity(uint256[4] calldata uamounts, uint256 min_mint_amount) external; function remove_liquidity(uint256 amount, uint256[4] calldata min_uamounts) external; function remove_liquidity_imbalance(uint256[4] calldata amounts, uint256 max_burn_amount) external; function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_uamount ) external; function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256); function calc_token_amount(uint256[4] calldata inAmounts, bool deposit) external view returns (uint256); function pool() external view returns (address); } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/interfaces/IController.sol pragma solidity >=0.6.0 <0.7.0; interface IController { function stablecoins() external view returns (address[3] memory); function vaults() external view returns (address[3] memory); function underlyingVaults(uint256 i) external view returns (address vault); function curveVault() external view returns (address); function pnl() external view returns (address); function insurance() external view returns (address); function lifeGuard() external view returns (address); function buoy() external view returns (address); function reward() external view returns (address); function isValidBigFish( bool pwrd, bool deposit, uint256 amount ) external view returns (bool); function withdrawHandler() external view returns (address); function emergencyHandler() external view returns (address); function depositHandler() external view returns (address); function totalAssets() external view returns (uint256); function gTokenTotalAssets() external view returns (uint256); function eoaOnly(address sender) external; function getSkimPercent() external view returns (uint256); function gToken(bool _pwrd) external view returns (address); function emergencyState() external view returns (bool); function deadCoin() external view returns (uint256); function distributeStrategyGainLoss(uint256 gain, uint256 loss) external; function burnGToken( bool pwrd, bool all, address account, uint256 amount, uint256 bonus ) external; function mintGToken( bool pwrd, address account, uint256 amount ) external; function getUserAssets(bool pwrd, address account) external view returns (uint256 deductUsd); function referrals(address account) external view returns (address); function addReferral(address account, address referral) external; function getStrategiesTargetRatio() external view returns (uint256[] memory); function withdrawalFee(bool pwrd) external view returns (uint256); function validGTokenDecrease(uint256 amount) external view returns (bool); } // File: contracts/interfaces/IPausable.sol pragma solidity >=0.6.0 <0.7.0; interface IPausable { function paused() external view returns (bool); } // File: contracts/common/Controllable.sol pragma solidity >=0.6.0 <0.7.0; contract Controllable is Ownable { address public controller; event ChangeController(address indexed oldController, address indexed newController); /// Modifier to make a function callable only when the contract is not paused. /// Requirements: /// - The contract must not be paused. modifier whenNotPaused() { require(!_pausable().paused(), "Pausable: paused"); _; } /// Modifier to make a function callable only when the contract is paused /// Requirements: /// - The contract must be paused modifier whenPaused() { require(_pausable().paused(), "Pausable: not paused"); _; } /// @notice Returns true if the contract is paused, and false otherwise function ctrlPaused() public view returns (bool) { return _pausable().paused(); } function setController(address newController) external onlyOwner { require(newController != address(0), "setController: !0x"); address oldController = controller; controller = newController; emit ChangeController(oldController, newController); } function _controller() internal view returns (IController) { require(controller != address(0), "Controller not set"); return IController(controller); } function _pausable() internal view returns (IPausable) { require(controller != address(0), "Controller not set"); return IPausable(controller); } } // File: contracts/interfaces/IBuoy.sol pragma solidity >=0.6.0 <0.7.0; interface IBuoy { function safetyCheck() external view returns (bool); function updateRatios() external returns (bool); function updateRatiosWithTolerance(uint256 tolerance) external returns (bool); function lpToUsd(uint256 inAmount) external view returns (uint256); function usdToLp(uint256 inAmount) external view returns (uint256); function stableToUsd(uint256[3] calldata inAmount, bool deposit) external view returns (uint256); function stableToLp(uint256[3] calldata inAmount, bool deposit) external view returns (uint256); function singleStableFromLp(uint256 inAmount, int128 i) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function singleStableFromUsd(uint256 inAmount, int128 i) external view returns (uint256); function singleStableToUsd(uint256 inAmount, uint256 i) external view returns (uint256); } // File: contracts/interfaces/IChainPrice.sol pragma solidity >=0.6.0 <0.7.0; interface IChainPrice { function getPriceFeed(uint256 i) external view returns (uint256 _price); } // File: contracts/interfaces/IERC20Detailed.sol pragma solidity >=0.6.0 <0.7.0; interface IERC20Detailed { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // File: contracts/pools/oracle/Buoy3Pool.sol pragma solidity >=0.6.0 <0.7.0; /// @notice Contract for calculating prices of underlying assets and LP tokens in Curve pool. Also /// used to sanity check pool against external oracle, to ensure that pools underlying coin ratios /// are within a specific range (measued in BP) of the external oracles coin price ratios. /// Sanity check: /// The Buoy checks previously recorded (cached) curve coin dy, which it compares against current curve dy, /// blocking any interaction that is outside a certain tolerance (oracle_check_tolerance). When updting the cached /// value, the buoy uses chainlink to ensure that curves prices arent off peg. contract Buoy3Pool is FixedStablecoins, Controllable, IBuoy, IChainPrice { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public oracle_check_tolerance = 1000; uint256 public curve_check_tolerance = 150; uint256 constant CHAIN_FACTOR = 100; ICurve3Pool public immutable curvePool; mapping(uint256 => uint256) public lastRatio; // Chianlink price feed address public immutable daiUsdAgg; address public immutable usdcUsdAgg; address public immutable usdtUsdAgg; event LogNewOracleTolerance(uint256 oldLimit, uint256 newLimit); event LogNewCurveTolerance(uint256 oldLimit, uint256 newLimit); event LogNewRatios(uint256[N_COINS] newRatios); constructor( address _crv3pool, address[N_COINS] memory _tokens, uint256[N_COINS] memory _decimals, address[N_COINS] memory aggregators ) public FixedStablecoins(_tokens, _decimals) { curvePool = ICurve3Pool(_crv3pool); daiUsdAgg = aggregators[0]; usdcUsdAgg = aggregators[1]; usdtUsdAgg = aggregators[2]; } /// @notice Set limit for how much Curve pool and external oracle is allowed /// to deviate before failing transactions /// @param newLimit New threshold in 1E6 function setOracleTolerance(uint256 newLimit) external onlyOwner { uint256 oldLimit = oracle_check_tolerance; oracle_check_tolerance = newLimit; emit LogNewOracleTolerance(oldLimit, newLimit); } /// @notice Set limit for how much Curve pool current and cached values /// can deviate before failing transactions /// @param newLimit New threshold in 1E6 function setCurveTolerance(uint256 newLimit) external onlyOwner { uint256 oldLimit = curve_check_tolerance; curve_check_tolerance = newLimit; emit LogNewCurveTolerance(oldLimit, newLimit); } /// @notice Check the health of the Curve pool: /// Ratios are checked by the following heuristic: /// Orcale A - Curve /// Oracle B - External oracle /// Both oracles establish ratios for a set of stable coins /// (a, b, c) /// and product the following set of ratios: /// (a/a, a/b, a/c), (b/b, b/a, b/c), (c/c, c/a, c/b) /// 1) ratios between a stable coin and itself can be discarded /// 2) inverted ratios, a/b vs b/a, while producing different results /// should both reflect similar in any one of the two underlying assets, /// but in opposite directions. This difference between the two will increase /// as the two assets drift apart, but is considered insignificant at the required /// treshold /// This mean that the following set should provide the necessary coverage checks /// to establish that the coins pricing is healthy: /// (a/b, a/c, c/b)) function safetyCheck() external view override returns (bool) { uint256 _ratio; for (uint256 i = 1; i < N_COINS; i++) { _ratio = curvePool.get_dy(int128(0), int128(i), getDecimal(0)); _ratio = abs(int256(_ratio) - int256(lastRatio[i - 1])); if (_ratio > curve_check_tolerance) { return false; } } _ratio = curvePool.get_dy(int128(2), int128(1), getDecimal(1)); _ratio = abs(int256(_ratio) - int256(lastRatio[N_COINS - 1])); if (_ratio > curve_check_tolerance) { return false; } return true; } /// @notice Check depths in curve pool /// @param tolerance Check that the pool is within a given tolerance function healthCheck(uint256 tolerance) external view returns (bool, uint256) { uint256[N_COINS] memory balances; uint256 total; uint256 ratio; for (uint256 i = 0; i < N_COINS; i++) { uint256 balance = curvePool.balances(i); balance = balance.mul(1E18 / getDecimal(i)); total = total.add(balance); balances[i] = balance; } for (uint256 i = 0; i < N_COINS; i++) { ratio = balances[i].mul(PERCENTAGE_DECIMAL_FACTOR).div(total); if (ratio < tolerance) { return (false, i); } } return (true, N_COINS); } /// @notice Updated cached curve value with a custom tolerance towards chainlink /// @param tolerance How much difference between curve and chainlink can be tolerated function updateRatiosWithTolerance(uint256 tolerance) external override returns (bool) { require(msg.sender == controller || msg.sender == owner(), "updateRatiosWithTolerance: !authorized"); return _updateRatios(tolerance); } /// @notice Updated cached curve values function updateRatios() external override returns (bool) { require(msg.sender == controller || msg.sender == owner(), "updateRatios: !authorized"); return _updateRatios(oracle_check_tolerance); } /// @notice Get USD value for a specific input amount of tokens, slippage included function stableToUsd(uint256[N_COINS] calldata inAmounts, bool deposit) external view override returns (uint256) { return _stableToUsd(inAmounts, deposit); } /// @notice Get estimate USD price of a stablecoin amount /// @param inAmount Token amount /// @param i Index of token function singleStableToUsd(uint256 inAmount, uint256 i) external view override returns (uint256) { uint256[N_COINS] memory inAmounts; inAmounts[i] = inAmount; return _stableToUsd(inAmounts, true); } /// @notice Get LP token value of input amount of tokens function stableToLp(uint256[N_COINS] calldata tokenAmounts, bool deposit) external view override returns (uint256) { return _stableToLp(tokenAmounts, deposit); } /// @notice Get LP token value of input amount of single token function singleStableFromUsd(uint256 inAmount, int128 i) external view override returns (uint256) { return _singleStableFromLp(_usdToLp(inAmount), i); } /// @notice Get LP token value of input amount of single token function singleStableFromLp(uint256 inAmount, int128 i) external view override returns (uint256) { return _singleStableFromLp(inAmount, i); } /// @notice Get USD price of LP tokens you receive for a specific input amount of tokens, slippage included function lpToUsd(uint256 inAmount) external view override returns (uint256) { return _lpToUsd(inAmount); } /// @notice Convert USD amount to LP tokens function usdToLp(uint256 inAmount) external view override returns (uint256) { return _usdToLp(inAmount); } /// @notice Split LP token amount to balance of pool tokens /// @param inAmount Amount of LP tokens /// @param totalBalance Total balance of pool function poolBalances(uint256 inAmount, uint256 totalBalance) internal view returns (uint256[N_COINS] memory balances) { uint256[N_COINS] memory _balances; for (uint256 i = 0; i < N_COINS; i++) { _balances[i] = (IERC20(getToken(i)).balanceOf(address(curvePool)).mul(inAmount)).div(totalBalance); } balances = _balances; } function getVirtualPrice() external view override returns (uint256) { return curvePool.get_virtual_price(); } // Internal functions function _lpToUsd(uint256 inAmount) internal view returns (uint256) { return inAmount.mul(curvePool.get_virtual_price()).div(DEFAULT_DECIMALS_FACTOR); } function _stableToUsd(uint256[N_COINS] memory tokenAmounts, bool deposit) internal view returns (uint256) { uint256 lpAmount = curvePool.calc_token_amount(tokenAmounts, deposit); return _lpToUsd(lpAmount); } function _stableToLp(uint256[N_COINS] memory tokenAmounts, bool deposit) internal view returns (uint256) { return curvePool.calc_token_amount(tokenAmounts, deposit); } function _singleStableFromLp(uint256 inAmount, int128 i) internal view returns (uint256) { if (inAmount == 0) { return 0; } return curvePool.calc_withdraw_one_coin(inAmount, i); } /// @notice Convert USD amount to LP tokens function _usdToLp(uint256 inAmount) internal view returns (uint256) { return inAmount.mul(DEFAULT_DECIMALS_FACTOR).div(curvePool.get_virtual_price()); } /// @notice Calculate price ratios for stablecoins /// Get USD price data for stablecoin /// @param i Stablecoin to get USD price for function getPriceFeed(uint256 i) external view override returns (uint256) { int256 _price; (, _price, , ,) = AggregatorV3Interface(getAggregator(i)).latestRoundData(); return uint256(_price); } /// @notice Fetch chainlink token ratios /// @param i Token in function getTokenRatios(uint256 i) private view returns (uint256[N_COINS] memory _ratios) { int256[N_COINS] memory _prices; (,_prices[0], , ,) = AggregatorV3Interface(getAggregator(0)).latestRoundData(); (,_prices[1], , ,) = AggregatorV3Interface(getAggregator(1)).latestRoundData(); (,_prices[2], , ,) = AggregatorV3Interface(getAggregator(2)).latestRoundData(); _ratios[0] = uint256(_prices[0]).mul(CHAINLINK_PRICE_DECIMAL_FACTOR).div(uint256(_prices[1])); _ratios[1] = uint256(_prices[0]).mul(CHAINLINK_PRICE_DECIMAL_FACTOR).div(uint256(_prices[2])); _ratios[2] = uint256(_prices[2]).mul(CHAINLINK_PRICE_DECIMAL_FACTOR).div(uint256(_prices[1])); return _ratios; } function getAggregator(uint256 index) private view returns (address) { require(index < N_COINS, 'getAggregator: !index < N_COINS'); if (index == 0) { return daiUsdAgg; } else if (index == 1) { return usdcUsdAgg; } else { return usdtUsdAgg; } } /// @notice Get absolute value function abs(int256 x) private pure returns (uint256) { return x >= 0 ? uint256(x) : uint256(-x); } function _updateRatios(uint256 tolerance) private returns (bool) { uint256[N_COINS] memory chainRatios = getTokenRatios(0); uint256[N_COINS] memory newRatios; uint256 _ratio; uint256 check; for (uint256 i = 1; i < N_COINS; i++) { _ratio = curvePool.get_dy(int128(0), int128(i), getDecimal(0)); check = abs(int256(_ratio) - int256(chainRatios[i - 1].div(CHAIN_FACTOR))); if (check > tolerance) { return false; } else { newRatios[i - 1] = _ratio; } } _ratio = curvePool.get_dy(int128(2), int128(1), getDecimal(1)); check = abs(int256(_ratio) - int256(chainRatios[2]/CHAIN_FACTOR)); if (check > tolerance) { return false; } newRatios[N_COINS - 1] = _ratio; for (uint256 i; i < N_COINS; i++) { lastRatio[i] = newRatios[i]; } emit LogNewRatios(newRatios); return true; } }
@notice Get LP token value of input amount of single token
function singleStableFromUsd(uint256 inAmount, int128 i) external view override returns (uint256) { return _singleStableFromLp(_usdToLp(inAmount), i); }
5,901,486
[ 1, 967, 511, 52, 1147, 460, 434, 810, 3844, 434, 2202, 1147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2202, 30915, 1265, 3477, 72, 12, 11890, 5034, 316, 6275, 16, 509, 10392, 277, 13, 3903, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 7526, 30915, 1265, 48, 84, 24899, 407, 72, 774, 48, 84, 12, 267, 6275, 3631, 277, 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 ]
pragma solidity ^0.4.15; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; if (a != 0 && c / a != b) revert(); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { if (b > a) revert(); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; if (c < a) revert(); return c; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant 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 constant 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)); // 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 constant 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)) 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)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); 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 constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @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() { 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)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title IRBTokens * @dev IRB Token contract based on Zeppelin StandardToken contract */ contract IRBToken is StandardToken, Ownable { using SafeMath for uint256; /** * @dev ERC20 descriptor variables */ string public constant name = "IRB Tokens"; string public constant symbol = "IRB"; uint8 public decimals = 18; /** * @dev 489.58 millions s the initial Token sale */ uint256 public constant crowdsaleTokens = 489580 * 10 ** 21; /** * @dev 10.42 millions is the initial Token presale */ uint256 public constant preCrowdsaleTokens = 10420 * 10 ** 21; // TODO: TestRPC addresses, replace to real // PRE Crowdsale Tokens Wallet address public constant preCrowdsaleTokensWallet = 0x0CD95a59fAd089c4EBCCEB54f335eC8f61Caa80e; // Crowdsale Tokens Wallet address public constant crowdsaleTokensWallet = 0x48545E41696Dc51020C35cA8C36b678101a98437; /** * @dev Address of PRE Crowdsale contract which will be compared * against in the appropriate modifier check */ address public preCrowdsaleContractAddress; /** * @dev Address of Crowdsale contract which will be compared * against in the appropriate modifier check */ address public crowdsaleContractAddress; /** * @dev variable that holds flag of ended pre tokensake */ bool isPreFinished = false; /** * @dev variable that holds flag of ended tokensake */ bool isFinished = false; /** * @dev Modifier that allow only the Crowdsale contract to be sender */ modifier onlyPreCrowdsaleContract() { require(msg.sender == preCrowdsaleContractAddress); _; } /** * @dev Modifier that allow only the Crowdsale contract to be sender */ modifier onlyCrowdsaleContract() { require(msg.sender == crowdsaleContractAddress); _; } /** * @dev event for the burnt tokens after crowdsale logging * @param tokens amount of tokens available for crowdsale */ event TokensBurnt(uint256 tokens); /** * @dev event for the tokens contract move to the active state logging * @param supply amount of tokens left after all the unsold was burned */ event Live(uint256 supply); /** * @dev Contract constructor */ function IRBToken() { // Issue pre crowdsale tokens balances[preCrowdsaleTokensWallet] = balanceOf(preCrowdsaleTokensWallet).add(preCrowdsaleTokens); Transfer(address(0), preCrowdsaleTokensWallet, preCrowdsaleTokens); // Issue crowdsale tokens balances[crowdsaleTokensWallet] = balanceOf(crowdsaleTokensWallet).add(crowdsaleTokens); Transfer(address(0), crowdsaleTokensWallet, crowdsaleTokens); // 500 millions tokens overall totalSupply = crowdsaleTokens.add(preCrowdsaleTokens); } /** * @dev back link IRBToken contract with IRBPreCrowdsale one * @param _preCrowdsaleAddress non zero address of IRBPreCrowdsale contract */ function setPreCrowdsaleAddress(address _preCrowdsaleAddress) onlyOwner external { require(_preCrowdsaleAddress != address(0)); preCrowdsaleContractAddress = _preCrowdsaleAddress; // Allow pre crowdsale contract uint256 balance = balanceOf(preCrowdsaleTokensWallet); allowed[preCrowdsaleTokensWallet][preCrowdsaleContractAddress] = balance; Approval(preCrowdsaleTokensWallet, preCrowdsaleContractAddress, balance); } /** * @dev back link IRBToken contract with IRBCrowdsale one * @param _crowdsaleAddress non zero address of IRBCrowdsale contract */ function setCrowdsaleAddress(address _crowdsaleAddress) onlyOwner external { require(isPreFinished); require(_crowdsaleAddress != address(0)); crowdsaleContractAddress = _crowdsaleAddress; // Allow crowdsale contract uint256 balance = balanceOf(crowdsaleTokensWallet); allowed[crowdsaleTokensWallet][crowdsaleContractAddress] = balance; Approval(crowdsaleTokensWallet, crowdsaleContractAddress, balance); } /** * @dev called only by linked IRBPreCrowdsale contract to end precrowdsale. */ function endPreTokensale() onlyPreCrowdsaleContract external { require(!isPreFinished); uint256 preCrowdsaleLeftovers = balanceOf(preCrowdsaleTokensWallet); if (preCrowdsaleLeftovers > 0) { balances[preCrowdsaleTokensWallet] = 0; balances[crowdsaleTokensWallet] = balances[crowdsaleTokensWallet].add(preCrowdsaleLeftovers); Transfer(preCrowdsaleTokensWallet, crowdsaleTokensWallet, preCrowdsaleLeftovers); } isPreFinished = true; } /** * @dev called only by linked IRBCrowdsale contract to end crowdsale. */ function endTokensale() onlyCrowdsaleContract external { require(!isFinished); uint256 crowdsaleLeftovers = balanceOf(crowdsaleTokensWallet); if (crowdsaleLeftovers > 0) { totalSupply = totalSupply.sub(crowdsaleLeftovers); balances[crowdsaleTokensWallet] = 0; Transfer(crowdsaleTokensWallet, address(0), crowdsaleLeftovers); TokensBurnt(crowdsaleLeftovers); } isFinished = true; Live(totalSupply); } } /** * @title RefundVault. * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract IRBPreRefundVault is Ownable { using SafeMath for uint256; enum State {Active, Refunding, Closed} State public state; mapping (address => uint256) public deposited; uint256 public totalDeposited; address public constant wallet = 0x26dB9eF39Bbfe437f5b384c3913E807e5633E7cE; address preCrowdsaleContractAddress; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); event Withdrawal(address indexed receiver, uint256 weiAmount); function IRBPreRefundVault() { state = State.Active; } modifier onlyCrowdsaleContract() { require(msg.sender == preCrowdsaleContractAddress); _; } function setPreCrowdsaleAddress(address _preCrowdsaleAddress) external onlyOwner { require(_preCrowdsaleAddress != address(0)); preCrowdsaleContractAddress = _preCrowdsaleAddress; } function deposit(address investor) onlyCrowdsaleContract external payable { require(state == State.Active); uint256 amount = msg.value; deposited[investor] = deposited[investor].add(amount); totalDeposited = totalDeposited.add(amount); } function close() onlyCrowdsaleContract external { require(state == State.Active); state = State.Closed; totalDeposited = 0; Closed(); wallet.transfer(this.balance); } function enableRefunds() onlyCrowdsaleContract external { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } /** * @dev withdraw method that can be used by crowdsale contract's owner * for the withdrawal funds to the owner */ function withdraw(uint value) onlyCrowdsaleContract external returns (bool success) { require(state == State.Active); require(totalDeposited >= value); totalDeposited = totalDeposited.sub(value); wallet.transfer(value); Withdrawal(wallet, value); return true; } /** * @dev killer method that can be used by owner to * kill the contract and send funds to owner */ function kill() onlyOwner { require(state == State.Closed); selfdestruct(owner); } } /** * @title IRBPreCrowdsale * @dev IRB pre crowdsale contract borrows Zeppelin Finalized, Capped and Refundable crowdsales implementations */ contract IRBPreCrowdsale is Ownable, Pausable { using SafeMath for uint; /** * @dev token contract */ IRBToken public token; /** * @dev refund vault used to hold funds while crowdsale is running */ IRBPreRefundVault public vault; /** * @dev tokensale(presale) start time: Dec 12, 2017, 11:00:00 + 3 */ uint startTime = 1513065600; /** * @dev tokensale end time: Jan 14, 2018 23:59:59 +3 */ uint endTime = 1515963599; /** * @dev minimum purchase amount for presale */ uint256 public constant minPresaleAmount = 108 * 10 ** 15; // 400 IRB /** * @dev minimum and maximum amount of funds to be raised in weis */ uint256 public constant goal = 1125 * 10 ** 18; // 1.125 Kether uint256 public constant cap = 2250 * 10 ** 18; // 2.25 Kether /** * @dev amount of raised money in wei */ uint256 public weiRaised; /** * @dev tokensale finalization flag */ bool public isFinalized = false; /** * @dev event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @dev event for tokensale final logging */ event Finalized(); /** * @dev Pre Crowdsale in the constructor takes addresses of * the just deployed IRBToken and IRBPreRefundVault contracts * @param _tokenAddress address of the IRBToken deployed contract * @param _vaultAddress address of the IRBPreRefundVault deployed contract */ function IRBPreCrowdsale(address _tokenAddress, address _vaultAddress) { require(_tokenAddress != address(0)); require(_vaultAddress != address(0)); // IRBToken and IRBPreRefundVault was deployed separately token = IRBToken(_tokenAddress); vault = IRBPreRefundVault(_vaultAddress); } /** * @dev fallback function can be used to buy tokens */ function() payable { buyTokens(msg.sender); } /** * @dev main function to buy tokens * @param beneficiary target wallet for tokens can vary from the sender one */ function buyTokens(address beneficiary) whenNotPaused public payable { require(beneficiary != address(0)); require(validPurchase(msg.value)); uint256 weiAmount = msg.value; // buyer and beneficiary could be two different wallets address buyer = msg.sender; // calculate token amount to be created uint256 tokens = convertAmountToTokens(weiAmount); weiRaised = weiRaised.add(weiAmount); if (!token.transferFrom(token.preCrowdsaleTokensWallet(), beneficiary, tokens)) { revert(); } TokenPurchase(buyer, beneficiary, weiAmount, tokens); vault.deposit.value(weiAmount)(buyer); } /** * @dev check if the current purchase valid based on time and amount of passed ether * @param _value amount of passed ether * @return true if investors can buy at the moment */ function validPurchase(uint256 _value) internal constant returns (bool) { bool nonZeroPurchase = _value != 0; bool withinPeriod = now >= startTime && now <= endTime; bool withinCap = weiRaised.add(_value) <= cap; // For presale we want to decline all payments less then minPresaleAmount bool withinAmount = msg.value >= minPresaleAmount; return nonZeroPurchase && withinPeriod && withinCap && withinAmount; } /** * @dev check if crowdsale still active based on current time and cap * consider minPresaleAmount * @return true if crowdsale event has ended */ function hasEnded() public constant returns (bool) { bool capReached = weiRaised.add(minPresaleAmount) >= cap; bool timeIsUp = now > endTime; return timeIsUp || capReached; } /** * @dev if crowdsale is unsuccessful, investors can claim refunds here */ function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } /** * @dev finalize crowdsale. this method triggers vault and token finalization */ function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); // trigger vault and token finalization if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } token.endPreTokensale(); isFinalized = true; Finalized(); } /** * @dev check if hard cap goal is reached */ function goalReached() public constant returns (bool) { return weiRaised >= goal; } /** * @dev withdraw method that can be used by owner for * withdraw funds from vault to owner */ function withdraw(uint256 amount) onlyOwner public { require(!isFinalized); require(goalReached()); require(amount > 0); vault.withdraw(amount); } /** * @dev returns current token price */ function convertAmountToTokens(uint256 amount) public constant returns (uint256) { // 1 token = 0.00027 ETH uint256 tokens = amount.div(27).mul(100000); // bonus +25% uint256 bonus = tokens.div(4); return tokens.add(bonus); } /** * @dev killer method that can bu used by owner to * kill the contract and send funds to owner */ function kill() onlyOwner whenPaused { selfdestruct(owner); } }
* @dev returns current token price/ 1 token = 0.00027 ETH bonus +25%
function convertAmountToTokens(uint256 amount) public constant returns (uint256) { uint256 tokens = amount.div(27).mul(100000); uint256 bonus = tokens.div(4); return tokens.add(bonus); }
13,031,485
[ 1, 6154, 783, 1147, 6205, 19, 404, 1147, 273, 374, 18, 17954, 27, 512, 2455, 324, 22889, 397, 2947, 9, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1765, 6275, 774, 5157, 12, 11890, 5034, 3844, 13, 1071, 5381, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 2430, 273, 3844, 18, 2892, 12, 5324, 2934, 16411, 12, 21, 11706, 1769, 203, 3639, 2254, 5034, 324, 22889, 273, 2430, 18, 2892, 12, 24, 1769, 203, 203, 3639, 327, 2430, 18, 1289, 12, 18688, 407, 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 ]
./full_match/1/0x2c75A27616117C680AD289590D278C8294fCFE9e/sources/contracts/PolygonZkEVM.sol
* @param initializePackedParameters Struct to save gas and avoid stack too deep errors @param genesisRoot Rollup genesis root @param _trustedSequencerURL Trusted sequencer URL @param _networkName L2 network name/ Check initialize parameters
function initialize( InitializePackedParameters calldata initializePackedParameters, bytes32 genesisRoot, string memory _trustedSequencerURL, string memory _networkName, string calldata _version ) external initializer { admin = initializePackedParameters.admin; trustedSequencer = initializePackedParameters.trustedSequencer; trustedAggregator = initializePackedParameters.trustedAggregator; batchNumToStateRoot[0] = genesisRoot; trustedSequencerURL = _trustedSequencerURL; networkName = _networkName; if ( initializePackedParameters.pendingStateTimeout > _HALT_AGGREGATION_TIMEOUT ) { revert PendingStateTimeoutExceedHaltAggregationTimeout(); } pendingStateTimeout = initializePackedParameters.pendingStateTimeout; if ( initializePackedParameters.trustedAggregatorTimeout > _HALT_AGGREGATION_TIMEOUT ) { revert TrustedAggregatorTimeoutExceedHaltAggregationTimeout(); } trustedAggregatorTimeout = initializePackedParameters .trustedAggregatorTimeout; multiplierBatchFee = 1002; forceBatchTimeout = 5 days; isForcedBatchDisallowed = true; }
4,995,492
[ 1, 11160, 4420, 329, 2402, 7362, 358, 1923, 16189, 471, 4543, 2110, 4885, 4608, 1334, 225, 21906, 2375, 31291, 416, 21906, 1365, 225, 389, 25247, 1761, 372, 23568, 1785, 30645, 26401, 23568, 1976, 225, 389, 5185, 461, 511, 22, 2483, 508, 19, 2073, 4046, 1472, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4046, 12, 203, 3639, 9190, 4420, 329, 2402, 745, 892, 4046, 4420, 329, 2402, 16, 203, 3639, 1731, 1578, 21906, 2375, 16, 203, 3639, 533, 3778, 389, 25247, 1761, 372, 23568, 1785, 16, 203, 3639, 533, 3778, 389, 5185, 461, 16, 203, 3639, 533, 745, 892, 389, 1589, 203, 565, 262, 3903, 12562, 288, 203, 3639, 3981, 273, 4046, 4420, 329, 2402, 18, 3666, 31, 203, 3639, 13179, 1761, 372, 23568, 273, 4046, 4420, 329, 2402, 18, 25247, 1761, 372, 23568, 31, 203, 3639, 13179, 17711, 273, 4046, 4420, 329, 2402, 18, 25247, 17711, 31, 203, 3639, 2581, 2578, 774, 1119, 2375, 63, 20, 65, 273, 21906, 2375, 31, 203, 3639, 13179, 1761, 372, 23568, 1785, 273, 389, 25247, 1761, 372, 23568, 1785, 31, 203, 3639, 2483, 461, 273, 389, 5185, 461, 31, 203, 203, 3639, 309, 261, 203, 5411, 4046, 4420, 329, 2402, 18, 9561, 1119, 2694, 405, 203, 5411, 389, 44, 18255, 67, 1781, 43, 5937, 2689, 67, 9503, 203, 3639, 262, 288, 203, 5411, 15226, 16034, 1119, 2694, 424, 5288, 27034, 12089, 2694, 5621, 203, 3639, 289, 203, 3639, 4634, 1119, 2694, 273, 4046, 4420, 329, 2402, 18, 9561, 1119, 2694, 31, 203, 203, 3639, 309, 261, 203, 5411, 4046, 4420, 329, 2402, 18, 25247, 17711, 2694, 405, 203, 5411, 389, 44, 18255, 67, 1781, 43, 5937, 2689, 67, 9503, 203, 3639, 262, 288, 203, 5411, 15226, 30645, 17711, 2694, 424, 5288, 27034, 12089, 2694, 5621, 203, 3639, 289, 203, 203, 3639, 13179, 17711, 2694, 273, 4046, 4420, 329, 2 ]
pragma solidity 0.5.17; import "./BondedECDSAKeep.sol"; import "./KeepBonding.sol"; import "./api/IBondedECDSAKeepFactory.sol"; import "./CloneFactory.sol"; import "@keep-network/sortition-pools/contracts/api/IStaking.sol"; import "@keep-network/sortition-pools/contracts/api/IBonding.sol"; import "@keep-network/sortition-pools/contracts/BondedSortitionPool.sol"; import "@keep-network/sortition-pools/contracts/BondedSortitionPoolFactory.sol"; import { AuthorityDelegator, TokenStaking } from "@keep-network/keep-core/contracts/TokenStaking.sol"; import "@keep-network/keep-core/contracts/IRandomBeacon.sol"; import "@keep-network/keep-core/contracts/utils/AddressArrayUtils.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /// @title Bonded ECDSA Keep Factory /// @notice Contract creating bonded ECDSA keeps. /// @dev We avoid redeployment of bonded ECDSA keep contract by using the clone factory. /// Proxy delegates calls to sortition pool and therefore does not affect contract's /// state. This means that we only need to deploy the bonded ECDSA keep contract /// once. The factory provides clean state for every new bonded ECDSA keep clone. contract BondedECDSAKeepFactory is IBondedECDSAKeepFactory, CloneFactory, AuthorityDelegator, IRandomBeaconConsumer { using AddressArrayUtils for address[]; using SafeMath for uint256; // Notification that a new sortition pool has been created. event SortitionPoolCreated( address indexed application, address sortitionPool ); // Notification that a new keep has been created. event BondedECDSAKeepCreated( address indexed keepAddress, address[] members, address indexed owner, address indexed application, uint256 honestThreshold ); // Holds the address of the bonded ECDSA keep contract that will be used as a // master contract for cloning. address public masterBondedECDSAKeepAddress; // Keeps created by this factory. address[] public keeps; // Maps keep opened timestamp to each keep address mapping(address => uint256) keepOpenedTimestamp; // Mapping of pools with registered member candidates for each application. mapping(address => address) candidatesPools; // application -> candidates pool uint256 public groupSelectionSeed; BondedSortitionPoolFactory sortitionPoolFactory; TokenStaking tokenStaking; KeepBonding keepBonding; IRandomBeacon randomBeacon; // Sortition pool is created with a minimum bond of 1 to avoid // griefing. // // Anyone can create a sortition pool for an application. If a pool is // created with a ridiculously high bond, nobody can join it and // updating bond is not possible because trying to select a group // with an empty pool reverts. // // We set the minimum bond value to 1 to prevent from this situation and // to allow the pool adjust the minimum bond during the first signer // selection. uint256 public constant minimumBond = 1; // Signer candidates in bonded sortition pool are weighted by their eligible // stake divided by a constant divisor. The divisor is set to 1 KEEP so that // all KEEPs in eligible stake matter when calculating operator's eligible // weight for signer selection. uint256 public constant poolStakeWeightDivisor = 1e18; // Gas required for a callback from the random beacon. The value specifies // gas required to call `__beaconCallback` function in the worst-case // scenario with all the checks and maximum allowed uint256 relay entry as // a callback parameter. uint256 public constant callbackGas = 30000; // Random beacon sends back callback surplus to the requestor. It may also // decide to send additional request subsidy fee. What's more, it may happen // that the beacon is busy and we will not refresh group selection seed from // the beacon. We accumulate all funds received from the beacon in the // reseed pool and later use this pool to reseed using a public reseed // function on a manual request at any moment. uint256 public reseedPool; constructor( address _masterBondedECDSAKeepAddress, address _sortitionPoolFactory, address _tokenStaking, address _keepBonding, address _randomBeacon ) public { masterBondedECDSAKeepAddress = _masterBondedECDSAKeepAddress; sortitionPoolFactory = BondedSortitionPoolFactory( _sortitionPoolFactory ); tokenStaking = TokenStaking(_tokenStaking); keepBonding = KeepBonding(_keepBonding); randomBeacon = IRandomBeacon(_randomBeacon); // initial value before the random beacon updates the seed // https://www.wolframalpha.com/input/?i=pi+to+78+digits groupSelectionSeed = 31415926535897932384626433832795028841971693993751058209749445923078164062862; } /// @notice Adds any received funds to the factory reseed pool. function() external payable { reseedPool += msg.value; } /// @notice Creates new sortition pool for the application. /// @dev Emits an event after sortition pool creation. /// @param _application Address of the application. /// @return Address of the created sortition pool contract. function createSortitionPool(address _application) external returns (address) { require( candidatesPools[_application] == address(0), "Sortition pool already exists" ); address sortitionPoolAddress = sortitionPoolFactory.createSortitionPool( IStaking(address(tokenStaking)), IBonding(address(keepBonding)), tokenStaking.minimumStake(), minimumBond, poolStakeWeightDivisor ); candidatesPools[_application] = sortitionPoolAddress; emit SortitionPoolCreated(_application, sortitionPoolAddress); return candidatesPools[_application]; } /// @notice Gets the sortition pool address for the given application. /// @dev Reverts if sortition does not exits for the application. /// @param _application Address of the application. /// @return Address of the sortition pool contract. function getSortitionPool(address _application) external view returns (address) { require( candidatesPools[_application] != address(0), "No pool found for the application" ); return candidatesPools[_application]; } /// @notice Register caller as a candidate to be selected as keep member /// for the provided customer application. /// @dev If caller is already registered it returns without any changes. /// @param _application Address of the application. function registerMemberCandidate(address _application) external { require( candidatesPools[_application] != address(0), "No pool found for the application" ); BondedSortitionPool candidatesPool = BondedSortitionPool( candidatesPools[_application] ); address operator = msg.sender; if (!candidatesPool.isOperatorInPool(operator)) { candidatesPool.joinPool(operator); } } /// @notice Checks if operator's details in the member candidates pool are /// up to date for the given application. If not update operator status /// function should be called by the one who is monitoring the status. /// @param _operator Operator's address. /// @param _application Customer application address. function isOperatorUpToDate(address _operator, address _application) external view returns (bool) { BondedSortitionPool candidatesPool = getSortitionPoolForOperator( _operator, _application ); return candidatesPool.isOperatorUpToDate(_operator); } /// @notice Invokes update of operator's details in the member candidates pool /// for the given application /// @param _operator Operator's address. /// @param _application Customer application address. function updateOperatorStatus(address _operator, address _application) external { BondedSortitionPool candidatesPool = getSortitionPoolForOperator( _operator, _application ); candidatesPool.updateOperatorStatus(_operator); } /// @notice Opens a new ECDSA keep. /// @dev Selects a list of signers for the keep based on provided parameters. /// A caller of this function is expected to be an application for which /// member candidates were registered in a pool. /// @param _groupSize Number of signers in the keep. /// @param _honestThreshold Minimum number of honest keep signers. /// @param _owner Address of the keep owner. /// @param _bond Value of ETH bond required from the keep in wei. /// @param _stakeLockDuration Stake lock duration in seconds. /// @return Created keep address. function openKeep( uint256 _groupSize, uint256 _honestThreshold, address _owner, uint256 _bond, uint256 _stakeLockDuration ) external payable returns (address keepAddress) { require(_groupSize > 0, "Minimum signing group size is 1"); require(_groupSize <= 16, "Maximum signing group size is 16"); require( _honestThreshold > 0, "Honest threshold must be greater than 0" ); require( _honestThreshold <= _groupSize, "Honest threshold must be less or equal the group size" ); address application = msg.sender; address pool = candidatesPools[application]; require(pool != address(0), "No signer pool for this application"); // In Solidity, division rounds towards zero (down) and dividing // '_bond' by '_groupSize' can leave a remainder. Even though, a remainder // is very small, we want to avoid this from happening and memberBond is // rounded up by: `(bond + groupSize - 1 ) / groupSize` // Ex. (100 + 3 - 1) / 3 = 34 uint256 memberBond = (_bond.add(_groupSize).sub(1)).div(_groupSize); require(memberBond > 0, "Bond per member must be greater than zero"); require( msg.value >= openKeepFeeEstimate(), "Insufficient payment for opening a new keep" ); uint256 minimumStake = tokenStaking.minimumStake(); address[] memory members = BondedSortitionPool(pool).selectSetGroup( _groupSize, bytes32(groupSelectionSeed), minimumStake, memberBond ); newGroupSelectionSeed(); keepAddress = createClone(masterBondedECDSAKeepAddress); BondedECDSAKeep keep = BondedECDSAKeep(keepAddress); // keepOpenedTimestamp value for newly created keep is required to be set // before calling `keep.initialize` function as it is used to determine // token staking delegation authority recognition in `__isRecognized` // function. /* solium-disable-next-line security/no-block-members*/ keepOpenedTimestamp[address(keep)] = block.timestamp; keep.initialize( _owner, members, _honestThreshold, minimumStake, _stakeLockDuration, address(tokenStaking), address(keepBonding), address(this) ); for (uint256 i = 0; i < _groupSize; i++) { keepBonding.createBond( members[i], keepAddress, uint256(keepAddress), memberBond, pool ); } keeps.push(address(keep)); emit BondedECDSAKeepCreated( keepAddress, members, _owner, application, _honestThreshold ); } /// @notice Gets how many keeps have been opened by this contract. /// @dev Checks the size of the keeps array. /// @return The number of keeps opened so far. function getKeepCount() external view returns (uint256) { return keeps.length; } /// @notice Gets a specific keep address at a given index. /// @return The address of the keep at the given index. function getKeepAtIndex(uint256 index) external view returns (address) { require(index < keeps.length, "Out of bounds."); return keeps[index]; } /// @notice Gets the opened timestamp of the given keep. /// @return Timestamp the given keep was opened at or 0 if this keep /// was not created by this factory. function getKeepOpenedTimestamp(address _keep) external view returns (uint256) { return keepOpenedTimestamp[_keep]; } /// @notice Verifies if delegates authority recipient is valid address recognized /// by the factory for token staking authority delegation. /// @param _delegatedAuthorityRecipient Address of the delegated authority /// recipient. /// @return True if provided address is recognized delegated token staking /// authority for this factory contract. function __isRecognized(address _delegatedAuthorityRecipient) external returns (bool) { return keepOpenedTimestamp[_delegatedAuthorityRecipient] > 0; } /// @notice Sets a new group selection seed value. /// @dev The function is expected to be called in a callback by the random /// beacon. /// @param _relayEntry Beacon output. function __beaconCallback(uint256 _relayEntry) external onlyRandomBeacon { groupSelectionSeed = _relayEntry; } /// @notice Checks if operator is registered as a candidate for the given /// customer application. /// @param _operator Operator's address. /// @param _application Customer application address. /// @return True if operator is already registered in the candidates pool, /// false otherwise. function isOperatorRegistered(address _operator, address _application) public view returns (bool) { if (candidatesPools[_application] == address(0)) { return false; } BondedSortitionPool candidatesPool = BondedSortitionPool( candidatesPools[_application] ); return candidatesPool.isOperatorRegistered(_operator); } /// @notice Checks if given operator is eligible for the given application. /// @param _operator Operator's address. /// @param _application Customer application address. function isOperatorEligible(address _operator, address _application) public view returns (bool) { if (candidatesPools[_application] == address(0)) { return false; } BondedSortitionPool candidatesPool = BondedSortitionPool( candidatesPools[_application] ); return candidatesPool.isOperatorEligible(_operator); } /// @notice Gets a fee estimate for opening a new keep. /// @return Uint256 estimate. function openKeepFeeEstimate() public view returns (uint256) { return randomBeacon.entryFeeEstimate(callbackGas); } /// @notice Calculates the fee requestor has to pay to reseed the factory /// for signer selection. Depending on how much value is stored in the /// reseed pool and the price of a new relay entry, returned value may vary. function newGroupSelectionSeedFee() public view returns (uint256) { uint256 beaconFee = randomBeacon.entryFeeEstimate(callbackGas); return beaconFee <= reseedPool ? 0 : beaconFee.sub(reseedPool); } /// @notice Reseeds the value used for a signer selection. Requires enough /// payment to be passed. The required payment can be calculated using /// reseedFee function. Factory is automatically triggering reseeding after /// opening a new keep but the reseed can be also triggered at any moment /// using this function. function requestNewGroupSelectionSeed() public payable { uint256 beaconFee = randomBeacon.entryFeeEstimate(callbackGas); reseedPool = reseedPool.add(msg.value); require(reseedPool >= beaconFee, "Not enough funds to trigger reseed"); (bool success, bytes memory returnData) = requestRelayEntry(beaconFee); if (!success) { revert(string(returnData)); } reseedPool = reseedPool.sub(beaconFee); } /// @notice Checks if the specified account has enough active stake to become /// network operator and that this contract has been authorized for potential /// slashing. /// /// Having the required minimum of active stake makes the operator eligible /// to join the network. If the active stake is not currently undelegating, /// operator is also eligible for work selection. /// /// @param _operator operator's address /// @return True if has enough active stake to participate in the network, /// false otherwise. function hasMinimumStake(address _operator) public view returns (bool) { return tokenStaking.hasMinimumStake(_operator, address(this)); } /// @notice Checks if the factory has the authorization to operate on stake /// represented by the provided operator. /// /// @param _operator operator's address /// @return True if the factory has access to the staked token balance of /// the provided operator and can slash that stake. False otherwise. function isOperatorAuthorized(address _operator) public view returns (bool) { return tokenStaking.isAuthorizedForOperator(_operator, address(this)); } /// @notice Gets the stake balance of the specified operator. /// @param _operator The operator to query the balance of. /// @return An uint256 representing the amount staked by the passed operator. function balanceOf(address _operator) public view returns (uint256) { return tokenStaking.balanceOf(_operator); } /// @notice Gets the total weight of operators /// in the sortition pool for the given application. /// @dev Reverts if sortition does not exits for the application. /// @param _application Address of the application. /// @return The sum of all registered operators' weights in the pool. /// Reverts if sortition pool for the application does not exist. function getSortitionPoolWeight(address _application) public view returns (uint256) { address poolAddress = candidatesPools[_application]; require(poolAddress != address(0), "No pool found for the application"); return BondedSortitionPool(poolAddress).totalWeight(); } /// @notice Gets bonded sortition pool of specific application for the /// operator. /// @dev Reverts if the operator is not registered for the application. /// @param _operator Operator's address. /// @param _application Customer application address. /// @return Bonded sortition pool. function getSortitionPoolForOperator( address _operator, address _application ) internal view returns (BondedSortitionPool) { require( isOperatorRegistered(_operator, _application), "Operator not registered for the application" ); return BondedSortitionPool(candidatesPools[_application]); } /// @notice Updates group selection seed. /// @dev The main goal of this function is to request the random beacon to /// generate a new random number. The beacon generates the number asynchronously /// and will call a callback function when the number is ready. In the meantime /// we update current group selection seed to a new value using a hash function. /// In case of the random beacon request failure this function won't revert /// but add beacon payment to factory's reseed pool. function newGroupSelectionSeed() internal { // Calculate new group selection seed based on the current seed. // We added address of the factory as a key to calculate value different // than sortition pool RNG will, so we don't end up selecting almost // identical group. groupSelectionSeed = uint256( keccak256(abi.encodePacked(groupSelectionSeed, address(this))) ); // Call the random beacon to get a random group selection seed. (bool success, ) = requestRelayEntry(msg.value); if (!success) { reseedPool += msg.value; } } /// @notice Requests for a relay entry using the beacon payment provided as /// the parameter. function requestRelayEntry(uint256 payment) internal returns (bool, bytes memory) { return address(randomBeacon).call.value(payment)( abi.encodeWithSignature( "requestRelayEntry(address,uint256)", address(this), callbackGas ) ); } /// @notice Checks if the caller is the random beacon. /// @dev Throws an error if called by any account other than the random beacon. modifier onlyRandomBeacon() { require( address(randomBeacon) == msg.sender, "Caller is not the random beacon" ); _; } }
@notice Register caller as a candidate to be selected as keep member for the provided customer application. @dev If caller is already registered it returns without any changes. @param _application Address of the application.
function registerMemberCandidate(address _application) external { require( candidatesPools[_application] != address(0), "No pool found for the application" ); BondedSortitionPool candidatesPool = BondedSortitionPool( candidatesPools[_application] ); address operator = msg.sender; if (!candidatesPool.isOperatorInPool(operator)) { candidatesPool.joinPool(operator); } }
5,456,993
[ 1, 3996, 4894, 487, 279, 5500, 358, 506, 3170, 487, 3455, 3140, 364, 326, 2112, 6666, 2521, 18, 225, 971, 4894, 353, 1818, 4104, 518, 1135, 2887, 1281, 3478, 18, 225, 389, 3685, 5267, 434, 326, 2521, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 1744, 4419, 11910, 12, 2867, 389, 3685, 13, 3903, 288, 203, 3639, 2583, 12, 203, 5411, 7965, 16639, 63, 67, 3685, 65, 480, 1758, 12, 20, 3631, 203, 5411, 315, 2279, 2845, 1392, 364, 326, 2521, 6, 203, 3639, 11272, 203, 203, 3639, 605, 265, 785, 4416, 608, 2864, 7965, 2864, 273, 605, 265, 785, 4416, 608, 2864, 12, 203, 5411, 7965, 16639, 63, 67, 3685, 65, 203, 3639, 11272, 203, 203, 3639, 1758, 3726, 273, 1234, 18, 15330, 31, 203, 3639, 309, 16051, 21635, 2864, 18, 291, 5592, 382, 2864, 12, 9497, 3719, 288, 203, 5411, 7965, 2864, 18, 5701, 2864, 12, 9497, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xaE92F938E51b2F53e16fb8E2D69903B4112D5BCF/sources/contracts/SimpleStorage.sol
People(_favoriteNumber, name);
peoples[msg.sender] = People({name: _name, favoriteNumber: _favoriteNumber});
830,085
[ 1, 11227, 11763, 24899, 19731, 280, 1137, 1854, 16, 508, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 2804, 83, 6089, 63, 3576, 18, 15330, 65, 273, 19622, 11763, 12590, 529, 30, 389, 529, 16, 30705, 1854, 30, 389, 19731, 280, 1137, 1854, 22938, 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 ]
pragma solidity ^0.4.24; // File: contracts/library/SafeMath.sol /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ 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; } /** * @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) { 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); } } } // File: contracts/library/NameFilter.sol library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } // File: contracts/library/MSFun.sol /** @title -MSFun- v0.2.4 * ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐ * │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐ * ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘ * _____ _____ * (, / /) /) /) (, / /) /) * ┌─┐ / _ (/_ // // / _ // _ __ _(/ * ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_ * ┴ ┴ / / .-/ _____ (__ / * (__ / (_/ (, / /)™ * / __ __ __ __ _ __ __ _ _/_ _ _(/ * ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_ * ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018 * ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ * _ _ _ _ _ _ _ _ _ _ _ *=(_) _ _ (_)==========_(_)(_)(_)(_)_==========(_)(_)(_)(_)(_)================================* * (_)(_) (_)(_) (_) (_) (_) _ _ _ _ _ _ * (_) (_)_(_) (_) (_)_ _ _ _ (_) _ _ (_) (_) (_)(_)(_)(_)_ * (_) (_) (_) (_)(_)(_)(_)_ (_)(_)(_)(_) (_) (_) (_) * (_) (_) _ _ _ (_) _ _ (_) (_) (_) (_) (_) _ _ *=(_)=========(_)=(_)(_)==(_)_ _ _ _(_)=(_)(_)==(_)======(_)_ _ _(_)_ (_)========(_)=(_)(_)==* * (_) (_) (_)(_) (_)(_)(_)(_) (_)(_) (_) (_)(_)(_) (_)(_) (_) (_)(_) * * ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐ * ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │ * ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘ * * ┌──────────────────────────────────────────────────────────────────────┐ * │ MSFun, is an importable library that gives your contract the ability │ * │ add multiSig requirement to functions. │ * └──────────────────────────────────────────────────────────────────────┘ * ┌────────────────────┐ * │ Setup Instructions │ * └────────────────────┘ * (Step 1) import the library into your contract * * import "./MSFun.sol"; * * (Step 2) set up the signature data for msFun * * MSFun.Data private msData; * ┌────────────────────┐ * │ Usage Instructions │ * └────────────────────┘ * at the beginning of a function * * function functionName() * { * if (MSFun.multiSig(msData, required signatures, "functionName") == true) * { * MSFun.deleteProposal(msData, "functionName"); * * // put function body here * } * } * ┌────────────────────────────────┐ * │ Optional Wrappers For TeamJust │ * └────────────────────────────────┘ * multiSig wrapper function (cuts down on inputs, improves readability) * this wrapper is HIGHLY recommended * * function multiSig(bytes32 _whatFunction) private returns (bool) {return(MSFun.multiSig(msData, TeamJust.requiredSignatures(), _whatFunction));} * function multiSigDev(bytes32 _whatFunction) private returns (bool) {return(MSFun.multiSig(msData, TeamJust.requiredDevSignatures(), _whatFunction));} * * wrapper for delete proposal (makes code cleaner) * * function deleteProposal(bytes32 _whatFunction) private {MSFun.deleteProposal(msData, _whatFunction);} * ┌────────────────────────────┐ * │ Utility & Vanity Functions │ * └────────────────────────────┘ * delete any proposal is highly recommended. without it, if an admin calls a multiSig * function, with argument inputs that the other admins do not agree upon, the function * can never be executed until the undesirable arguments are approved. * * function deleteAnyProposal(bytes32 _whatFunction) onlyDevs() public {MSFun.deleteProposal(msData, _whatFunction);} * * for viewing who has signed a proposal & proposal data * * function checkData(bytes32 _whatFunction) onlyAdmins() public view returns(bytes32, uint256) {return(MSFun.checkMsgData(msData, _whatFunction), MSFun.checkCount(msData, _whatFunction));} * * lets you check address of up to 3 signers (address) * * function checkSignersByAddress(bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC) onlyAdmins() public view returns(address, address, address) {return(MSFun.checkSigner(msData, _whatFunction, _signerA), MSFun.checkSigner(msData, _whatFunction, _signerB), MSFun.checkSigner(msData, _whatFunction, _signerC));} * * same as above but will return names in string format. * * function checkSignersByName(bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC) onlyAdmins() public view returns(bytes32, bytes32, bytes32) {return(TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerA)), TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerB)), TeamJust.adminName(MSFun.checkSigner(msData, _whatFunction, _signerC)));} * ┌──────────────────────────┐ * │ Functions In Depth Guide │ * └──────────────────────────┘ * In the following examples, the Data is the proposal set for this library. And * the bytes32 is the name of the function. * * MSFun.multiSig(Data, uint256, bytes32) - Manages creating/updating multiSig * proposal for the function being called. The uint256 is the required * number of signatures needed before the multiSig will return true. * Upon first call, multiSig will create a proposal and store the arguments * passed with the function call as msgData. Any admins trying to sign the * function call will need to send the same argument values. Once required * number of signatures is reached this will return a bool of true. * * MSFun.deleteProposal(Data, bytes32) - once multiSig unlocks the function body, * you will want to delete the proposal data. This does that. * * MSFun.checkMsgData(Data, bytes32) - checks the message data for any given proposal * * MSFun.checkCount(Data, bytes32) - checks the number of admins that have signed * the proposal * * MSFun.checkSigners(data, bytes32, uint256) - checks the address of a given signer. * the uint256, is the log number of the signer (ie 1st signer, 2nd signer) */ library MSFun { //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // DATA SETS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // contact data setup struct Data { mapping (bytes32 => ProposalData) proposal_; } struct ProposalData { // a hash of msg.data bytes32 msgData; // number of signers uint256 count; // tracking of wither admins have signed mapping (address => bool) admin; // list of admins who have signed mapping (uint256 => address) log; } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // MULTI SIG FUNCTIONS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function multiSig(Data storage self, uint256 _requiredSignatures, bytes32 _whatFunction) internal returns(bool) { // our proposal key will be a hash of our function name + our contracts address // by adding our contracts address to this, we prevent anyone trying to circumvent // the proposal's security via external calls. bytes32 _whatProposal = whatProposal(_whatFunction); // this is just done to make the code more readable. grabs the signature count uint256 _currentCount = self.proposal_[_whatProposal].count; // store the address of the person sending the function call. we use msg.sender // here as a layer of security. in case someone imports our contract and tries to // circumvent function arguments. still though, our contract that imports this // library and calls multisig, needs to use onlyAdmin modifiers or anyone who // calls the function will be a signer. address _whichAdmin = msg.sender; // prepare our msg data. by storing this we are able to verify that all admins // are approving the same argument input to be executed for the function. we hash // it and store in bytes32 so its size is known and comparable bytes32 _msgData = keccak256(msg.data); // check to see if this is a new execution of this proposal or not if (_currentCount == 0) { // if it is, lets record the original signers data self.proposal_[_whatProposal].msgData = _msgData; // record original senders signature self.proposal_[_whatProposal].admin[_whichAdmin] = true; // update log (used to delete records later, and easy way to view signers) // also useful if the calling function wants to give something to a // specific signer. self.proposal_[_whatProposal].log[_currentCount] = _whichAdmin; // track number of signatures self.proposal_[_whatProposal].count += 1; // if we now have enough signatures to execute the function, lets // return a bool of true. we put this here in case the required signatures // is set to 1. if (self.proposal_[_whatProposal].count == _requiredSignatures) { return(true); } // if its not the first execution, lets make sure the msgData matches } else if (self.proposal_[_whatProposal].msgData == _msgData) { // msgData is a match // make sure admin hasnt already signed if (self.proposal_[_whatProposal].admin[_whichAdmin] == false) { // record their signature self.proposal_[_whatProposal].admin[_whichAdmin] = true; // update log (used to delete records later, and easy way to view signers) self.proposal_[_whatProposal].log[_currentCount] = _whichAdmin; // track number of signatures self.proposal_[_whatProposal].count += 1; } // if we now have enough signatures to execute the function, lets // return a bool of true. // we put this here for a few reasons. (1) in normal operation, if // that last recorded signature got us to our required signatures. we // need to return bool of true. (2) if we have a situation where the // required number of signatures was adjusted to at or lower than our current // signature count, by putting this here, an admin who has already signed, // can call the function again to make it return a true bool. but only if // they submit the correct msg data if (self.proposal_[_whatProposal].count == _requiredSignatures) { return(true); } } } // deletes proposal signature data after successfully executing a multiSig function function deleteProposal(Data storage self, bytes32 _whatFunction) internal { //done for readability sake bytes32 _whatProposal = whatProposal(_whatFunction); address _whichAdmin; //delete the admins votes & log. i know for loops are terrible. but we have to do this //for our data stored in mappings. simply deleting the proposal itself wouldn't accomplish this. for (uint256 i=0; i < self.proposal_[_whatProposal].count; i++) { _whichAdmin = self.proposal_[_whatProposal].log[i]; delete self.proposal_[_whatProposal].admin[_whichAdmin]; delete self.proposal_[_whatProposal].log[i]; } //delete the rest of the data in the record delete self.proposal_[_whatProposal]; } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // HELPER FUNCTIONS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function whatProposal(bytes32 _whatFunction) private view returns(bytes32) { return(keccak256(abi.encodePacked(_whatFunction,this))); } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // VANITY FUNCTIONS //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // returns a hashed version of msg.data sent by original signer for any given function function checkMsgData (Data storage self, bytes32 _whatFunction) internal view returns (bytes32 msg_data) { bytes32 _whatProposal = whatProposal(_whatFunction); return (self.proposal_[_whatProposal].msgData); } // returns number of signers for any given function function checkCount (Data storage self, bytes32 _whatFunction) internal view returns (uint256 signature_count) { bytes32 _whatProposal = whatProposal(_whatFunction); return (self.proposal_[_whatProposal].count); } // returns address of an admin who signed for any given function function checkSigner (Data storage self, bytes32 _whatFunction, uint256 _signer) internal view returns (address signer) { require(_signer > 0, "MSFun checkSigner failed - 0 not allowed"); bytes32 _whatProposal = whatProposal(_whatFunction); return (self.proposal_[_whatProposal].log[_signer - 1]); } } // File: contracts/interface/PlayerBookReceiverInterface.sol interface PlayerBookReceiverInterface { function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff, uint8 _level) external; function receivePlayerNameList(uint256 _pID, bytes32 _name) external; } // File: contracts/PlayerBook.sol /* * -PlayerBook - v-x * ______ _ ______ _ *====(_____ \=| |===============================(____ \===============| |=============* * _____) )| | _____ _ _ _____ ____ ____) ) ___ ___ | | _ * | ____/ | | (____ || | | || ___ | / ___) | __ ( / _ \ / _ \ | |_/ ) * | | | | / ___ || |_| || ____|| | | |__) )| |_| || |_| || _ ( *====|_|=======\_)\_____|=\__ ||_____)|_|======|______/==\___/==\___/=|_|=\_)=========* * (____/ * ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐ * ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ │ * ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘ */ contract PlayerBook { using NameFilter for string; using SafeMath for uint256; address private Community_Wallet1 = 0x00839c9d56F48E17d410E94309C91B9639D48242; address private Community_Wallet2 = 0x53bB6E7654155b8bdb5C4c6e41C9f47Cd8Ed1814; MSFun.Data private msData; function deleteProposal(bytes32 _whatFunction) private {MSFun.deleteProposal(msData, _whatFunction);} function deleteAnyProposal(bytes32 _whatFunction) onlyDevs() public {MSFun.deleteProposal(msData, _whatFunction);} function checkData(bytes32 _whatFunction) onlyDevs() public view returns(bytes32, uint256) {return(MSFun.checkMsgData(msData, _whatFunction), MSFun.checkCount(msData, _whatFunction));} function checkSignersByAddress(bytes32 _whatFunction, uint256 _signerA, uint256 _signerB, uint256 _signerC) onlyDevs() public view returns(address, address, address) {return(MSFun.checkSigner(msData, _whatFunction, _signerA), MSFun.checkSigner(msData, _whatFunction, _signerB), MSFun.checkSigner(msData, _whatFunction, _signerC));} //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . //=============================|================================================ uint256 public registrationFee_ = 10 finney; // price to register a name mapping(uint256 => PlayerBookReceiverInterface) public games_; // mapping of our game interfaces for sending your account info to games mapping(address => bytes32) public gameNames_; // lookup a games name mapping(address => uint256) public gameIDs_; // lokup a games ID uint256 public gID_; // total number of games 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 => Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amoungst any name you own) mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_; // (pID => nameNum => name) list of names a player owns struct Player { address addr; bytes32 name; uint256 laff; uint256 names; uint256 rreward; //for rank board uint256 cost; //everyone charges per round uint32 round; //rank round number for players uint8 level; } event eveSuperPlayer(bytes32 _name, uint256 _pid, address _addr, uint8 _level); event eveResolve(uint256 _startBlockNumber, uint32 _roundNumber); event eveUpdate(uint256 _pID, uint32 _roundNumber, uint256 _roundCost, uint256 _cost); event eveDeposit(address _from, uint256 _value, uint256 _balance ); event eveReward(uint256 _pID, uint256 _have, uint256 _reward, uint256 _vault, uint256 _allcost, uint256 _lastRefrralsVault ); event eveWithdraw(uint256 _pID, address _addr, uint256 _reward, uint256 _balance ); event eveSetAffID(uint256 _pID, address _addr, uint256 _laff, address _affAddr ); mapping (uint8 => uint256) public levelValue_; //for super player uint256[] public superPlayers_; //rank board data uint256[] public rankPlayers_; uint256[] public rankCost_; //the eth of refrerrals uint256 public referralsVault_; //the last rank round refrefrrals uint256 public lastRefrralsVault_; //time per round, the ethernum generate one block per 15 seconds, it will generate 24*60*60/15 blocks per 24h uint256 constant public roundBlockCount_ = 5760; //the start block numnber when the rank board had been activted for first time uint256 public startBlockNumber_; //rank top 10 uint8 constant public rankNumbers_ = 10; //current round number uint32 public roundNumber_; //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { levelValue_[3] = 0.003 ether; levelValue_[2] = 0.3 ether; levelValue_[1] = 1.5 ether; // premine the dev names (sorry not sorry) // No keys are purchased with this method, it's simply locking our addresses, // PID's and names for referral codes. pID_ = 0; rankPlayers_.length = rankNumbers_; rankCost_.length = rankNumbers_; roundNumber_ = 0; startBlockNumber_ = block.number; referralsVault_ = 0; lastRefrralsVault_ =0; addSuperPlayer(0x008d20ea31021bb4C93F3051aD7763523BBb0481,"main",1); addSuperPlayer(0x00De30E1A0E82750ea1f96f6D27e112f5c8A352D,"go",1); // addSuperPlayer(0x26042eb2f06D419093313ae2486fb40167Ba349C,"jack",1); addSuperPlayer(0x8d60d529c435e2A4c67FD233c49C3F174AfC72A8,"leon",1); addSuperPlayer(0xF9f24b9a5FcFf3542Ae3361c394AD951a8C0B3e1,"zuopiezi",1); addSuperPlayer(0x9ca974f2c49d68bd5958978e81151e6831290f57,"cowkeys",1); addSuperPlayer(0xf22978ed49631b68409a16afa8e123674115011e,"vulcan",1); addSuperPlayer(0x00b22a1D6CFF93831Cf2842993eFBB2181ad78de,"neo",1); // addSuperPlayer(0x10a04F6b13E95Bf8cC82187536b87A8646f1Bd9d,"mydream",1); // addSuperPlayer(0xce7aed496f69e2afdb99979952d9be8a38ad941d,"uking",1); addSuperPlayer(0x43fbedf2b2620ccfbd33d5c735b12066ff2fcdc1,"agg",1); } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } // only player with reward modifier onlyHaveReward() { require(myReward() > 0); _; } // check address modifier validAddress( address addr ) { require(addr != address(0x0)); _; } //devs check modifier onlyDevs(){ require( //msg.sender == 0x00D8E8CCb4A29625D299798036825f3fa349f2b4 ||//for test msg.sender == 0x00A32C09c8962AEc444ABde1991469eD0a9ccAf7 || msg.sender == 0x00aBBff93b10Ece374B14abb70c4e588BA1F799F, "only dev" ); _; } //level check modifier isLevel(uint8 _level) { require(_level >= 0 && _level <= 3, "invalid level"); require(msg.value >= levelValue_[_level], "sorry request price less than affiliate level"); _; } modifier isRegisteredGame() { require(gameIDs_[msg.sender] != 0); _; } //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); //============================================================================== // _ _ _|_ _ . // _\(/_ | |_||_) . //=============|================================================================ function addSuperPlayer(address _addr, bytes32 _name, uint8 _level) private { pID_++; plyr_[pID_].addr = _addr; plyr_[pID_].name = _name; plyr_[pID_].names = 1; plyr_[pID_].level = _level; pIDxAddr_[_addr] = pID_; pIDxName_[_name] = pID_; plyrNames_[pID_][_name] = true; plyrNameList_[pID_][1] = _name; superPlayers_.push(pID_); //fire event emit eveSuperPlayer(_name,pID_,_addr,_level); } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // BALANCE //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function balances() public view returns(uint256) { return (address(this).balance); } //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // DEPOSIT //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function deposit() validAddress(msg.sender) external payable returns (bool) { if(msg.value>0){ referralsVault_ += msg.value; emit eveDeposit(msg.sender, msg.value, address(this).balance); return true; } return false; } function updateRankBoard(uint256 _pID,uint256 _cost) isRegisteredGame() validAddress(msg.sender) external { uint256 _affID = plyr_[_pID].laff; if(_affID<=0){ return ; } if(_cost<=0){ return ; } //just for level 3 player if(plyr_[_affID].level != 3){ return ; } uint256 _affReward = _cost.mul(5)/100; //calc round charge if( plyr_[_affID].round == roundNumber_ ){ //same round plyr_[_affID].cost += _affReward; } else{ //diffrent round plyr_[_affID].cost = _affReward; plyr_[_affID].round = roundNumber_; } //check board players bool inBoard = false; for( uint8 i=0; i<rankNumbers_; i++ ){ if( _affID == rankPlayers_[i] ){ //update inBoard = true; rankCost_[i] = plyr_[_affID].cost; break; } } if( inBoard == false ){ //find the min charge player uint256 minCost = plyr_[_affID].cost; uint8 minIndex = rankNumbers_; for( uint8 k=0; k<rankNumbers_; k++){ if( rankCost_[k] < minCost){ minIndex = k; minCost = rankCost_[k]; } } if( minIndex != rankNumbers_ ){ //replace rankPlayers_[minIndex] = _affID; rankCost_[minIndex] = plyr_[_affID].cost; } } emit eveUpdate( _affID,roundNumber_,plyr_[_affID].cost,_cost); } // function resolveRankBoard() //isRegisteredGame() validAddress(msg.sender) external { uint256 deltaBlockCount = block.number - startBlockNumber_; if( deltaBlockCount < roundBlockCount_ ){ return; } //update start block number startBlockNumber_ = block.number; // emit eveResolve(startBlockNumber_,roundNumber_); roundNumber_++; //reward uint256 allCost = 0; for( uint8 k=0; k<rankNumbers_; k++){ allCost += rankCost_[k]; } if( allCost > 0 ){ uint256 reward = 0; uint256 roundVault = referralsVault_.sub(lastRefrralsVault_); for( uint8 m=0; m<rankNumbers_; m++){ uint256 pid = rankPlayers_[m]; if( pid>0 ){ reward = (roundVault.mul(8)/10).mul(rankCost_[m])/allCost; lastRefrralsVault_ += reward; plyr_[pid].rreward += reward; emit eveReward(rankPlayers_[m],plyr_[pid].rreward, reward,referralsVault_,allCost, lastRefrralsVault_); } } } //reset rank data rankPlayers_.length=0; rankCost_.length=0; rankPlayers_.length=10; rankCost_.length=10; } /** * Withdraws all of the callers earnings. */ function myReward() public view returns(uint256) { uint256 pid = pIDxAddr_[msg.sender]; return plyr_[pid].rreward; } function withdraw() onlyHaveReward() isHuman() public { address addr = msg.sender; uint256 pid = pIDxAddr_[addr]; uint256 reward = plyr_[pid].rreward; //reset plyr_[pid].rreward = 0; //get reward addr.transfer(reward); // fire event emit eveWithdraw(pIDxAddr_[addr], addr, reward, balances()); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= function checkIfNameValid(string _nameStr) public view returns(bool) { bytes32 _name = _nameStr.nameFilter(); if (pIDxName_[_name] == 0) return (true); else return (false); } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev registers a name. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who refered you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all, uint8 _level) isHuman() isLevel(_level) public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given, no new affiliate code was given, or the // player tried to use their own pID as an affiliate code, lolz if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID) { // update last affiliate plyr_[_pID].laff = _affCode; } else if (_affCode == _pID) { _affCode = 0; } // register name registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all, _level); } function registerNameXaddr(string _nameString, address _affCode, bool _all, uint8 _level) isHuman() isLevel(_level) public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all, _level); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all, uint8 _level) isHuman() isLevel(_level) public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != "" && _affCode != _name) { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all, _level); } /** * @dev players, if you registered a profile, before a game was released, or * set the all bool to false when you registered, use this function to push * your profile to a single game. also, if you've updated your name, you * can use this to push your name to games of your choosing. * -functionhash- 0x81c5b206 * @param _gameID game id */ function addMeToGame(uint256 _gameID) isHuman() public { require(_gameID <= gID_, "silly player, that game doesn't exist yet"); address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _totalNames = plyr_[_pID].names; // add players profile and most recent name games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff, 0); // add list of all names if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } /** * @dev players, use this to push your player profile to all registered games. * -functionhash- 0x0c6940ea */ function addMeToAllGames() isHuman() public { address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _laff = plyr_[_pID].laff; uint256 _totalNames = plyr_[_pID].names; bytes32 _name = plyr_[_pID].name; for (uint256 i = 1; i <= gID_; i++) { games_[i].receivePlayerInfo(_pID, _addr, _name, _laff, 0); if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } } /** * @dev players use this to change back to one of your old names. tip, you'll * still need to push that info to existing games. * -functionhash- 0xb9291296 * @param _nameString the name you want to use */ function useMyOldName(string _nameString) isHuman() public { // filter name, and get pID bytes32 _name = _nameString.nameFilter(); uint256 _pID = pIDxAddr_[msg.sender]; // make sure they own the name require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own"); // update their current name plyr_[_pID].name = _name; } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . //=====================_|======================================================= function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all, uint8 _level) private { // if names already has been used, require that current msg sender owns the name if( pIDxName_[_name] == _pID && _pID !=0 ){ //level up must keep old name! if (_level >= plyr_[_pID].level ) { require(plyrNames_[_pID][_name] == true, "sorry that names already taken"); } } else if (pIDxName_[_name] != 0){ require(plyrNames_[_pID][_name] == true, "sorry that names already taken"); } // add name to player profile, registry, and name book plyr_[_pID].name = _name; plyr_[_pID].level = _level; pIDxName_[_name] = _pID; if (plyrNames_[_pID][_name] == false) { plyrNames_[_pID][_name] = true; plyr_[_pID].names++; plyrNameList_[_pID][plyr_[_pID].names] = _name; } // registration fee goes directly to community rewards Community_Wallet1.transfer(msg.value / 2); Community_Wallet2.transfer(msg.value / 2); // push player info to games if (_all == true) for (uint256 i = 1; i <= gID_; i++) games_[i].receivePlayerInfo(_pID, _addr, _name, _affID, _level); // fire event emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== function determinePID(address _addr) private returns (bool) { if (pIDxAddr_[_addr] == 0) { pID_++; pIDxAddr_[_addr] = pID_; plyr_[pID_].addr = _addr; // set the new player bool to true return (true); } else { return (false); } } //============================================================================== // _ _|_ _ _ _ _ | _ _ || _ . // (/_>< | (/_| | |(_|| (_(_|||_\ . //============================================================================== function getPlayerID(address _addr) isRegisteredGame() external returns (uint256) { determinePID(_addr); return (pIDxAddr_[_addr]); } function getPlayerName(uint256 _pID) external view returns (bytes32) { return (plyr_[_pID].name); } function getPlayerLAff(uint256 _pID) external view returns (uint256) { return (plyr_[_pID].laff); } function getPlayerAddr(uint256 _pID) external view returns (address) { return (plyr_[_pID].addr); } function getPlayerLevel(uint256 _pID) external view returns (uint8) { return (plyr_[_pID].level); } function getNameFee() external view returns (uint256) { return(registrationFee_); } function setPlayerAffID(uint256 _pID,uint256 _laff) isRegisteredGame() external { plyr_[_pID].laff = _laff; emit eveSetAffID(_pID, plyr_[_pID].addr, _laff, plyr_[_laff].addr); } function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all, uint8 _level) isRegisteredGame() isLevel(_level) external payable returns(bool, uint256) { // make sure name fees paid //TODO 已经通过 islevel //require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given, no new affiliate code was given, or the // player tried to use their own pID as an affiliate code, lolz uint256 _affID = _affCode; if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID) { // update last affiliate if (plyr_[_pID].laff == 0) plyr_[_pID].laff = _affID; } else if (_affID == _pID) { _affID = 0; } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all, _level); return(_isNewPlayer, _affID); } function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all, uint8 _level) isRegisteredGame() isLevel(_level) external payable returns(bool, uint256) { // make sure name fees paid //TODO 已经通过 islevel //require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate if (plyr_[_pID].laff == 0) plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all, _level); return(_isNewPlayer, _affID); } function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all, uint8 _level) isRegisteredGame() isLevel(_level) external payable returns(bool, uint256) { // make sure name fees paid //TODO 已经通过 islevel //require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != "" && _affCode != _name) { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate if (plyr_[_pID].laff == 0) plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all, _level); return(_isNewPlayer, _affID); } //============================================================================== // _ _ _|_ _ . // _\(/_ | |_||_) . //=============|================================================================ function addGame(address _gameAddress, string _gameNameStr) onlyDevs() public { require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered"); deleteProposal("addGame"); gID_++; bytes32 _name = _gameNameStr.nameFilter(); gameIDs_[_gameAddress] = gID_; gameNames_[_gameAddress] = _name; games_[gID_] = PlayerBookReceiverInterface(_gameAddress); for(uint8 i=0; i<superPlayers_.length; i++){ uint256 pid =superPlayers_[i]; if( pid > 0 ){ games_[gID_].receivePlayerInfo(pid, plyr_[pid].addr, plyr_[pid].name, 0, plyr_[pid].level); } } } function setRegistrationFee(uint256 _fee) onlyDevs() public { deleteProposal("setRegistrationFee"); registrationFee_ = _fee; } }
make sure name fees paid TODO 已经通过 islevelrequire (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); set up our tx event data and determine if player is new or not fetch player id manage affiliate residuals if no affiliate code was given or player tried to use their own, lolz get affiliate ID from aff Code if affID is not the same as previously stored update last affiliate
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all, uint8 _level) isRegisteredGame() isLevel(_level) external payable returns(bool, uint256) { bool _isNewPlayer = determinePID(_addr); uint256 _pID = pIDxAddr_[_addr]; uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { _affID = pIDxAddr_[_affCode]; if (_affID != plyr_[_pID].laff) { if (plyr_[_pID].laff == 0) plyr_[_pID].laff = _affID; } } return(_isNewPlayer, _affID); }
6,075,933
[ 1, 6540, 3071, 508, 1656, 281, 30591, 2660, 225, 166, 120, 115, 168, 124, 242, 170, 227, 253, 169, 128, 234, 353, 2815, 6528, 261, 3576, 18, 1132, 1545, 7914, 14667, 67, 16, 315, 379, 81, 838, 2777, 225, 1846, 1240, 358, 8843, 326, 508, 14036, 8863, 444, 731, 3134, 2229, 871, 501, 471, 4199, 309, 7291, 353, 394, 578, 486, 2158, 7291, 612, 10680, 7103, 330, 3840, 29252, 309, 1158, 7103, 330, 3840, 981, 1703, 864, 578, 7291, 12928, 358, 999, 3675, 4953, 16, 328, 355, 94, 336, 7103, 330, 3840, 1599, 628, 7103, 3356, 309, 7103, 734, 353, 486, 326, 1967, 487, 7243, 4041, 1089, 1142, 7103, 330, 3840, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1744, 461, 60, 4793, 1265, 40, 2910, 12, 2867, 389, 4793, 16, 1731, 1578, 389, 529, 16, 1758, 389, 7329, 1085, 16, 1426, 389, 454, 16, 2254, 28, 389, 2815, 13, 203, 3639, 353, 10868, 12496, 1435, 203, 3639, 353, 2355, 24899, 2815, 13, 203, 3639, 3903, 203, 3639, 8843, 429, 203, 3639, 1135, 12, 6430, 16, 2254, 5034, 13, 203, 565, 288, 203, 540, 203, 3639, 1426, 389, 291, 1908, 12148, 273, 4199, 16522, 24899, 4793, 1769, 203, 540, 203, 3639, 2254, 5034, 389, 84, 734, 273, 293, 734, 92, 3178, 67, 63, 67, 4793, 15533, 203, 540, 203, 3639, 2254, 5034, 389, 7329, 734, 31, 203, 3639, 309, 261, 67, 7329, 1085, 480, 1758, 12, 20, 13, 597, 389, 7329, 1085, 480, 389, 4793, 13, 203, 3639, 288, 203, 5411, 389, 7329, 734, 273, 293, 734, 92, 3178, 67, 63, 67, 7329, 1085, 15533, 203, 2398, 203, 5411, 309, 261, 67, 7329, 734, 480, 293, 715, 86, 67, 63, 67, 84, 734, 8009, 80, 7329, 13, 203, 5411, 288, 203, 7734, 309, 261, 1283, 86, 67, 63, 67, 84, 734, 8009, 80, 7329, 422, 374, 13, 203, 10792, 293, 715, 86, 67, 63, 67, 84, 734, 8009, 80, 7329, 273, 389, 7329, 734, 31, 203, 5411, 289, 203, 3639, 289, 203, 203, 540, 203, 3639, 327, 24899, 291, 1908, 12148, 16, 389, 7329, 734, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./SwapUtils.sol"; /** * @title AmplificationUtils library * @notice A library to calculate and ramp the A parameter of a given `SwapUtils.Swap` struct. * This library assumes the struct is fully validated. */ library AmplificationUtils { using SafeMath for uint256; event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(SwapUtils.Swap storage self) external view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(SwapUtils.Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(SwapUtils.Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( SwapUtils.Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(SwapUtils.Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // 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.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./AmplificationUtils.sol"; import "./LPToken.sol"; import "./MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtils { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; LPToken lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculations in the // {add,remove}Liquidity functions to avoid stack too deep errors struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; LPToken lpToken; uint256 totalSupply; uint256[] balances; uint256[] multipliers; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; /*** VIEW & PURE FUNCTIONS ***/ function _getAPrecise(Swap storage self) internal view returns (uint256) { return AmplificationUtils._getAPrecise(self); } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive */ function calculateWithdrawOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { (uint256 availableTokenAmount, ) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, self.lpToken.totalSupply() ); return availableTokenAmount; } function _calculateWithdrawOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 newY; uint256 currentY; (dy, newY, currentY) = calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, totalSupply ); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant iteratively. * See the StableSwap paper and Curve.fi implementation for further details. * * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex Index of token we are calculating for. * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool. * @param d the stableswap invariant * @return the price of the token, in the same precision as in xp */ function getYD( uint256 a, uint8 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @param xp a precision-adjusted set of pool balances. Array should be the same cardinality * as the pool. * @param a the amplification coefficient * n * (n - 1) in A_PRECISION. * See the StableSwap paper for details * @return the invariant, at the precision of the pool */ function getD(uint256[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA .mul(s) .div(AmplificationUtils.A_PRECISION) .add(dP.mul(numTokens)) .mul(d) .div( nA .sub(AmplificationUtils.A_PRECISION) .mul(d) .div(AmplificationUtils.A_PRECISION) .add(numTokens.add(1).mul(dP)) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); LPToken lpToken = self.lpToken; uint256 supply = lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(POOL_PRECISION_DECIMALS)).div(supply); } return 0; } /** * @notice Calculate the new balances of the tokens given the indexes of the token * that is swapped from (FROM) and the token that is swapped to (TO). * This function is used as a helper function to calculate how much TO token * the user should receive on swap. * * @param preciseA precise form of amplification coefficient * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @param x the new total amount of FROM token * @param xp balances of the tokens in the pool * @return the amount of TO token that should remain in the pool */ function getY( uint256 preciseA, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal pure returns (uint256) { uint256 numTokens = xp.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 d = getD(xp, preciseA); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(preciseA); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, self.balances ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256[] memory balances ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256[] memory xp = _xp(balances, multipliers); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(multipliers[tokenIndexFrom]).add(xp[tokenIndexFrom]); uint256 y = getY( _getAPrecise(self), tokenIndexFrom, tokenIndexTo, x, xp ); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(multipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity(Swap storage self, uint256 amount) external view returns (uint256[] memory) { return _calculateRemoveLiquidity( self.balances, amount, self.lpToken.totalSupply() ); } function _calculateRemoveLiquidity( uint256[] memory balances, uint256 amount, uint256 totalSupply ) internal pure returns (uint256[] memory) { require(amount <= totalSupply, "Cannot exceed total supply"); uint256[] memory amounts = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amounts[i] = balances[i].mul(amount).div(totalSupply); } return amounts; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = _getAPrecise(self); uint256[] memory balances = self.balances; uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256 d0 = getD(_xp(balances, multipliers), a); for (uint256 i = 0; i < balances.length; i++) { if (deposit) { balances[i] = balances[i].add(amounts[i]); } else { balances[i] = balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(balances, multipliers), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param swapFee swap fee for the tokens * @param numTokens number of tokens pooled */ function _feePerToken(uint256 swapFee, uint256 numTokens) internal pure returns (uint256) { return swapFee.mul(numTokens).div(numTokens.sub(1).mul(4)); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math dx = tokenFrom.balanceOf(address(this)).sub(beforeBalance); } uint256 dy; uint256 dyFee; uint256[] memory balances = self.balances; (dy, dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, balances ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = balances[tokenIndexFrom].add(dx); self.balances[tokenIndexTo] = balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap(msg.sender, dx, dy, tokenIndexFrom, tokenIndexTo); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); } uint256[] memory newBalances = new uint256[](pooledTokens.length); for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf( address(this) ); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = v.balances[i].add(amounts[i]); } // invariant after change v.d1 = getD(_xp(newBalances, v.multipliers), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256[] memory fees = new uint256[](pooledTokens.length); if (v.totalSupply != 0) { uint256 feePerToken = _feePerToken( self.swapFee, pooledTokens.length ); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(newBalances, v.multipliers), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (v.totalSupply == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens v.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(amount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory balances = self.balances; uint256 totalSupply = lpToken.totalSupply(); uint256[] memory amounts = _calculateRemoveLiquidity( balances, amount, totalSupply ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = balances[i].sub(amounts[i]); pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, totalSupply.sub(amount)); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < pooledTokens.length, "Token not found"); uint256 totalSupply = lpToken.totalSupply(); (uint256 dy, uint256 dyFee) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, totalSupply ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); lpToken.burnFrom(msg.sender, tokenAmount); pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= v.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); uint256 feePerToken = _feePerToken(self.swapFee, pooledTokens.length); uint256[] memory fees = new uint256[](pooledTokens.length); { uint256[] memory balances1 = new uint256[](pooledTokens.length); v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { balances1[i] = v.balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(balances1, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(balances1, v.multipliers), v.preciseA); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < pooledTokens.length; i++) { pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { IERC20[] memory pooledTokens = self.pooledTokens; for (uint256 i = 0; i < pooledTokens.length; i++) { IERC20 token = pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub( self.balances[i] ); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/ISwap.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. * @dev Only Swap contracts should initialize and own LPToken contracts. */ contract LPToken is ERC20BurnableUpgradeable, OwnableUpgradeable { using SafeMathUpgradeable for uint256; /** * @notice Initializes this LPToken contract with the given name and symbol * @dev The caller of this function will become the owner. A Swap contract should call this * in its initializer function. * @param name name of this token * @param symbol symbol of this token */ function initialize(string memory name, string memory symbol) external initializer returns (bool) { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); __Ownable_init_unchained(); return true; } /** * @notice Mints the given amount of LPToken to the recipient. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "LPToken: cannot mint 0"); _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that Swap.updateUserWithdrawFees are called everytime. * This assumes the owner is set to a Swap contract's address. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable) { super._beforeTokenTransfer(from, to, amount); require(to != address(this), "LPToken: cannot send to itself"); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title MathUtils library * @notice A library to be used in conjunction with SafeMath. Contains functions for calculating * differences between two uint256. */ library MathUtils { /** * @notice Compares a and b and returns true if the difference between a and b * is less than 1 or equal to each other. * @param a uint256 to compare with * @param b uint256 to compare with * @return True if the difference between a and b is less than 1 or equal, * otherwise return false */ function within1(uint256 a, uint256 b) internal pure returns (bool) { return (difference(a, b) <= 1); } /** * @notice Calculates absolute difference between a and b * @param a uint256 to compare with * @param b uint256 to compare with * @return Difference between a and b */ function difference(uint256 a, uint256 b) internal pure returns (uint256) { if (a > b) { return a - b; } return b - a; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./ERC20Upgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable { function __ERC20Burnable_init() internal initializer { __Context_init_unchained(); __ERC20Burnable_init_unchained(); } function __ERC20Burnable_init_unchained() internal initializer { } using SafeMathUpgradeable for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view 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 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./IAllowlist.sol"; interface ISwap { // pool data view functions function getA() external view returns (uint256); function getAllowlist() external view returns (IAllowlist); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); function swapStorage() external view returns ( uint256, uint256, uint256, uint256, uint256, uint256, address ); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 a, uint256 fee, uint256 adminFee, address lpTokenTargetAddress ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 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 SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IAllowlist { function getPoolAccountLimit(address poolAddress) external view returns (uint256); function getPoolCap(address poolAddress) external view returns (uint256); function verifyAddress(address account, bytes32[] calldata merkleProof) external returns (bool); } // 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.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "./OwnerPausableUpgradeable.sol"; import "./SwapUtils.sol"; import "./AmplificationUtils.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract Swap is OwnerPausableUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; using SwapUtils for SwapUtils.Swap; using AmplificationUtils for SwapUtils.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtils.sol SwapUtils.Swap public swapStorage; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) public virtual initializer { __OwnerPausable_init(); __ReentrancyGuard_init(); // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtils.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtils.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee parameters require(_a < AmplificationUtils.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtils.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtils.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); // Clone and initialize a LPToken contract LPToken lpToken = LPToken(Clones.clone(lpTokenTargetAddress)); require( lpToken.initialize(lpTokenName, lpTokenSymbol), "could not init lpToken clone" ); // Initialize swapStorage struct swapStorage.lpToken = lpToken; swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(AmplificationUtils.A_PRECISION); swapStorage.futureA = _a.mul(AmplificationUtils.A_PRECISION); // swapStorage.initialATime = 0; // swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view virtual returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view virtual returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view virtual returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) public view virtual returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view virtual returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view virtual returns (uint256) { return swapStorage.calculateTokenAmount(amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(uint256 amount) external view virtual returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view virtual returns (uint256 availableTokenAmount) { return swapStorage.calculateWithdrawOneToken(tokenAmount, tokenIndex); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view virtual returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external virtual nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`. * * This function uses the create opcode, which should never revert. */ function clone(address master) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `master` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address master, bytes32 salt, address deployer) internal pure returns (address predicted) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address master, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(master, salt, address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/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 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; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; /** * @title OwnerPausable * @notice An ownable contract allows the owner to pause and unpause the * contract without a delay. * @dev Only methods using the provided modifiers will be paused. */ abstract contract OwnerPausableUpgradeable is OwnableUpgradeable, PausableUpgradeable { function __OwnerPausable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); } /** * @notice Pause the contract. Revert if already paused. */ function pause() external onlyOwner { PausableUpgradeable._pause(); } /** * @notice Unpause the contract. Revert if already unpaused. */ function unpause() external onlyOwner { PausableUpgradeable._unpause(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT WITH AGPL-3.0-only pragma solidity 0.6.12; import "./Swap.sol"; import "./interfaces/IFlashLoanReceiver.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapFlashLoan is Swap { // Total fee that is charged on all flashloans in BPS. Borrowers must repay the amount plus the flash loan fee. // This fee is split between the protocol and the pool. uint256 public flashLoanFeeBPS; // Share of the flash loan fee that goes to the protocol in BPS. A portion of each flash loan fee is allocated // to the protocol rather than the pool. uint256 public protocolFeeShareBPS; // Max BPS for limiting flash loan fee settings. uint256 public constant MAX_BPS = 10000; /*** EVENTS ***/ event FlashLoan( address indexed receiver, uint8 tokenIndex, uint256 amount, uint256 amountFee, uint256 protocolFee ); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) public virtual override initializer { Swap.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress ); flashLoanFeeBPS = 8; // 8 bps protocolFeeShareBPS = 0; // 0 bps } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Borrow the specified token from this pool for this transaction only. This function will call * `IFlashLoanReceiver(receiver).executeOperation` and the `receiver` must return the full amount of the token * and the associated fee by the end of the callback transaction. If the conditions are not met, this call * is reverted. * @param receiver the address of the receiver of the token. This address must implement the IFlashLoanReceiver * interface and the callback function `executeOperation`. * @param token the protocol fee in bps to be applied on the total flash loan fee * @param amount the total amount to borrow in this transaction * @param params optional data to pass along to the callback function */ function flashLoan( address receiver, IERC20 token, uint256 amount, bytes memory params ) external nonReentrant { uint8 tokenIndex = getTokenIndex(address(token)); uint256 availableLiquidityBefore = token.balanceOf(address(this)); uint256 protocolBalanceBefore = availableLiquidityBefore.sub( swapStorage.balances[tokenIndex] ); require( amount > 0 && availableLiquidityBefore >= amount, "invalid amount" ); // Calculate the additional amount of tokens the pool should end up with uint256 amountFee = amount.mul(flashLoanFeeBPS).div(10000); // Calculate the portion of the fee that will go to the protocol uint256 protocolFee = amountFee.mul(protocolFeeShareBPS).div(10000); require(amountFee > 0, "amount is small for a flashLoan"); // Transfer the requested amount of tokens token.safeTransfer(receiver, amount); // Execute callback function on receiver IFlashLoanReceiver(receiver).executeOperation( address(this), address(token), amount, amountFee, params ); uint256 availableLiquidityAfter = token.balanceOf(address(this)); require( availableLiquidityAfter >= availableLiquidityBefore.add(amountFee), "flashLoan fee is not met" ); swapStorage.balances[tokenIndex] = availableLiquidityAfter .sub(protocolBalanceBefore) .sub(protocolFee); emit FlashLoan(receiver, tokenIndex, amount, amountFee, protocolFee); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the flash loan fee parameters. This function can only be called by the owner. * @param newFlashLoanFeeBPS the total fee in bps to be applied on future flash loans * @param newProtocolFeeShareBPS the protocol fee in bps to be applied on the total flash loan fee */ function setFlashLoanFees( uint256 newFlashLoanFeeBPS, uint256 newProtocolFeeShareBPS ) external onlyOwner { require( newFlashLoanFeeBPS > 0 && newFlashLoanFeeBPS <= MAX_BPS && newProtocolFeeShareBPS <= MAX_BPS, "fees are not in valid range" ); flashLoanFeeBPS = newFlashLoanFeeBPS; protocolFeeShareBPS = newProtocolFeeShareBPS; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.6.12; /** * @title IFlashLoanReceiver interface * @notice Interface for the Saddle fee IFlashLoanReceiver. Modified from Aave's IFlashLoanReceiver interface. * https://github.com/aave/aave-protocol/blob/4b4545fb583fd4f400507b10f3c3114f45b8a037/contracts/flashloan/interfaces/IFlashLoanReceiver.sol * @author Aave * @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract **/ interface IFlashLoanReceiver { function executeOperation( address pool, address token, uint256 amount, uint256 fee, bytes calldata params ) external; } // SPDX-License-Identifier: MIT WITH AGPL-3.0-only pragma solidity 0.6.12; import "./SwapV1.sol"; import "./interfaces/IFlashLoanReceiver.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapFlashLoanV1 is SwapV1 { // Total fee that is charged on all flashloans in BPS. Borrowers must repay the amount plus the flash loan fee. // This fee is split between the protocol and the pool. uint256 public flashLoanFeeBPS; // Share of the flash loan fee that goes to the protocol in BPS. A portion of each flash loan fee is allocated // to the protocol rather than the pool. uint256 public protocolFeeShareBPS; // Max BPS for limiting flash loan fee settings. uint256 public constant MAX_BPS = 10000; /*** EVENTS ***/ event FlashLoan( address indexed receiver, uint8 tokenIndex, uint256 amount, uint256 amountFee, uint256 protocolFee ); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) public virtual override initializer { SwapV1.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, _withdrawFee, lpTokenTargetAddress ); flashLoanFeeBPS = 8; // 8 bps protocolFeeShareBPS = 0; // 0 bps } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Borrow the specified token from this pool for this transaction only. This function will call * `IFlashLoanReceiver(receiver).executeOperation` and the `receiver` must return the full amount of the token * and the associated fee by the end of the callback transaction. If the conditions are not met, this call * is reverted. * @param receiver the address of the receiver of the token. This address must implement the IFlashLoanReceiver * interface and the callback function `executeOperation`. * @param token the protocol fee in bps to be applied on the total flash loan fee * @param amount the total amount to borrow in this transaction * @param params optional data to pass along to the callback function */ function flashLoan( address receiver, IERC20 token, uint256 amount, bytes memory params ) external nonReentrant { uint8 tokenIndex = getTokenIndex(address(token)); uint256 availableLiquidityBefore = token.balanceOf(address(this)); uint256 protocolBalanceBefore = availableLiquidityBefore.sub( swapStorage.balances[tokenIndex] ); require( amount > 0 && availableLiquidityBefore >= amount, "invalid amount" ); // Calculate the additional amount of tokens the pool should end up with uint256 amountFee = amount.mul(flashLoanFeeBPS).div(10000); // Calculate the portion of the fee that will go to the protocol uint256 protocolFee = amountFee.mul(protocolFeeShareBPS).div(10000); require(amountFee > 0, "amount is small for a flashLoan"); // Transfer the requested amount of tokens token.safeTransfer(receiver, amount); // Execute callback function on receiver IFlashLoanReceiver(receiver).executeOperation( address(this), address(token), amount, amountFee, params ); uint256 availableLiquidityAfter = token.balanceOf(address(this)); require( availableLiquidityAfter >= availableLiquidityBefore.add(amountFee), "flashLoan fee is not met" ); swapStorage.balances[tokenIndex] = availableLiquidityAfter .sub(protocolBalanceBefore) .sub(protocolFee); emit FlashLoan(receiver, tokenIndex, amount, amountFee, protocolFee); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the flash loan fee parameters. This function can only be called by the owner. * @param newFlashLoanFeeBPS the total fee in bps to be applied on future flash loans * @param newProtocolFeeShareBPS the protocol fee in bps to be applied on the total flash loan fee */ function setFlashLoanFees( uint256 newFlashLoanFeeBPS, uint256 newProtocolFeeShareBPS ) external onlyOwner { require( newFlashLoanFeeBPS > 0 && newFlashLoanFeeBPS <= MAX_BPS && newProtocolFeeShareBPS <= MAX_BPS, "fees are not in valid range" ); flashLoanFeeBPS = newFlashLoanFeeBPS; protocolFeeShareBPS = newProtocolFeeShareBPS; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "./OwnerPausableUpgradeable.sol"; import "./SwapUtilsV1.sol"; import "./AmplificationUtilsV1.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapV1 is OwnerPausableUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; using SwapUtilsV1 for SwapUtilsV1.Swap; using AmplificationUtilsV1 for SwapUtilsV1.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtilsV1.sol SwapUtilsV1.Swap public swapStorage; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) public virtual initializer { __OwnerPausable_init(); __ReentrancyGuard_init(); // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtilsV1.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtilsV1.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee parameters require(_a < AmplificationUtilsV1.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtilsV1.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtilsV1.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); require( _withdrawFee < SwapUtilsV1.MAX_WITHDRAW_FEE, "_withdrawFee exceeds maximum" ); // Clone and initialize a LPToken contract LPToken lpToken = LPToken(Clones.clone(lpTokenTargetAddress)); require( lpToken.initialize(lpTokenName, lpTokenSymbol), "could not init lpToken clone" ); // Initialize swapStorage struct swapStorage.lpToken = lpToken; swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(AmplificationUtilsV1.A_PRECISION); swapStorage.futureA = _a.mul(AmplificationUtilsV1.A_PRECISION); // swapStorage.initialATime = 0; // swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; swapStorage.defaultWithdrawFee = _withdrawFee; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view virtual returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view virtual returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view virtual returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) public view virtual returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Return timestamp of last deposit of given address * @return timestamp of the last deposit made by the given address */ function getDepositTimestamp(address user) external view virtual returns (uint256) { return swapStorage.getDepositTimestamp(user); } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view virtual returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param account address that is depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view virtual returns (uint256) { return swapStorage.calculateTokenAmount(account, amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param account the address that is withdrawing tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(address account, uint256 amount) external view virtual returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(account, amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param account the address that is withdrawing tokens * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view virtual returns (uint256 availableTokenAmount) { return swapStorage.calculateWithdrawOneToken( account, tokenAmount, tokenIndex ); } /** * @notice Calculate the fee that is applied when the given user withdraws. The withdraw fee * decays linearly over period of 4 weeks. For example, depositing and withdrawing right away * will charge you the full amount of withdraw fee. But withdrawing after 4 weeks will charge you * no additional fees. * @dev returned value should be divided by FEE_DENOMINATOR to convert to correct decimals * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(address user) external view virtual returns (uint256) { return swapStorage.calculateCurrentWithdrawFee(user); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view virtual returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external virtual nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the user withdraw fee. This function can only be called by * the pool token. Should be used to update the withdraw fee on transfer of pool tokens. * Transferring your pool token will reset the 4 weeks period. If the recipient is already * holding some pool tokens, the withdraw fee will be discounted in respective amounts. * @param recipient address of the recipient of pool token * @param transferAmount amount of pool token to transfer */ function updateUserWithdrawFee(address recipient, uint256 transferAmount) external { require( msg.sender == address(swapStorage.lpToken), "Only callable by pool token" ); swapStorage.updateUserWithdrawFee(recipient, transferAmount); } /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Update the withdraw fee. This fee decays linearly over 4 weeks since * user's last deposit. * @param newWithdrawFee new withdraw fee to be applied on future deposits */ function setDefaultWithdrawFee(uint256 newWithdrawFee) external onlyOwner { swapStorage.setDefaultWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./AmplificationUtilsV1.sol"; import "./LPToken.sol"; import "./MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtilsV1 { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; uint256 defaultWithdrawFee; LPToken lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; mapping(address => uint256) depositTimestamp; mapping(address => uint256) withdrawFeeMultiplier; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculations in the // {add,remove}Liquidity functions to avoid stack too deep errors struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; LPToken lpToken; uint256 totalSupply; uint256[] balances; uint256[] multipliers; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Max withdrawFee is 1% of the value withdrawn // Fee will be redistributed to the LPs in the pool, rewarding // long term providers. uint256 public constant MAX_WITHDRAW_FEE = 10**8; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; // Time that it should take for the withdraw fee to fully decay to 0 uint256 public constant WITHDRAW_FEE_DECAY_TIME = 4 weeks; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Retrieves the timestamp of last deposit made by the given address * @param self Swap struct to read from * @return timestamp of last deposit */ function getDepositTimestamp(Swap storage self, address user) external view returns (uint256) { return self.depositTimestamp[user]; } function _getAPrecise(Swap storage self) internal view returns (uint256) { return AmplificationUtilsV1._getAPrecise(self); } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param account the address that is withdrawing * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive */ function calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { (uint256 availableTokenAmount, ) = _calculateWithdrawOneToken( self, account, tokenAmount, tokenIndex, self.lpToken.totalSupply() ); return availableTokenAmount; } function _calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 newY; uint256 currentY; (dy, newY, currentY) = calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, totalSupply ); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); dy = dy .mul( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant iteratively. * See the StableSwap paper and Curve.fi implementation for further details. * * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex Index of token we are calculating for. * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool. * @param d the stableswap invariant * @return the price of the token, in the same precision as in xp */ function getYD( uint256 a, uint8 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(AmplificationUtilsV1.A_PRECISION).div( nA.mul(numTokens) ); uint256 b = s.add(d.mul(AmplificationUtilsV1.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @param xp a precision-adjusted set of pool balances. Array should be the same cardinality * as the pool. * @param a the amplification coefficient * n * (n - 1) in A_PRECISION. * See the StableSwap paper for details * @return the invariant, at the precision of the pool */ function getD(uint256[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA .mul(s) .div(AmplificationUtilsV1.A_PRECISION) .add(dP.mul(numTokens)) .mul(d) .div( nA .sub(AmplificationUtilsV1.A_PRECISION) .mul(d) .div(AmplificationUtilsV1.A_PRECISION) .add(numTokens.add(1).mul(dP)) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); LPToken lpToken = self.lpToken; uint256 supply = lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(POOL_PRECISION_DECIMALS)).div(supply); } return 0; } /** * @notice Calculate the new balances of the tokens given the indexes of the token * that is swapped from (FROM) and the token that is swapped to (TO). * This function is used as a helper function to calculate how much TO token * the user should receive on swap. * * @param preciseA precise form of amplification coefficient * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @param x the new total amount of FROM token * @param xp balances of the tokens in the pool * @return the amount of TO token that should remain in the pool */ function getY( uint256 preciseA, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal pure returns (uint256) { uint256 numTokens = xp.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 d = getD(xp, preciseA); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(preciseA); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(AmplificationUtilsV1.A_PRECISION).div( nA.mul(numTokens) ); uint256 b = s.add(d.mul(AmplificationUtilsV1.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, self.balances ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256[] memory balances ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256[] memory xp = _xp(balances, multipliers); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(multipliers[tokenIndexFrom]).add(xp[tokenIndexFrom]); uint256 y = getY( _getAPrecise(self), tokenIndexFrom, tokenIndexTo, x, xp ); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(multipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param account the address that is removing liquidity. required for withdraw fee calculation * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) external view returns (uint256[] memory) { return _calculateRemoveLiquidity( self, self.balances, account, amount, self.lpToken.totalSupply() ); } function _calculateRemoveLiquidity( Swap storage self, uint256[] memory balances, address account, uint256 amount, uint256 totalSupply ) internal view returns (uint256[] memory) { require(amount <= totalSupply, "Cannot exceed total supply"); uint256 feeAdjustedAmount = amount .mul( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); uint256[] memory amounts = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amounts[i] = balances[i].mul(feeAdjustedAmount).div(totalSupply); } return amounts; } /** * @notice Calculate the fee that is applied when the given user withdraws. * Withdraw fee decays linearly over WITHDRAW_FEE_DECAY_TIME. * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(Swap storage self, address user) external view returns (uint256) { return _calculateCurrentWithdrawFee(self, user); } function _calculateCurrentWithdrawFee(Swap storage self, address user) internal view returns (uint256) { uint256 endTime = self.depositTimestamp[user].add( WITHDRAW_FEE_DECAY_TIME ); if (endTime > block.timestamp) { uint256 timeLeftover = endTime.sub(block.timestamp); return self .defaultWithdrawFee .mul(self.withdrawFeeMultiplier[user]) .mul(timeLeftover) .div(WITHDRAW_FEE_DECAY_TIME) .div(FEE_DENOMINATOR); } return 0; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param account address of the account depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = _getAPrecise(self); uint256[] memory balances = self.balances; uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256 d0 = getD(_xp(balances, multipliers), a); for (uint256 i = 0; i < balances.length; i++) { if (deposit) { balances[i] = balances[i].add(amounts[i]); } else { balances[i] = balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(balances, multipliers), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub( _calculateCurrentWithdrawFee(self, account) ) ); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param swapFee swap fee for the tokens * @param numTokens number of tokens pooled */ function _feePerToken(uint256 swapFee, uint256 numTokens) internal pure returns (uint256) { return swapFee.mul(numTokens).div(numTokens.sub(1).mul(4)); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math dx = tokenFrom.balanceOf(address(this)).sub(beforeBalance); } uint256 dy; uint256 dyFee; uint256[] memory balances = self.balances; (dy, dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, balances ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = balances[tokenIndexFrom].add(dx); self.balances[tokenIndexTo] = balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap(msg.sender, dx, dy, tokenIndexFrom, tokenIndexTo); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); } uint256[] memory newBalances = new uint256[](pooledTokens.length); for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf( address(this) ); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = v.balances[i].add(amounts[i]); } // invariant after change v.d1 = getD(_xp(newBalances, v.multipliers), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256[] memory fees = new uint256[](pooledTokens.length); if (v.totalSupply != 0) { uint256 feePerToken = _feePerToken( self.swapFee, pooledTokens.length ); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(newBalances, v.multipliers), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (v.totalSupply == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens v.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Update the withdraw fee for `user`. If the user is currently * not providing liquidity in the pool, sets to default value. If not, recalculate * the starting withdraw fee based on the last deposit's time & amount relative * to the new deposit. * * @param self Swap struct to read from and write to * @param user address of the user depositing tokens * @param toMint amount of pool tokens to be minted */ function updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) public { // If token is transferred to address 0 (or burned), don't update the fee. if (user == address(0)) { return; } if (self.defaultWithdrawFee == 0) { // If current fee is set to 0%, set multiplier to FEE_DENOMINATOR self.withdrawFeeMultiplier[user] = FEE_DENOMINATOR; } else { // Otherwise, calculate appropriate discount based on last deposit amount uint256 currentFee = _calculateCurrentWithdrawFee(self, user); uint256 currentBalance = self.lpToken.balanceOf(user); // ((currentBalance * currentFee) + (toMint * defaultWithdrawFee)) * FEE_DENOMINATOR / // ((toMint + currentBalance) * defaultWithdrawFee) self.withdrawFeeMultiplier[user] = currentBalance .mul(currentFee) .add(toMint.mul(self.defaultWithdrawFee)) .mul(FEE_DENOMINATOR) .div(toMint.add(currentBalance).mul(self.defaultWithdrawFee)); } self.depositTimestamp[user] = block.timestamp; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(amount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory balances = self.balances; uint256 totalSupply = lpToken.totalSupply(); uint256[] memory amounts = _calculateRemoveLiquidity( self, balances, msg.sender, amount, totalSupply ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = balances[i].sub(amounts[i]); pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, totalSupply.sub(amount)); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < pooledTokens.length, "Token not found"); uint256 totalSupply = lpToken.totalSupply(); (uint256 dy, uint256 dyFee) = _calculateWithdrawOneToken( self, msg.sender, tokenAmount, tokenIndex, totalSupply ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); lpToken.burnFrom(msg.sender, tokenAmount); pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= v.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); uint256 feePerToken = _feePerToken(self.swapFee, pooledTokens.length); uint256[] memory fees = new uint256[](pooledTokens.length); { uint256[] memory balances1 = new uint256[](pooledTokens.length); v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { balances1[i] = v.balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(balances1, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(balances1, v.multipliers), v.preciseA); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, msg.sender)) ); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < pooledTokens.length; i++) { pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { IERC20[] memory pooledTokens = self.pooledTokens; for (uint256 i = 0; i < pooledTokens.length; i++) { IERC20 token = pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub( self.balances[i] ); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } /** * @notice update the default withdraw fee. This also affects deposits made in the past as well. * @param self Swap struct to update * @param newWithdrawFee new withdraw fee to be applied */ function setDefaultWithdrawFee(Swap storage self, uint256 newWithdrawFee) external { require(newWithdrawFee <= MAX_WITHDRAW_FEE, "Fee is too high"); self.defaultWithdrawFee = newWithdrawFee; emit NewWithdrawFee(newWithdrawFee); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./SwapUtilsV1.sol"; /** * @title AmplificationUtils library * @notice A library to calculate and ramp the A parameter of a given `SwapUtils.Swap` struct. * This library assumes the struct is fully validated. */ library AmplificationUtilsV1 { using SafeMath for uint256; event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(SwapUtilsV1.Swap storage self) external view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(SwapUtilsV1.Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(SwapUtilsV1.Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( SwapUtilsV1.Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(SwapUtilsV1.Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../LPToken.sol"; import "../interfaces/ISwap.sol"; import "../MathUtils.sol"; import "../SwapUtils.sol"; /** * @title MetaSwapUtils library * @notice A library to be used within MetaSwap.sol. Contains functions responsible for custody and AMM functionalities. * * MetaSwap is a modified version of Swap that allows Swap's LP token to be utilized in pooling with other tokens. * As an example, if there is a Swap pool consisting of [DAI, USDC, USDT]. Then a MetaSwap pool can be created * with [sUSD, BaseSwapLPToken] to allow trades between either the LP token or the underlying tokens and sUSD. * * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library MetaSwapUtils { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; using AmplificationUtils for SwapUtils.Swap; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event TokenSwapUnderlying( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); struct MetaSwap { // Meta-Swap related parameters ISwap baseSwap; uint256 baseVirtualPrice; uint256 baseCacheLastUpdated; IERC20[] baseTokens; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; uint256 xpi; } // Struct storing variables used in calculation in removeLiquidityImbalance function // to avoid stack too deep error struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; LPToken lpToken; uint256 totalSupply; uint256 preciseA; uint256 baseVirtualPrice; uint256[] tokenPrecisionMultipliers; uint256[] newBalances; } struct SwapUnderlyingInfo { uint256 x; uint256 dx; uint256 dy; uint256[] tokenPrecisionMultipliers; uint256[] oldBalances; IERC20[] baseTokens; IERC20 tokenFrom; uint8 metaIndexFrom; IERC20 tokenTo; uint8 metaIndexTo; uint256 baseVirtualPrice; } struct CalculateSwapUnderlyingInfo { uint256 baseVirtualPrice; ISwap baseSwap; uint8 baseLPTokenIndex; uint8 baseTokensLength; uint8 metaIndexTo; uint256 x; uint256 dy; } // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Cache expire time for the stored value of base Swap's virtual price uint256 public constant BASE_CACHE_EXPIRE_TIME = 10 minutes; uint256 public constant BASE_VIRTUAL_PRICE_PRECISION = 10**18; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Return the stored value of base Swap's virtual price. If * value was updated past BASE_CACHE_EXPIRE_TIME, then read it directly * from the base Swap contract. * @param metaSwapStorage MetaSwap struct to read from * @return base Swap's virtual price */ function _getBaseVirtualPrice(MetaSwap storage metaSwapStorage) internal view returns (uint256) { if ( block.timestamp > metaSwapStorage.baseCacheLastUpdated + BASE_CACHE_EXPIRE_TIME ) { return metaSwapStorage.baseSwap.getVirtualPrice(); } return metaSwapStorage.baseVirtualPrice; } function _getBaseSwapFee(ISwap baseSwap) internal view returns (uint256 swapFee) { (, , , , swapFee, , ) = baseSwap.swapStorage(); } /** * @notice Calculate how much the user would receive when withdrawing via single token * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @return dy the amount of token user will receive */ function calculateWithdrawOneToken( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 dy) { (dy, ) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, _getBaseVirtualPrice(metaSwapStorage), self.lpToken.totalSupply() ); } function _calculateWithdrawOneToken( SwapUtils.Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 baseVirtualPrice, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 dySwapFee; { uint256 currentY; uint256 newY; // Calculate how much to withdraw (dy, newY, currentY) = _calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, baseVirtualPrice, totalSupply ); // Calculate the associated swap fee dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); } return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @param baseVirtualPrice the virtual price of the base swap's LP token * @return the dy excluding swap fee, the new y after withdrawing one token, and current y */ function _calculateWithdrawOneTokenDY( SwapUtils.Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 baseVirtualPrice, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self, baseVirtualPrice); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo( 0, 0, 0, 0, self._getAPrecise(), 0 ); v.d0 = SwapUtils.getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = SwapUtils.getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = SwapUtils._feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { v.xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = v.xpi.sub( ( (i == tokenIndex) ? v.xpi.mul(v.d1).div(v.d0).sub(v.newY) : v.xpi.sub(v.xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( SwapUtils.getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); if (tokenIndex == xp.length.sub(1)) { dy = dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(baseVirtualPrice); v.newY = v.newY.mul(BASE_VIRTUAL_PRICE_PRECISION).div( baseVirtualPrice ); xp[tokenIndex] = xp[tokenIndex] .mul(BASE_VIRTUAL_PRICE_PRECISION) .div(baseVirtualPrice); } dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. The last element will also get scaled up by * the given baseVirtualPrice. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @param baseVirtualPrice the base virtual price to scale the balance of the * base Swap's LP token. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers, uint256 baseVirtualPrice ) internal pure returns (uint256[] memory) { uint256[] memory xp = SwapUtils._xp(balances, precisionMultipliers); uint256 baseLPTokenIndex = balances.length.sub(1); xp[baseLPTokenIndex] = xp[baseLPTokenIndex].mul(baseVirtualPrice).div( BASE_VIRTUAL_PRICE_PRECISION ); return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(SwapUtils.Swap storage self, uint256 baseVirtualPrice) internal view returns (uint256[] memory) { return _xp( self.balances, self.tokenPrecisionMultipliers, baseVirtualPrice ); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @return the virtual price, scaled to precision of BASE_VIRTUAL_PRICE_PRECISION */ function getVirtualPrice( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage ) external view returns (uint256) { uint256 d = SwapUtils.getD( _xp( self.balances, self.tokenPrecisionMultipliers, _getBaseVirtualPrice(metaSwapStorage) ), self._getAPrecise() ); uint256 supply = self.lpToken.totalSupply(); if (supply != 0) { return d.mul(BASE_VIRTUAL_PRICE_PRECISION).div(supply); } return 0; } /** * @notice Externally calculates a swap between two tokens. The SwapUtils.Swap storage and * MetaSwap storage should be from the same MetaSwap contract. * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct from the same contract * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, _getBaseVirtualPrice(metaSwapStorage) ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param baseVirtualPrice the virtual price of the base LP token * @return dy the number of tokens the user will get and dyFee the associated fee */ function _calculateSwap( SwapUtils.Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 baseVirtualPrice ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory xp = _xp(self, baseVirtualPrice); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 baseLPTokenIndex = xp.length.sub(1); uint256 x = dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]); if (tokenIndexFrom == baseLPTokenIndex) { // When swapping from a base Swap token, scale up dx by its virtual price x = x.mul(baseVirtualPrice).div(BASE_VIRTUAL_PRICE_PRECISION); } x = x.add(xp[tokenIndexFrom]); uint256 y = SwapUtils.getY( self._getAPrecise(), tokenIndexFrom, tokenIndexTo, x, xp ); dy = xp[tokenIndexTo].sub(y).sub(1); if (tokenIndexTo == baseLPTokenIndex) { // When swapping to a base Swap token, scale down dy by its virtual price dy = dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(baseVirtualPrice); } dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee); dy = dy.div(self.tokenPrecisionMultipliers[tokenIndexTo]); } /** * @notice Calculates the expected return amount from swapping between * the pooled tokens and the underlying tokens of the base Swap pool. * * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct from the same contract * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwapUnderlying( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { CalculateSwapUnderlyingInfo memory v = CalculateSwapUnderlyingInfo( _getBaseVirtualPrice(metaSwapStorage), metaSwapStorage.baseSwap, 0, uint8(metaSwapStorage.baseTokens.length), 0, 0, 0 ); uint256[] memory xp = _xp(self, v.baseVirtualPrice); v.baseLPTokenIndex = uint8(xp.length.sub(1)); { uint8 maxRange = v.baseLPTokenIndex + v.baseTokensLength; require( tokenIndexFrom < maxRange && tokenIndexTo < maxRange, "Token index out of range" ); } if (tokenIndexFrom < v.baseLPTokenIndex) { // tokenFrom is from this pool v.x = xp[tokenIndexFrom].add( dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]) ); } else { // tokenFrom is from the base pool tokenIndexFrom = tokenIndexFrom - v.baseLPTokenIndex; if (tokenIndexTo < v.baseLPTokenIndex) { uint256[] memory baseInputs = new uint256[](v.baseTokensLength); baseInputs[tokenIndexFrom] = dx; v.x = v .baseSwap .calculateTokenAmount(baseInputs, true) .mul(v.baseVirtualPrice) .div(BASE_VIRTUAL_PRICE_PRECISION); // when adding to the base pool,you pay approx 50% of the swap fee v.x = v .x .sub( v.x.mul(_getBaseSwapFee(metaSwapStorage.baseSwap)).div( FEE_DENOMINATOR.mul(2) ) ) .add(xp[v.baseLPTokenIndex]); } else { // both from and to are from the base pool return v.baseSwap.calculateSwap( tokenIndexFrom, tokenIndexTo - v.baseLPTokenIndex, dx ); } tokenIndexFrom = v.baseLPTokenIndex; } v.metaIndexTo = v.baseLPTokenIndex; if (tokenIndexTo < v.baseLPTokenIndex) { v.metaIndexTo = tokenIndexTo; } { uint256 y = SwapUtils.getY( self._getAPrecise(), tokenIndexFrom, v.metaIndexTo, v.x, xp ); v.dy = xp[v.metaIndexTo].sub(y).sub(1); uint256 dyFee = v.dy.mul(self.swapFee).div(FEE_DENOMINATOR); v.dy = v.dy.sub(dyFee); } if (tokenIndexTo < v.baseLPTokenIndex) { // tokenTo is from this pool v.dy = v.dy.div(self.tokenPrecisionMultipliers[v.metaIndexTo]); } else { // tokenTo is from the base pool v.dy = v.baseSwap.calculateRemoveLiquidityOneToken( v.dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(v.baseVirtualPrice), tokenIndexTo - v.baseLPTokenIndex ); } return v.dy; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = self._getAPrecise(); uint256 d0; uint256 d1; { uint256 baseVirtualPrice = _getBaseVirtualPrice(metaSwapStorage); uint256[] memory balances1 = self.balances; uint256[] memory tokenPrecisionMultipliers = self .tokenPrecisionMultipliers; uint256 numTokens = balances1.length; d0 = SwapUtils.getD( _xp(balances1, tokenPrecisionMultipliers, baseVirtualPrice), a ); for (uint256 i = 0; i < numTokens; i++) { if (deposit) { balances1[i] = balances1[i].add(amounts[i]); } else { balances1[i] = balances1[i].sub( amounts[i], "Cannot withdraw more than available" ); } } d1 = SwapUtils.getD( _xp(balances1, tokenPrecisionMultipliers, baseVirtualPrice), a ); } uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0); } } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { uint256 pooledTokensLength = self.pooledTokens.length; require( tokenIndexFrom < pooledTokensLength && tokenIndexTo < pooledTokensLength, "Token index is out of range" ); } uint256 transferredDx; { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); { // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math transferredDx = tokenFrom.balanceOf(address(this)).sub( beforeBalance ); } } (uint256 dy, uint256 dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, transferredDx, _updateBaseVirtualPrice(metaSwapStorage) ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = self.balances[tokenIndexFrom].add( transferredDx ); self.balances[tokenIndexTo] = self.balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap( msg.sender, transferredDx, dy, tokenIndexFrom, tokenIndexTo ); return dy; } /** * @notice Swaps with the underlying tokens of the base Swap pool. For this function, * the token indices are flattened out so that underlying tokens are represented * in the indices. * @dev Since this calls multiple external functions during the execution, * it is recommended to protect any function that depends on this with reentrancy guards. * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swapUnderlying( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { SwapUnderlyingInfo memory v = SwapUnderlyingInfo( 0, 0, 0, self.tokenPrecisionMultipliers, self.balances, metaSwapStorage.baseTokens, IERC20(address(0)), 0, IERC20(address(0)), 0, _updateBaseVirtualPrice(metaSwapStorage) ); uint8 baseLPTokenIndex = uint8(v.oldBalances.length.sub(1)); { uint8 maxRange = uint8(baseLPTokenIndex + v.baseTokens.length); require( tokenIndexFrom < maxRange && tokenIndexTo < maxRange, "Token index out of range" ); } ISwap baseSwap = metaSwapStorage.baseSwap; // Find the address of the token swapping from and the index in MetaSwap's token list if (tokenIndexFrom < baseLPTokenIndex) { v.tokenFrom = self.pooledTokens[tokenIndexFrom]; v.metaIndexFrom = tokenIndexFrom; } else { v.tokenFrom = v.baseTokens[tokenIndexFrom - baseLPTokenIndex]; v.metaIndexFrom = baseLPTokenIndex; } // Find the address of the token swapping to and the index in MetaSwap's token list if (tokenIndexTo < baseLPTokenIndex) { v.tokenTo = self.pooledTokens[tokenIndexTo]; v.metaIndexTo = tokenIndexTo; } else { v.tokenTo = v.baseTokens[tokenIndexTo - baseLPTokenIndex]; v.metaIndexTo = baseLPTokenIndex; } // Check for possible fee on transfer v.dx = v.tokenFrom.balanceOf(address(this)); v.tokenFrom.safeTransferFrom(msg.sender, address(this), dx); v.dx = v.tokenFrom.balanceOf(address(this)).sub(v.dx); // update dx in case of fee on transfer if ( tokenIndexFrom < baseLPTokenIndex || tokenIndexTo < baseLPTokenIndex ) { // Either one of the tokens belongs to the MetaSwap tokens list uint256[] memory xp = _xp( v.oldBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ); if (tokenIndexFrom < baseLPTokenIndex) { // Swapping from a MetaSwap token v.x = xp[tokenIndexFrom].add( dx.mul(v.tokenPrecisionMultipliers[tokenIndexFrom]) ); } else { // Swapping from one of the tokens hosted in the base Swap // This case requires adding the underlying token to the base Swap, then // using the base LP token to swap to the desired token uint256[] memory baseAmounts = new uint256[]( v.baseTokens.length ); baseAmounts[tokenIndexFrom - baseLPTokenIndex] = v.dx; // Add liquidity to the base Swap contract and receive base LP token v.dx = baseSwap.addLiquidity(baseAmounts, 0, block.timestamp); // Calculate the value of total amount of baseLPToken we end up with v.x = v .dx .mul(v.baseVirtualPrice) .div(BASE_VIRTUAL_PRICE_PRECISION) .add(xp[baseLPTokenIndex]); } // Calculate how much to withdraw in MetaSwap level and the the associated swap fee uint256 dyFee; { uint256 y = SwapUtils.getY( self._getAPrecise(), v.metaIndexFrom, v.metaIndexTo, v.x, xp ); v.dy = xp[v.metaIndexTo].sub(y).sub(1); if (tokenIndexTo >= baseLPTokenIndex) { // When swapping to a base Swap token, scale down dy by its virtual price v.dy = v.dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div( v.baseVirtualPrice ); } dyFee = v.dy.mul(self.swapFee).div(FEE_DENOMINATOR); v.dy = v.dy.sub(dyFee).div( v.tokenPrecisionMultipliers[v.metaIndexTo] ); } // Update the balances array according to the calculated input and output amount { uint256 dyAdminFee = dyFee.mul(self.adminFee).div( FEE_DENOMINATOR ); dyAdminFee = dyAdminFee.div( v.tokenPrecisionMultipliers[v.metaIndexTo] ); self.balances[v.metaIndexFrom] = v .oldBalances[v.metaIndexFrom] .add(v.dx); self.balances[v.metaIndexTo] = v .oldBalances[v.metaIndexTo] .sub(v.dy) .sub(dyAdminFee); } if (tokenIndexTo >= baseLPTokenIndex) { // When swapping to a token that belongs to the base Swap, burn the LP token // and withdraw the desired token from the base pool uint256 oldBalance = v.tokenTo.balanceOf(address(this)); baseSwap.removeLiquidityOneToken( v.dy, tokenIndexTo - baseLPTokenIndex, 0, block.timestamp ); v.dy = v.tokenTo.balanceOf(address(this)) - oldBalance; } // Check the amount of token to send meets minDy require(v.dy >= minDy, "Swap didn't result in min tokens"); } else { // Both tokens are from the base Swap pool // Do a swap through the base Swap v.dy = v.tokenTo.balanceOf(address(this)); baseSwap.swap( tokenIndexFrom - baseLPTokenIndex, tokenIndexTo - baseLPTokenIndex, v.dx, minDy, block.timestamp ); v.dy = v.tokenTo.balanceOf(address(this)).sub(v.dy); } // Send the desired token to the caller v.tokenTo.safeTransfer(msg.sender, v.dy); emit TokenSwapUnderlying( msg.sender, dx, v.dy, tokenIndexFrom, tokenIndexTo ); return v.dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); uint256[] memory fees = new uint256[](pooledTokens.length); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, self.lpToken, 0, self._getAPrecise(), _updateBaseVirtualPrice(metaSwapStorage), self.tokenPrecisionMultipliers, self.balances ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = SwapUtils.getD( _xp( v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ), v.preciseA ); } for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf( address(this) ); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } v.newBalances[i] = v.newBalances[i].add(amounts[i]); } // invariant after change v.d1 = SwapUtils.getD( _xp(v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256 toMint; if (v.totalSupply != 0) { uint256 feePerToken = SwapUtils._feePerToken( self.swapFee, pooledTokens.length ); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(self.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(v.newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = v.newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); v.newBalances[i] = v.newBalances[i].sub(fees[i]); } v.d2 = SwapUtils.getD( _xp( v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ), v.preciseA ); toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } else { // the initial depositor doesn't pay fees self.balances = v.newBalances; toMint = v.d1; } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens self.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; uint256 totalSupply = lpToken.totalSupply(); uint256 numTokens = self.pooledTokens.length; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < numTokens, "Token not found"); uint256 dyFee; uint256 dy; (dy, dyFee) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, _updateBaseVirtualPrice(metaSwapStorage), totalSupply ); require(dy >= minAmount, "dy < minAmount"); // Update balances array self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); // Burn the associated LP token from the caller and send the desired token lpToken.burnFrom(msg.sender, tokenAmount); self.pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { // Using this struct to avoid stack too deep error ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, self.lpToken, 0, self._getAPrecise(), _updateBaseVirtualPrice(metaSwapStorage), self.tokenPrecisionMultipliers, self.balances ); v.totalSupply = v.lpToken.totalSupply(); require( amounts.length == v.newBalances.length, "Amounts should match pool tokens" ); require(maxBurnAmount != 0, "Must burn more than 0"); uint256 feePerToken = SwapUtils._feePerToken( self.swapFee, v.newBalances.length ); // Calculate how much LPToken should be burned uint256[] memory fees = new uint256[](v.newBalances.length); { uint256[] memory balances1 = new uint256[](v.newBalances.length); v.d0 = SwapUtils.getD( _xp( v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ), v.preciseA ); for (uint256 i = 0; i < v.newBalances.length; i++) { balances1[i] = v.newBalances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = SwapUtils.getD( _xp(balances1, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); for (uint256 i = 0; i < v.newBalances.length; i++) { uint256 idealBalance = v.d1.mul(v.newBalances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = SwapUtils.getD( _xp(balances1, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); // Scale up by withdraw fee tokenAmount = tokenAmount.add(1); // Check for max burn amount require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); // Burn the calculated amount of LPToken from the caller and send the desired tokens v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < v.newBalances.length; i++) { self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice Determines if the stored value of base Swap's virtual price is expired. * If the last update was past the BASE_CACHE_EXPIRE_TIME, then update the stored value. * * @param metaSwapStorage MetaSwap struct to read from and write to * @return base Swap's virtual price */ function _updateBaseVirtualPrice(MetaSwap storage metaSwapStorage) internal returns (uint256) { if ( block.timestamp > metaSwapStorage.baseCacheLastUpdated + BASE_CACHE_EXPIRE_TIME ) { // When the cache is expired, update it uint256 baseVirtualPrice = ISwap(metaSwapStorage.baseSwap) .getVirtualPrice(); metaSwapStorage.baseVirtualPrice = baseVirtualPrice; metaSwapStorage.baseCacheLastUpdated = block.timestamp; return baseVirtualPrice; } else { return metaSwapStorage.baseVirtualPrice; } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "../LPToken.sol"; import "../interfaces/ISwap.sol"; import "../interfaces/IMetaSwap.sol"; /** * @title MetaSwapDeposit * @notice This contract flattens the LP token in a MetaSwap pool for easier user access. MetaSwap must be * deployed before this contract can be initialized successfully. * * For example, suppose there exists a base Swap pool consisting of [DAI, USDC, USDT]. * Then a MetaSwap pool can be created with [sUSD, BaseSwapLPToken] to allow trades between either * the LP token or the underlying tokens and sUSD. * * MetaSwapDeposit flattens the LP token and remaps them to a single array, allowing users * to ignore the dependency on BaseSwapLPToken. Using the above example, MetaSwapDeposit can act * as a Swap containing [sUSD, DAI, USDC, USDT] tokens. */ contract MetaSwapDeposit is Initializable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; ISwap public baseSwap; IMetaSwap public metaSwap; IERC20[] public baseTokens; IERC20[] public metaTokens; IERC20[] public tokens; IERC20 public metaLPToken; uint256 constant MAX_UINT256 = 2**256 - 1; struct RemoveLiquidityImbalanceInfo { ISwap baseSwap; IMetaSwap metaSwap; IERC20 metaLPToken; uint8 baseLPTokenIndex; bool withdrawFromBase; uint256 leftoverMetaLPTokenAmount; } /** * @notice Sets the address for the base Swap contract, MetaSwap contract, and the * MetaSwap LP token contract. * @param _baseSwap the address of the base Swap contract * @param _metaSwap the address of the MetaSwap contract * @param _metaLPToken the address of the MetaSwap LP token contract */ function initialize( ISwap _baseSwap, IMetaSwap _metaSwap, IERC20 _metaLPToken ) external initializer { __ReentrancyGuard_init(); // Check and approve base level tokens to be deposited to the base Swap contract { uint8 i; for (; i < 32; i++) { try _baseSwap.getToken(i) returns (IERC20 token) { baseTokens.push(token); token.safeApprove(address(_baseSwap), MAX_UINT256); token.safeApprove(address(_metaSwap), MAX_UINT256); } catch { break; } } require(i > 1, "baseSwap must have at least 2 tokens"); } // Check and approve meta level tokens to be deposited to the MetaSwap contract IERC20 baseLPToken; { uint8 i; for (; i < 32; i++) { try _metaSwap.getToken(i) returns (IERC20 token) { baseLPToken = token; metaTokens.push(token); tokens.push(token); token.safeApprove(address(_metaSwap), MAX_UINT256); } catch { break; } } require(i > 1, "metaSwap must have at least 2 tokens"); } // Flatten baseTokens and append it to tokens array tokens[tokens.length - 1] = baseTokens[0]; for (uint8 i = 1; i < baseTokens.length; i++) { tokens.push(baseTokens[i]); } // Approve base Swap LP token to be burned by the base Swap contract for withdrawing baseLPToken.safeApprove(address(_baseSwap), MAX_UINT256); // Approve MetaSwap LP token to be burned by the MetaSwap contract for withdrawing _metaLPToken.safeApprove(address(_metaSwap), MAX_UINT256); // Initialize storage variables baseSwap = _baseSwap; metaSwap = _metaSwap; metaLPToken = _metaLPToken; } // Mutative functions /** * @notice Swap two underlying tokens using the meta pool and the base pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external nonReentrant returns (uint256) { tokens[tokenIndexFrom].safeTransferFrom(msg.sender, address(this), dx); uint256 tokenToAmount = metaSwap.swapUnderlying( tokenIndexFrom, tokenIndexTo, dx, minDy, deadline ); tokens[tokenIndexTo].safeTransfer(msg.sender, tokenToAmount); return tokenToAmount; } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external nonReentrant returns (uint256) { // Read to memory to save on gas IERC20[] memory memBaseTokens = baseTokens; IERC20[] memory memMetaTokens = metaTokens; uint256 baseLPTokenIndex = memMetaTokens.length - 1; require(amounts.length == memBaseTokens.length + baseLPTokenIndex); uint256 baseLPTokenAmount; { // Transfer base tokens from the caller and deposit to the base Swap pool uint256[] memory baseAmounts = new uint256[](memBaseTokens.length); bool shouldDepositBaseTokens; for (uint8 i = 0; i < memBaseTokens.length; i++) { IERC20 token = memBaseTokens[i]; uint256 depositAmount = amounts[baseLPTokenIndex + i]; if (depositAmount > 0) { token.safeTransferFrom( msg.sender, address(this), depositAmount ); baseAmounts[i] = token.balanceOf(address(this)); // account for any fees on transfer // if there are any base Swap level tokens, flag it for deposits shouldDepositBaseTokens = true; } } if (shouldDepositBaseTokens) { // Deposit any base Swap level tokens and receive baseLPToken baseLPTokenAmount = baseSwap.addLiquidity( baseAmounts, 0, deadline ); } } uint256 metaLPTokenAmount; { // Transfer remaining meta level tokens from the caller uint256[] memory metaAmounts = new uint256[](metaTokens.length); for (uint8 i = 0; i < baseLPTokenIndex; i++) { IERC20 token = memMetaTokens[i]; uint256 depositAmount = amounts[i]; if (depositAmount > 0) { token.safeTransferFrom( msg.sender, address(this), depositAmount ); metaAmounts[i] = token.balanceOf(address(this)); // account for any fees on transfer } } // Update the baseLPToken amount that will be deposited metaAmounts[baseLPTokenIndex] = baseLPTokenAmount; // Deposit the meta level tokens and the baseLPToken metaLPTokenAmount = metaSwap.addLiquidity( metaAmounts, minToMint, deadline ); } // Transfer the meta lp token to the caller metaLPToken.safeTransfer(msg.sender, metaLPTokenAmount); return metaLPTokenAmount; } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external nonReentrant returns (uint256[] memory) { IERC20[] memory memBaseTokens = baseTokens; IERC20[] memory memMetaTokens = metaTokens; uint256[] memory totalRemovedAmounts; { uint256 numOfAllTokens = memBaseTokens.length + memMetaTokens.length - 1; require(minAmounts.length == numOfAllTokens, "out of range"); totalRemovedAmounts = new uint256[](numOfAllTokens); } // Transfer meta lp token from the caller to this metaLPToken.safeTransferFrom(msg.sender, address(this), amount); uint256 baseLPTokenAmount; { // Remove liquidity from the MetaSwap pool uint256[] memory removedAmounts; uint256 baseLPTokenIndex = memMetaTokens.length - 1; { uint256[] memory metaMinAmounts = new uint256[]( memMetaTokens.length ); for (uint8 i = 0; i < baseLPTokenIndex; i++) { metaMinAmounts[i] = minAmounts[i]; } removedAmounts = metaSwap.removeLiquidity( amount, metaMinAmounts, deadline ); } // Send the meta level tokens to the caller for (uint8 i = 0; i < baseLPTokenIndex; i++) { totalRemovedAmounts[i] = removedAmounts[i]; memMetaTokens[i].safeTransfer(msg.sender, removedAmounts[i]); } baseLPTokenAmount = removedAmounts[baseLPTokenIndex]; // Remove liquidity from the base Swap pool { uint256[] memory baseMinAmounts = new uint256[]( memBaseTokens.length ); for (uint8 i = 0; i < baseLPTokenIndex; i++) { baseMinAmounts[i] = minAmounts[baseLPTokenIndex + i]; } removedAmounts = baseSwap.removeLiquidity( baseLPTokenAmount, baseMinAmounts, deadline ); } // Send the base level tokens to the caller for (uint8 i = 0; i < memBaseTokens.length; i++) { totalRemovedAmounts[baseLPTokenIndex + i] = removedAmounts[i]; memBaseTokens[i].safeTransfer(msg.sender, removedAmounts[i]); } } return totalRemovedAmounts; } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external nonReentrant returns (uint256) { uint8 baseLPTokenIndex = uint8(metaTokens.length - 1); uint8 baseTokensLength = uint8(baseTokens.length); // Transfer metaLPToken from the caller metaLPToken.safeTransferFrom(msg.sender, address(this), tokenAmount); IERC20 token; if (tokenIndex < baseLPTokenIndex) { // When the desired token is meta level token, we can just call `removeLiquidityOneToken` directly metaSwap.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount, deadline ); token = metaTokens[tokenIndex]; } else if (tokenIndex < baseLPTokenIndex + baseTokensLength) { // When the desired token is a base level token, we need to first withdraw via baseLPToken, then withdraw // the desired token from the base Swap contract. uint256 removedBaseLPTokenAmount = metaSwap.removeLiquidityOneToken( tokenAmount, baseLPTokenIndex, 0, deadline ); baseSwap.removeLiquidityOneToken( removedBaseLPTokenAmount, tokenIndex - baseLPTokenIndex, minAmount, deadline ); token = baseTokens[tokenIndex - baseLPTokenIndex]; } else { revert("out of range"); } uint256 amountWithdrawn = token.balanceOf(address(this)); token.safeTransfer(msg.sender, amountWithdrawn); return amountWithdrawn; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external nonReentrant returns (uint256) { IERC20[] memory memBaseTokens = baseTokens; IERC20[] memory memMetaTokens = metaTokens; uint256[] memory metaAmounts = new uint256[](memMetaTokens.length); uint256[] memory baseAmounts = new uint256[](memBaseTokens.length); require( amounts.length == memBaseTokens.length + memMetaTokens.length - 1, "out of range" ); RemoveLiquidityImbalanceInfo memory v = RemoveLiquidityImbalanceInfo( baseSwap, metaSwap, metaLPToken, uint8(metaAmounts.length - 1), false, 0 ); for (uint8 i = 0; i < v.baseLPTokenIndex; i++) { metaAmounts[i] = amounts[i]; } for (uint8 i = 0; i < baseAmounts.length; i++) { baseAmounts[i] = amounts[v.baseLPTokenIndex + i]; if (baseAmounts[i] > 0) { v.withdrawFromBase = true; } } // Calculate how much base LP token we need to get the desired amount of underlying tokens if (v.withdrawFromBase) { metaAmounts[v.baseLPTokenIndex] = v .baseSwap .calculateTokenAmount(baseAmounts, false) .mul(10005) .div(10000); } // Transfer MetaSwap LP token from the caller to this contract v.metaLPToken.safeTransferFrom( msg.sender, address(this), maxBurnAmount ); // Withdraw the paired meta level tokens and the base LP token from the MetaSwap pool uint256 burnedMetaLPTokenAmount = v.metaSwap.removeLiquidityImbalance( metaAmounts, maxBurnAmount, deadline ); v.leftoverMetaLPTokenAmount = maxBurnAmount.sub( burnedMetaLPTokenAmount ); // If underlying tokens are desired, withdraw them from the base Swap pool if (v.withdrawFromBase) { v.baseSwap.removeLiquidityImbalance( baseAmounts, metaAmounts[v.baseLPTokenIndex], deadline ); // Base Swap may require LESS base LP token than the amount we have // In that case, deposit it to the MetaSwap pool. uint256[] memory leftovers = new uint256[](metaAmounts.length); IERC20 baseLPToken = memMetaTokens[v.baseLPTokenIndex]; uint256 leftoverBaseLPTokenAmount = baseLPToken.balanceOf( address(this) ); if (leftoverBaseLPTokenAmount > 0) { leftovers[v.baseLPTokenIndex] = leftoverBaseLPTokenAmount; v.leftoverMetaLPTokenAmount = v.leftoverMetaLPTokenAmount.add( v.metaSwap.addLiquidity(leftovers, 0, deadline) ); } } // Transfer all withdrawn tokens to the caller for (uint8 i = 0; i < amounts.length; i++) { IERC20 token; if (i < v.baseLPTokenIndex) { token = memMetaTokens[i]; } else { token = memBaseTokens[i - v.baseLPTokenIndex]; } if (amounts[i] > 0) { token.safeTransfer(msg.sender, amounts[i]); } } // If there were any extra meta lp token, transfer them back to the caller as well if (v.leftoverMetaLPTokenAmount > 0) { v.metaLPToken.safeTransfer(msg.sender, v.leftoverMetaLPTokenAmount); } return maxBurnAmount - v.leftoverMetaLPTokenAmount; } // VIEW FUNCTIONS /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running. When withdrawing from the base pool in imbalanced * fashion, the recommended slippage setting is 0.2% or higher. * * @dev This shouldn't be used outside frontends for user estimates. * * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256) { uint256[] memory metaAmounts = new uint256[](metaTokens.length); uint256[] memory baseAmounts = new uint256[](baseTokens.length); uint256 baseLPTokenIndex = metaAmounts.length - 1; for (uint8 i = 0; i < baseLPTokenIndex; i++) { metaAmounts[i] = amounts[i]; } for (uint8 i = 0; i < baseAmounts.length; i++) { baseAmounts[i] = amounts[baseLPTokenIndex + i]; } uint256 baseLPTokenAmount = baseSwap.calculateTokenAmount( baseAmounts, deposit ); metaAmounts[baseLPTokenIndex] = baseLPTokenAmount; return metaSwap.calculateTokenAmount(metaAmounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory) { uint256[] memory metaAmounts = metaSwap.calculateRemoveLiquidity( amount ); uint8 baseLPTokenIndex = uint8(metaAmounts.length - 1); uint256[] memory baseAmounts = baseSwap.calculateRemoveLiquidity( metaAmounts[baseLPTokenIndex] ); uint256[] memory totalAmounts = new uint256[]( baseLPTokenIndex + baseAmounts.length ); for (uint8 i = 0; i < baseLPTokenIndex; i++) { totalAmounts[i] = metaAmounts[i]; } for (uint8 i = 0; i < baseAmounts.length; i++) { totalAmounts[baseLPTokenIndex + i] = baseAmounts[i]; } return totalAmounts; } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { uint8 baseLPTokenIndex = uint8(metaTokens.length - 1); if (tokenIndex < baseLPTokenIndex) { return metaSwap.calculateRemoveLiquidityOneToken( tokenAmount, tokenIndex ); } else { uint256 baseLPTokenAmount = metaSwap .calculateRemoveLiquidityOneToken( tokenAmount, baseLPTokenIndex ); return baseSwap.calculateRemoveLiquidityOneToken( baseLPTokenAmount, tokenIndex - baseLPTokenIndex ); } } /** * @notice Returns the address of the pooled token at given index. Reverts if tokenIndex is out of range. * This is a flattened representation of the pooled tokens. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) external view returns (IERC20) { require(index < tokens.length, "index out of range"); return tokens[index]; } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { return metaSwap.calculateSwapUnderlying(tokenIndexFrom, tokenIndexTo, dx); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./ISwap.sol"; interface IMetaSwap { // pool data view functions function getA() external view returns (uint256); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateSwapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) external; function initializeMetaSwap( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress, ISwap baseSwap ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function swapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "./interfaces/ISwap.sol"; import "./interfaces/IMetaSwap.sol"; contract SwapDeployer is Ownable { event NewSwapPool( address indexed deployer, address swapAddress, IERC20[] pooledTokens ); event NewClone(address indexed target, address cloneAddress); constructor() public Ownable() {} function clone(address target) external returns (address) { address newClone = _clone(target); emit NewClone(target, newClone); return newClone; } function _clone(address target) internal returns (address) { return Clones.clone(target); } function deploy( address swapAddress, IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) external returns (address) { address swapClone = _clone(swapAddress); ISwap(swapClone).initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress ); Ownable(swapClone).transferOwnership(owner()); emit NewSwapPool(msg.sender, swapClone, _pooledTokens); return swapClone; } function deployMetaSwap( address metaSwapAddress, IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress, ISwap baseSwap ) external returns (address) { address metaSwapClone = _clone(metaSwapAddress); IMetaSwap(metaSwapClone).initializeMetaSwap( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress, baseSwap ); Ownable(metaSwapClone).transferOwnership(owner()); emit NewSwapPool(msg.sender, metaSwapClone, _pooledTokens); return metaSwapClone; } } // 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.12; import "synthetix/contracts/interfaces/ISynthetix.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "../interfaces/ISwap.sol"; /** * @title SynthSwapper * @notice Replacement of Virtual Synths in favor of gas savings. Allows swapping synths via the Synthetix protocol * or Saddle's pools. The `Bridge.sol` contract will deploy minimal clones of this contract upon initiating * any cross-asset swaps. */ contract SynthSwapper is Initializable { using SafeERC20 for IERC20; address payable owner; // SYNTHETIX points to `ProxyERC20` (0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F). // This contract is a proxy of `Synthetix` and is used to exchange synths. ISynthetix public constant SYNTHETIX = ISynthetix(0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F); // "SADDLE" in bytes32 form bytes32 public constant TRACKING = 0x534144444c450000000000000000000000000000000000000000000000000000; /** * @notice Initializes the contract when deploying this directly. This prevents * others from calling initialize() on the target contract and setting themself as the owner. */ constructor() public { initialize(); } /** * @notice This modifier checks if the caller is the owner */ modifier onlyOwner() { require(msg.sender == owner, "is not owner"); _; } /** * @notice Sets the `owner` as the caller of this function */ function initialize() public initializer { require(owner == address(0), "owner already set"); owner = msg.sender; } /** * @notice Swaps the synth to another synth via the Synthetix protocol. * @param sourceKey currency key of the source synth * @param synthAmount amount of the synth to swap * @param destKey currency key of the destination synth * @return amount of the destination synth received */ function swapSynth( bytes32 sourceKey, uint256 synthAmount, bytes32 destKey ) external onlyOwner returns (uint256) { return SYNTHETIX.exchangeWithTracking( sourceKey, synthAmount, destKey, msg.sender, TRACKING ); } /** * @notice Approves the given `tokenFrom` and swaps it to another token via the given `swap` pool. * @param swap the address of a pool to swap through * @param tokenFrom the address of the stored synth * @param tokenFromIndex the index of the token to swap from * @param tokenToIndex the token the user wants to swap to * @param tokenFromAmount the amount of the token to swap * @param minAmount the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction * @param recipient the address of the recipient */ function swapSynthToToken( ISwap swap, IERC20 tokenFrom, uint8 tokenFromIndex, uint8 tokenToIndex, uint256 tokenFromAmount, uint256 minAmount, uint256 deadline, address recipient ) external onlyOwner returns (IERC20, uint256) { tokenFrom.approve(address(swap), tokenFromAmount); swap.swap( tokenFromIndex, tokenToIndex, tokenFromAmount, minAmount, deadline ); IERC20 tokenTo = swap.getToken(tokenToIndex); uint256 balance = tokenTo.balanceOf(address(this)); tokenTo.safeTransfer(recipient, balance); return (tokenTo, balance); } /** * @notice Withdraws the given amount of `token` to the `recipient`. * @param token the address of the token to withdraw * @param recipient the address of the account to receive the token * @param withdrawAmount the amount of the token to withdraw * @param shouldDestroy whether this contract should be destroyed after this call */ function withdraw( IERC20 token, address recipient, uint256 withdrawAmount, bool shouldDestroy ) external onlyOwner { token.safeTransfer(recipient, withdrawAmount); if (shouldDestroy) { _destroy(); } } /** * @notice Destroys this contract. Only owner can call this function. */ function destroy() external onlyOwner { _destroy(); } function _destroy() internal { selfdestruct(msg.sender); } } pragma solidity >=0.4.24; import "./ISynth.sol"; import "./IVirtualSynth.sol"; // https://docs.synthetix.io/contracts/source/interfaces/isynthetix interface ISynthetix { // Views function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid); function availableCurrencyKeys() external view returns (bytes32[] memory); function availableSynthCount() external view returns (uint); function availableSynths(uint index) external view returns (ISynth); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint); function isWaitingPeriod(bytes32 currencyKey) external view returns (bool); function maxIssuableSynths(address issuer) external view returns (uint maxIssuable); function remainingIssuableSynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function synths(bytes32 currencyKey) external view returns (ISynth); function synthsByAddress(address synthAddress) external view returns (bytes32); function totalIssuedSynths(bytes32 currencyKey) external view returns (uint); function totalIssuedSynthsExcludeEtherCollateral(bytes32 currencyKey) external view returns (uint); function transferableSynthetix(address account) external view returns (uint transferable); // Mutative Functions function burnSynths(uint amount) external; function burnSynthsOnBehalf(address burnForAddress, uint amount) external; function burnSynthsToTarget() external; function burnSynthsToTargetOnBehalf(address burnForAddress) external; function exchange( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeOnBehalf( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeWithTracking( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeOnBehalfWithTracking( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithVirtual( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualSynth vSynth); function issueMaxSynths() external; function issueMaxSynthsOnBehalf(address issueForAddress) external; function issueSynths(uint amount) external; function issueSynthsOnBehalf(address issueForAddress, uint amount) external; function mint() external returns (bool); function settle(bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); // Liquidations function liquidateDelinquentAccount(address account, uint susdAmount) external returns (bool); // Restricted Functions function mintSecondary(address account, uint amount) external; function mintSecondaryRewards(uint amount) external; function burnSecondary(address account, uint amount) external; } pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/isynth interface ISynth { // Views function currencyKey() external view returns (bytes32); function transferableSynths(address account) external view returns (uint); // Mutative functions function transferAndSettle(address to, uint value) external returns (bool); function transferFromAndSettle( address from, address to, uint value ) external returns (bool); // Restricted: used internally to Synthetix function burn(address account, uint amount) external; function issue(address account, uint amount) external; } pragma solidity >=0.4.24; import "./ISynth.sol"; interface IVirtualSynth { // Views function balanceOfUnderlying(address account) external view returns (uint); function rate() external view returns (uint); function readyToSettle() external view returns (bool); function secsLeftInWaitingPeriod() external view returns (uint); function settled() external view returns (bool); function synth() external view returns (ISynth); // Mutative functions function settle(address account) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/ISwapV1.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. * @dev Only Swap contracts should initialize and own LPToken contracts. */ contract LPTokenV1 is ERC20BurnableUpgradeable, OwnableUpgradeable { using SafeMathUpgradeable for uint256; /** * @notice Initializes this LPToken contract with the given name and symbol * @dev The caller of this function will become the owner. A Swap contract should call this * in its initializer function. * @param name name of this token * @param symbol symbol of this token */ function initialize(string memory name, string memory symbol) external initializer returns (bool) { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); __Ownable_init_unchained(); return true; } /** * @notice Mints the given amount of LPToken to the recipient. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "LPToken: cannot mint 0"); _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that Swap.updateUserWithdrawFees are called everytime. * This assumes the owner is set to a Swap contract's address. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable) { super._beforeTokenTransfer(from, to, amount); require(to != address(this), "LPToken: cannot send to itself"); ISwapV1(owner()).updateUserWithdrawFee(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./IAllowlist.sol"; interface ISwapV1 { // pool data view functions function getA() external view returns (uint256); function getAllowlist() external view returns (IAllowlist); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256); function calculateRemoveLiquidity(address account, uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 a, uint256 fee, uint256 adminFee, uint256 withdrawFee, address lpTokenTargetAddress ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); // withdraw fee update function function updateUserWithdrawFee(address recipient, uint256 transferAmount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "./interfaces/ISwapV1.sol"; contract SwapDeployerV1 is Ownable { event NewSwapPool( address indexed deployer, address swapAddress, IERC20[] pooledTokens ); constructor() public Ownable() {} function deploy( address swapAddress, IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) external returns (address) { address swapClone = Clones.clone(swapAddress); ISwapV1(swapClone).initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, _withdrawFee, lpTokenTargetAddress ); Ownable(swapClone).transferOwnership(owner()); emit NewSwapPool(msg.sender, swapClone, _pooledTokens); return swapClone; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "synthetix/contracts/interfaces/IAddressResolver.sol"; import "synthetix/contracts/interfaces/IExchanger.sol"; import "synthetix/contracts/interfaces/IExchangeRates.sol"; import "../interfaces/ISwap.sol"; import "./SynthSwapper.sol"; contract Proxy { address public target; } contract Target { address public proxy; } /** * @title Bridge * @notice This contract is responsible for cross-asset swaps using the Synthetix protocol as the bridging exchange. * There are three types of supported cross-asset swaps, tokenToSynth, synthToToken, and tokenToToken. * * 1) tokenToSynth * Swaps a supported token in a saddle pool to any synthetic asset (e.g. tBTC -> sAAVE). * * 2) synthToToken * Swaps any synthetic asset to a suported token in a saddle pool (e.g. sDEFI -> USDC). * * 3) tokenToToken * Swaps a supported token in a saddle pool to one in another pool (e.g. renBTC -> DAI). * * Due to the settlement periods of synthetic assets, the users must wait until the trades can be completed. * Users will receive an ERC721 token that represents pending cross-asset swap. Once the waiting period is over, * the trades can be settled and completed by calling the `completeToSynth` or the `completeToToken` function. * In the cases of pending `synthToToken` or `tokenToToken` swaps, the owners of the pending swaps can also choose * to withdraw the bridging synthetic assets instead of completing the swap. */ contract Bridge is ERC721 { using SafeMath for uint256; using SafeERC20 for IERC20; event SynthIndex( address indexed swap, uint8 synthIndex, bytes32 currencyKey, address synthAddress ); event TokenToSynth( address indexed requester, uint256 indexed itemId, ISwap swapPool, uint8 tokenFromIndex, uint256 tokenFromInAmount, bytes32 synthToKey ); event SynthToToken( address indexed requester, uint256 indexed itemId, ISwap swapPool, bytes32 synthFromKey, uint256 synthFromInAmount, uint8 tokenToIndex ); event TokenToToken( address indexed requester, uint256 indexed itemId, ISwap[2] swapPools, uint8 tokenFromIndex, uint256 tokenFromAmount, uint8 tokenToIndex ); event Settle( address indexed requester, uint256 indexed itemId, IERC20 settleFrom, uint256 settleFromAmount, IERC20 settleTo, uint256 settleToAmount, bool isFinal ); event Withdraw( address indexed requester, uint256 indexed itemId, IERC20 synth, uint256 synthAmount, bool isFinal ); // The addresses for all Synthetix contracts can be found in the below URL. // https://docs.synthetix.io/addresses/#mainnet-contracts // // Since the Synthetix protocol is upgradable, we must use the proxy pairs of each contract such that // the composability is not broken after the protocol upgrade. // // SYNTHETIX_RESOLVER points to `ReadProxyAddressResolver` (0x4E3b31eB0E5CB73641EE1E65E7dCEFe520bA3ef2). // This contract is a read proxy of `AddressResolver` which is responsible for storing the addresses of the contracts // used by the Synthetix protocol. IAddressResolver public constant SYNTHETIX_RESOLVER = IAddressResolver(0x4E3b31eB0E5CB73641EE1E65E7dCEFe520bA3ef2); // EXCHANGER points to `Exchanger`. There is no proxy pair for this contract so we need to update this variable // when the protocol is upgraded. This contract is used to settle synths held by SynthSwapper. IExchanger public exchanger; // CONSTANTS // Available types of cross-asset swaps enum PendingSwapType { Null, TokenToSynth, SynthToToken, TokenToToken } uint256 public constant MAX_UINT256 = 2**256 - 1; uint8 public constant MAX_UINT8 = 2**8 - 1; bytes32 public constant EXCHANGE_RATES_NAME = "ExchangeRates"; bytes32 public constant EXCHANGER_NAME = "Exchanger"; address public immutable SYNTH_SWAPPER_MASTER; // MAPPINGS FOR STORING PENDING SETTLEMENTS // The below two mappings never share the same key. mapping(uint256 => PendingToSynthSwap) public pendingToSynthSwaps; mapping(uint256 => PendingToTokenSwap) public pendingToTokenSwaps; uint256 public pendingSwapsLength; mapping(uint256 => PendingSwapType) private pendingSwapType; // MAPPINGS FOR STORING SYNTH INFO mapping(address => SwapContractInfo) private swapContracts; // Structs holding information about pending settlements struct PendingToSynthSwap { SynthSwapper swapper; bytes32 synthKey; } struct PendingToTokenSwap { SynthSwapper swapper; bytes32 synthKey; ISwap swap; uint8 tokenToIndex; } struct SwapContractInfo { // index of the supported synth + 1 uint8 synthIndexPlusOne; // address of the supported synth address synthAddress; // bytes32 key of the supported synth bytes32 synthKey; // array of tokens supported by the contract IERC20[] tokens; } /** * @notice Deploys this contract and initializes the master version of the SynthSwapper contract. The address to * the Synthetix protocol's Exchanger contract is also set on deployment. */ constructor(address synthSwapperAddress) public ERC721("Saddle Cross-Asset Swap", "SaddleSynthSwap") { SYNTH_SWAPPER_MASTER = synthSwapperAddress; updateExchangerCache(); } /** * @notice Returns the address of the proxy contract targeting the synthetic asset with the given `synthKey`. * @param synthKey the currency key of the synth * @return address of the proxy contract */ function getProxyAddressFromTargetSynthKey(bytes32 synthKey) public view returns (IERC20) { return IERC20(Target(SYNTHETIX_RESOLVER.getSynth(synthKey)).proxy()); } /** * @notice Returns various information of a pending swap represented by the given `itemId`. Information includes * the type of the pending swap, the number of seconds left until it can be settled, the address and the balance * of the synth this swap currently holds, and the address of the destination token. * @param itemId ID of the pending swap * @return swapType the type of the pending virtual swap, * secsLeft number of seconds left until this swap can be settled, * synth address of the synth this swap uses, * synthBalance amount of the synth this swap holds, * tokenTo the address of the destination token */ function getPendingSwapInfo(uint256 itemId) external view returns ( PendingSwapType swapType, uint256 secsLeft, address synth, uint256 synthBalance, address tokenTo ) { swapType = pendingSwapType[itemId]; require(swapType != PendingSwapType.Null, "invalid itemId"); SynthSwapper synthSwapper; bytes32 synthKey; if (swapType == PendingSwapType.TokenToSynth) { synthSwapper = pendingToSynthSwaps[itemId].swapper; synthKey = pendingToSynthSwaps[itemId].synthKey; synth = address(getProxyAddressFromTargetSynthKey(synthKey)); tokenTo = synth; } else { PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; synthSwapper = pendingToTokenSwap.swapper; synthKey = pendingToTokenSwap.synthKey; synth = address(getProxyAddressFromTargetSynthKey(synthKey)); tokenTo = address( swapContracts[address(pendingToTokenSwap.swap)].tokens[ pendingToTokenSwap.tokenToIndex ] ); } secsLeft = exchanger.maxSecsLeftInWaitingPeriod( address(synthSwapper), synthKey ); synthBalance = IERC20(synth).balanceOf(address(synthSwapper)); } // Settles the synth only. function _settle(address synthOwner, bytes32 synthKey) internal { // Settle synth exchanger.settle(synthOwner, synthKey); } /** * @notice Settles and withdraws the synthetic asset without swapping it to a token in a Saddle pool. Only the owner * of the ERC721 token of `itemId` can call this function. Reverts if the given `itemId` does not represent a * `synthToToken` or a `tokenToToken` swap. * @param itemId ID of the pending swap * @param amount the amount of the synth to withdraw */ function withdraw(uint256 itemId, uint256 amount) external { address nftOwner = ownerOf(itemId); require(nftOwner == msg.sender, "not owner"); require( pendingSwapType[itemId] > PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; _settle( address(pendingToTokenSwap.swapper), pendingToTokenSwap.synthKey ); IERC20 synth = getProxyAddressFromTargetSynthKey( pendingToTokenSwap.synthKey ); bool shouldDestroy; if (amount >= synth.balanceOf(address(pendingToTokenSwap.swapper))) { _burn(itemId); delete pendingToTokenSwaps[itemId]; delete pendingSwapType[itemId]; shouldDestroy = true; } pendingToTokenSwap.swapper.withdraw( synth, nftOwner, amount, shouldDestroy ); emit Withdraw(msg.sender, itemId, synth, amount, shouldDestroy); } /** * @notice Completes the pending `tokenToSynth` swap by settling and withdrawing the synthetic asset. * Reverts if the given `itemId` does not represent a `tokenToSynth` swap. * @param itemId ERC721 token ID representing a pending `tokenToSynth` swap */ function completeToSynth(uint256 itemId) external { address nftOwner = ownerOf(itemId); require(nftOwner == msg.sender, "not owner"); require( pendingSwapType[itemId] == PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToSynthSwap memory pendingToSynthSwap = pendingToSynthSwaps[ itemId ]; _settle( address(pendingToSynthSwap.swapper), pendingToSynthSwap.synthKey ); IERC20 synth = getProxyAddressFromTargetSynthKey( pendingToSynthSwap.synthKey ); // Burn the corresponding ERC721 token and delete storage for gas _burn(itemId); delete pendingToTokenSwaps[itemId]; delete pendingSwapType[itemId]; // After settlement, withdraw the synth and send it to the recipient uint256 synthBalance = synth.balanceOf( address(pendingToSynthSwap.swapper) ); pendingToSynthSwap.swapper.withdraw( synth, nftOwner, synthBalance, true ); emit Settle( msg.sender, itemId, synth, synthBalance, synth, synthBalance, true ); } /** * @notice Calculates the expected amount of the token to receive on calling `completeToToken()` with * the given `swapAmount`. * @param itemId ERC721 token ID representing a pending `SynthToToken` or `TokenToToken` swap * @param swapAmount the amount of bridging synth to swap from * @return expected amount of the token the user will receive */ function calcCompleteToToken(uint256 itemId, uint256 swapAmount) external view returns (uint256) { require( pendingSwapType[itemId] > PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; return pendingToTokenSwap.swap.calculateSwap( getSynthIndex(pendingToTokenSwap.swap), pendingToTokenSwap.tokenToIndex, swapAmount ); } /** * @notice Completes the pending `SynthToToken` or `TokenToToken` swap by settling the bridging synth and swapping * it to the desired token. Only the owners of the pending swaps can call this function. * @param itemId ERC721 token ID representing a pending `SynthToToken` or `TokenToToken` swap * @param swapAmount the amount of bridging synth to swap from * @param minAmount the minimum amount of the token to receive - reverts if this amount is not reached * @param deadline the timestamp representing the deadline for this transaction - reverts if deadline is not met */ function completeToToken( uint256 itemId, uint256 swapAmount, uint256 minAmount, uint256 deadline ) external { require(swapAmount != 0, "amount must be greater than 0"); address nftOwner = ownerOf(itemId); require(msg.sender == nftOwner, "must own itemId"); require( pendingSwapType[itemId] > PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; _settle( address(pendingToTokenSwap.swapper), pendingToTokenSwap.synthKey ); IERC20 synth = getProxyAddressFromTargetSynthKey( pendingToTokenSwap.synthKey ); bool shouldDestroyClone; if ( swapAmount >= synth.balanceOf(address(pendingToTokenSwap.swapper)) ) { _burn(itemId); delete pendingToTokenSwaps[itemId]; delete pendingSwapType[itemId]; shouldDestroyClone = true; } // Try swapping the synth to the desired token via the stored swap pool contract // If the external call succeeds, send the token to the owner of token with itemId. (IERC20 tokenTo, uint256 amountOut) = pendingToTokenSwap .swapper .swapSynthToToken( pendingToTokenSwap.swap, synth, getSynthIndex(pendingToTokenSwap.swap), pendingToTokenSwap.tokenToIndex, swapAmount, minAmount, deadline, nftOwner ); if (shouldDestroyClone) { pendingToTokenSwap.swapper.destroy(); } emit Settle( msg.sender, itemId, synth, swapAmount, tokenTo, amountOut, shouldDestroyClone ); } // Add the given pending synth settlement struct to the list function _addToPendingSynthSwapList( PendingToSynthSwap memory pendingToSynthSwap ) internal returns (uint256) { require( pendingSwapsLength < MAX_UINT256, "pendingSwapsLength reached max size" ); pendingToSynthSwaps[pendingSwapsLength] = pendingToSynthSwap; return pendingSwapsLength++; } // Add the given pending synth to token settlement struct to the list function _addToPendingSynthToTokenSwapList( PendingToTokenSwap memory pendingToTokenSwap ) internal returns (uint256) { require( pendingSwapsLength < MAX_UINT256, "pendingSwapsLength reached max size" ); pendingToTokenSwaps[pendingSwapsLength] = pendingToTokenSwap; return pendingSwapsLength++; } /** * @notice Calculates the expected amount of the desired synthetic asset the caller will receive after completing * a `TokenToSynth` swap with the given parameters. This calculation does not consider the settlement periods. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param tokenFromIndex the index of the token to swap from * @param synthOutKey the currency key of the desired synthetic asset * @param tokenInAmount the amount of the token to swap form * @return the expected amount of the desired synth */ function calcTokenToSynth( ISwap swap, uint8 tokenFromIndex, bytes32 synthOutKey, uint256 tokenInAmount ) external view returns (uint256) { uint8 mediumSynthIndex = getSynthIndex(swap); uint256 expectedMediumSynthAmount = swap.calculateSwap( tokenFromIndex, mediumSynthIndex, tokenInAmount ); bytes32 mediumSynthKey = getSynthKey(swap); IExchangeRates exchangeRates = IExchangeRates( SYNTHETIX_RESOLVER.getAddress(EXCHANGE_RATES_NAME) ); return exchangeRates.effectiveValue( mediumSynthKey, expectedMediumSynthAmount, synthOutKey ); } /** * @notice Initiates a cross-asset swap from a token supported in the `swap` pool to any synthetic asset. * The caller will receive an ERC721 token representing their ownership of the pending cross-asset swap. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param tokenFromIndex the index of the token to swap from * @param synthOutKey the currency key of the desired synthetic asset * @param tokenInAmount the amount of the token to swap form * @param minAmount the amount of the token to swap form * @return ID of the ERC721 token sent to the caller */ function tokenToSynth( ISwap swap, uint8 tokenFromIndex, bytes32 synthOutKey, uint256 tokenInAmount, uint256 minAmount ) external returns (uint256) { require(tokenInAmount != 0, "amount must be greater than 0"); // Create a SynthSwapper clone SynthSwapper synthSwapper = SynthSwapper( Clones.clone(SYNTH_SWAPPER_MASTER) ); synthSwapper.initialize(); // Add the synthswapper to the pending settlement list uint256 itemId = _addToPendingSynthSwapList( PendingToSynthSwap(synthSwapper, synthOutKey) ); pendingSwapType[itemId] = PendingSwapType.TokenToSynth; // Mint an ERC721 token that represents ownership of the pending synth settlement to msg.sender _mint(msg.sender, itemId); // Transfer token from msg.sender IERC20 tokenFrom = swapContracts[address(swap)].tokens[tokenFromIndex]; // revert when token not found in swap pool tokenFrom.safeTransferFrom(msg.sender, address(this), tokenInAmount); tokenInAmount = tokenFrom.balanceOf(address(this)); // Swap the synth to the medium synth uint256 mediumSynthAmount = swap.swap( tokenFromIndex, getSynthIndex(swap), tokenInAmount, 0, block.timestamp ); // Swap synths via Synthetix network IERC20(getSynthAddress(swap)).safeTransfer( address(synthSwapper), mediumSynthAmount ); require( synthSwapper.swapSynth( getSynthKey(swap), mediumSynthAmount, synthOutKey ) >= minAmount, "minAmount not reached" ); // Emit TokenToSynth event with relevant data emit TokenToSynth( msg.sender, itemId, swap, tokenFromIndex, tokenInAmount, synthOutKey ); return (itemId); } /** * @notice Calculates the expected amount of the desired token the caller will receive after completing * a `SynthToToken` swap with the given parameters. This calculation does not consider the settlement periods or * any potential changes of the `swap` pool composition. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param synthInKey the currency key of the synth to swap from * @param tokenToIndex the index of the token to swap to * @param synthInAmount the amount of the synth to swap form * @return the expected amount of the bridging synth and the expected amount of the desired token */ function calcSynthToToken( ISwap swap, bytes32 synthInKey, uint8 tokenToIndex, uint256 synthInAmount ) external view returns (uint256, uint256) { IExchangeRates exchangeRates = IExchangeRates( SYNTHETIX_RESOLVER.getAddress(EXCHANGE_RATES_NAME) ); uint8 mediumSynthIndex = getSynthIndex(swap); bytes32 mediumSynthKey = getSynthKey(swap); require(synthInKey != mediumSynthKey, "use normal swap"); uint256 expectedMediumSynthAmount = exchangeRates.effectiveValue( synthInKey, synthInAmount, mediumSynthKey ); return ( expectedMediumSynthAmount, swap.calculateSwap( mediumSynthIndex, tokenToIndex, expectedMediumSynthAmount ) ); } /** * @notice Initiates a cross-asset swap from a synthetic asset to a supported token. The caller will receive * an ERC721 token representing their ownership of the pending cross-asset swap. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param synthInKey the currency key of the synth to swap from * @param tokenToIndex the index of the token to swap to * @param synthInAmount the amount of the synth to swap form * @param minMediumSynthAmount the minimum amount of the bridging synth at pre-settlement stage * @return the ID of the ERC721 token sent to the caller */ function synthToToken( ISwap swap, bytes32 synthInKey, uint8 tokenToIndex, uint256 synthInAmount, uint256 minMediumSynthAmount ) external returns (uint256) { require(synthInAmount != 0, "amount must be greater than 0"); bytes32 mediumSynthKey = getSynthKey(swap); require( synthInKey != mediumSynthKey, "synth is supported via normal swap" ); // Create a SynthSwapper clone SynthSwapper synthSwapper = SynthSwapper( Clones.clone(SYNTH_SWAPPER_MASTER) ); synthSwapper.initialize(); // Add the synthswapper to the pending synth to token settlement list uint256 itemId = _addToPendingSynthToTokenSwapList( PendingToTokenSwap(synthSwapper, mediumSynthKey, swap, tokenToIndex) ); pendingSwapType[itemId] = PendingSwapType.SynthToToken; // Mint an ERC721 token that represents ownership of the pending synth to token settlement to msg.sender _mint(msg.sender, itemId); // Receive synth from the user and swap it to another synth IERC20 synthFrom = getProxyAddressFromTargetSynthKey(synthInKey); synthFrom.safeTransferFrom(msg.sender, address(this), synthInAmount); synthFrom.safeTransfer(address(synthSwapper), synthInAmount); require( synthSwapper.swapSynth(synthInKey, synthInAmount, mediumSynthKey) >= minMediumSynthAmount, "minMediumSynthAmount not reached" ); // Emit SynthToToken event with relevant data emit SynthToToken( msg.sender, itemId, swap, synthInKey, synthInAmount, tokenToIndex ); return (itemId); } /** * @notice Calculates the expected amount of the desired token the caller will receive after completing * a `TokenToToken` swap with the given parameters. This calculation does not consider the settlement periods or * any potential changes of the pool compositions. * @param swaps the addresses of the two Saddle pools used to do the cross-asset swap * @param tokenFromIndex the index of the token in the first `swaps` pool to swap from * @param tokenToIndex the index of the token in the second `swaps` pool to swap to * @param tokenFromAmount the amount of the token to swap from * @return the expected amount of bridging synth at pre-settlement stage and the expected amount of the desired * token */ function calcTokenToToken( ISwap[2] calldata swaps, uint8 tokenFromIndex, uint8 tokenToIndex, uint256 tokenFromAmount ) external view returns (uint256, uint256) { IExchangeRates exchangeRates = IExchangeRates( SYNTHETIX_RESOLVER.getAddress(EXCHANGE_RATES_NAME) ); uint256 firstSynthAmount = swaps[0].calculateSwap( tokenFromIndex, getSynthIndex(swaps[0]), tokenFromAmount ); uint256 mediumSynthAmount = exchangeRates.effectiveValue( getSynthKey(swaps[0]), firstSynthAmount, getSynthKey(swaps[1]) ); return ( mediumSynthAmount, swaps[1].calculateSwap( getSynthIndex(swaps[1]), tokenToIndex, mediumSynthAmount ) ); } /** * @notice Initiates a cross-asset swap from a token in one Saddle pool to one in another. The caller will receive * an ERC721 token representing their ownership of the pending cross-asset swap. * @param swaps the addresses of the two Saddle pools used to do the cross-asset swap * @param tokenFromIndex the index of the token in the first `swaps` pool to swap from * @param tokenToIndex the index of the token in the second `swaps` pool to swap to * @param tokenFromAmount the amount of the token to swap from * @param minMediumSynthAmount the minimum amount of the bridging synth at pre-settlement stage * @return the ID of the ERC721 token sent to the caller */ function tokenToToken( ISwap[2] calldata swaps, uint8 tokenFromIndex, uint8 tokenToIndex, uint256 tokenFromAmount, uint256 minMediumSynthAmount ) external returns (uint256) { // Create a SynthSwapper clone require(tokenFromAmount != 0, "amount must be greater than 0"); SynthSwapper synthSwapper = SynthSwapper( Clones.clone(SYNTH_SWAPPER_MASTER) ); synthSwapper.initialize(); bytes32 mediumSynthKey = getSynthKey(swaps[1]); // Add the synthswapper to the pending synth to token settlement list uint256 itemId = _addToPendingSynthToTokenSwapList( PendingToTokenSwap( synthSwapper, mediumSynthKey, swaps[1], tokenToIndex ) ); pendingSwapType[itemId] = PendingSwapType.TokenToToken; // Mint an ERC721 token that represents ownership of the pending swap to msg.sender _mint(msg.sender, itemId); // Receive token from the user ISwap swap = swaps[0]; { IERC20 tokenFrom = swapContracts[address(swap)].tokens[ tokenFromIndex ]; tokenFrom.safeTransferFrom( msg.sender, address(this), tokenFromAmount ); } uint256 firstSynthAmount = swap.swap( tokenFromIndex, getSynthIndex(swap), tokenFromAmount, 0, block.timestamp ); // Swap the synth to another synth IERC20(getSynthAddress(swap)).safeTransfer( address(synthSwapper), firstSynthAmount ); require( synthSwapper.swapSynth( getSynthKey(swap), firstSynthAmount, mediumSynthKey ) >= minMediumSynthAmount, "minMediumSynthAmount not reached" ); // Emit TokenToToken event with relevant data emit TokenToToken( msg.sender, itemId, swaps, tokenFromIndex, tokenFromAmount, tokenToIndex ); return (itemId); } /** * @notice Registers the index and the address of the supported synth from the given `swap` pool. The matching currency key must * be supplied for a successful registration. * @param swap the address of the pool that contains the synth * @param synthIndex the index of the supported synth in the given `swap` pool * @param currencyKey the currency key of the synth in bytes32 form */ function setSynthIndex( ISwap swap, uint8 synthIndex, bytes32 currencyKey ) external { require(synthIndex < MAX_UINT8, "index is too large"); SwapContractInfo storage swapContractInfo = swapContracts[ address(swap) ]; // Check if the pool has already been added require(swapContractInfo.synthIndexPlusOne == 0, "Pool already added"); // Ensure the synth with the same currency key exists at the given `synthIndex` IERC20 synth = swap.getToken(synthIndex); require( ISynth(Proxy(address(synth)).target()).currencyKey() == currencyKey, "currencyKey does not match" ); swapContractInfo.synthIndexPlusOne = synthIndex + 1; swapContractInfo.synthAddress = address(synth); swapContractInfo.synthKey = currencyKey; swapContractInfo.tokens = new IERC20[](0); for (uint8 i = 0; i < MAX_UINT8; i++) { IERC20 token; if (i == synthIndex) { token = synth; } else { try swap.getToken(i) returns (IERC20 token_) { token = token_; } catch { break; } } swapContractInfo.tokens.push(token); token.safeApprove(address(swap), MAX_UINT256); } emit SynthIndex(address(swap), synthIndex, currencyKey, address(synth)); } /** * @notice Returns the index of the supported synth in the given `swap` pool. Reverts if the `swap` pool * is not registered. * @param swap the address of the pool that contains the synth * @return the index of the supported synth */ function getSynthIndex(ISwap swap) public view returns (uint8) { uint8 synthIndexPlusOne = swapContracts[address(swap)] .synthIndexPlusOne; require(synthIndexPlusOne > 0, "synth index not found for given pool"); return synthIndexPlusOne - 1; } /** * @notice Returns the address of the supported synth in the given `swap` pool. Reverts if the `swap` pool * is not registered. * @param swap the address of the pool that contains the synth * @return the address of the supported synth */ function getSynthAddress(ISwap swap) public view returns (address) { address synthAddress = swapContracts[address(swap)].synthAddress; require( synthAddress != address(0), "synth addr not found for given pool" ); return synthAddress; } /** * @notice Returns the currency key of the supported synth in the given `swap` pool. Reverts if the `swap` pool * is not registered. * @param swap the address of the pool that contains the synth * @return the currency key of the supported synth */ function getSynthKey(ISwap swap) public view returns (bytes32) { bytes32 synthKey = swapContracts[address(swap)].synthKey; require(synthKey != 0x0, "synth key not found for given pool"); return synthKey; } /** * @notice Updates the stored address of the `EXCHANGER` contract. When the Synthetix team upgrades their protocol, * a new Exchanger contract is deployed. This function manually updates the stored address. */ function updateExchangerCache() public { exchanger = IExchanger(SYNTHETIX_RESOLVER.getAddress(EXCHANGER_NAME)); } } // 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 { } } pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/iaddressresolver interface IAddressResolver { function getAddress(bytes32 name) external view returns (address); function getSynth(bytes32 key) external view returns (address); function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address); } pragma solidity >=0.4.24; import "./IVirtualSynth.sol"; // https://docs.synthetix.io/contracts/source/interfaces/iexchanger interface IExchanger { // Views function calculateAmountAfterSettlement( address from, bytes32 currencyKey, uint amount, uint refunded ) external view returns (uint amountAfterSettlement); function isSynthRateInvalid(bytes32 currencyKey) external view returns (bool); function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint); function settlementOwing(address account, bytes32 currencyKey) external view returns ( uint reclaimAmount, uint rebateAmount, uint numEntries ); function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool); function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view returns (uint exchangeFeeRate); function getAmountsForExchange( uint sourceAmount, bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey ) external view returns ( uint amountReceived, uint fee, uint exchangeFeeRate ); function priceDeviationThresholdFactor() external view returns (uint); function waitingPeriodSecs() external view returns (uint); // Mutative functions function exchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external returns (uint amountReceived); function exchangeOnBehalf( address exchangeForAddress, address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeWithTracking( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeOnBehalfWithTracking( address exchangeForAddress, address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithVirtual( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualSynth vSynth); function settle(address from, bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); function setLastExchangeRateForSynth(bytes32 currencyKey, uint rate) external; function suspendSynthWithInvalidRate(bytes32 currencyKey) external; } pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/iexchangerates interface IExchangeRates { // Structs struct RateAndUpdatedTime { uint216 rate; uint40 time; } struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozenAtUpperLimit; bool frozenAtLowerLimit; } // Views function aggregators(bytes32 currencyKey) external view returns (address); function aggregatorWarningFlags() external view returns (address); function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool); function canFreezeRate(bytes32 currencyKey) external view returns (bool); function currentRoundForRate(bytes32 currencyKey) external view returns (uint); function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory); function effectiveValue( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns (uint value); function effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns ( uint value, uint sourceRate, uint destinationRate ); function effectiveValueAtRound( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint roundIdForSrc, uint roundIdForDest ) external view returns (uint value); function getCurrentRoundId(bytes32 currencyKey) external view returns (uint); function getLastRoundIdBeforeElapsedSecs( bytes32 currencyKey, uint startingRoundId, uint startingTimestamp, uint timediff ) external view returns (uint); function inversePricing(bytes32 currencyKey) external view returns ( uint entryPoint, uint upperLimit, uint lowerLimit, bool frozenAtUpperLimit, bool frozenAtLowerLimit ); function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256); function oracle() external view returns (address); function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time); function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time); function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid); function rateForCurrency(bytes32 currencyKey) external view returns (uint); function rateIsFlagged(bytes32 currencyKey) external view returns (bool); function rateIsFrozen(bytes32 currencyKey) external view returns (bool); function rateIsInvalid(bytes32 currencyKey) external view returns (bool); function rateIsStale(bytes32 currencyKey) external view returns (bool); function rateStalePeriod() external view returns (uint); function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds) external view returns (uint[] memory rates, uint[] memory times); function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory rates, bool anyRateInvalid); function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory); // Mutative functions function freezeRate(bytes32 currencyKey) external; } // 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 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.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.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.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 Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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 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); } } // 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.12; pragma experimental ABIEncoderV2; import "./interfaces/ISwap.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title SwapMigrator * @notice This contract is responsible for migrating old USD pool liquidity to the new ones. * Users can use this contract to remove their liquidity from the old pools and add them to the new * ones with a single transaction. */ contract SwapMigrator { using SafeERC20 for IERC20; struct MigrationData { address oldPoolAddress; IERC20 oldPoolLPTokenAddress; address newPoolAddress; IERC20 newPoolLPTokenAddress; IERC20[] underlyingTokens; } MigrationData public usdPoolMigrationData; address public owner; uint256 private constant MAX_UINT256 = 2**256 - 1; /** * @notice Sets the storage variables and approves tokens to be used by the old and new swap contracts * @param usdData_ MigrationData struct with information about old and new USD pools * @param owner_ owner that is allowed to call the `rescue()` function */ constructor(MigrationData memory usdData_, address owner_) public { // Approve old USD LP Token to be used by the old USD pool usdData_.oldPoolLPTokenAddress.approve( usdData_.oldPoolAddress, MAX_UINT256 ); // Approve USD tokens to be used by the new USD pool for (uint256 i = 0; i < usdData_.underlyingTokens.length; i++) { usdData_.underlyingTokens[i].safeApprove( usdData_.newPoolAddress, MAX_UINT256 ); } // Set storage variables usdPoolMigrationData = usdData_; owner = owner_; } /** * @notice Migrates old USD pool's LPToken to the new pool * @param amount Amount of old LPToken to migrate * @param minAmount Minimum amount of new LPToken to receive */ function migrateUSDPool(uint256 amount, uint256 minAmount) external returns (uint256) { // Transfer old LP token from the caller usdPoolMigrationData.oldPoolLPTokenAddress.safeTransferFrom( msg.sender, address(this), amount ); // Remove liquidity from the old pool and add them to the new pool uint256[] memory amounts = ISwap(usdPoolMigrationData.oldPoolAddress) .removeLiquidity( amount, new uint256[](usdPoolMigrationData.underlyingTokens.length), MAX_UINT256 ); uint256 mintedAmount = ISwap(usdPoolMigrationData.newPoolAddress) .addLiquidity(amounts, minAmount, MAX_UINT256); // Transfer new LP Token to the caller usdPoolMigrationData.newPoolLPTokenAddress.safeTransfer( msg.sender, mintedAmount ); return mintedAmount; } /** * @notice Rescues any token that may be sent to this contract accidentally. * @param token Amount of old LPToken to migrate * @param to Minimum amount of new LPToken to receive */ function rescue(IERC20 token, address to) external { require(msg.sender == owner, "is not owner"); token.safeTransfer(to, token.balanceOf(address(this))); } } // SPDX-License-Identifier: MIT // Generalized and adapted from https://github.com/k06a/Unipool 🙇 pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title StakeableTokenWrapper * @notice A wrapper for an ERC-20 that can be staked and withdrawn. * @dev In this contract, staked tokens don't do anything- instead other * contracts can inherit from this one to add functionality. */ contract StakeableTokenWrapper { using SafeERC20 for IERC20; using SafeMath for uint256; uint256 public totalSupply; IERC20 public stakedToken; mapping(address => uint256) private _balances; event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); /** * @notice Creates a new StakeableTokenWrapper with given `_stakedToken` address * @param _stakedToken address of a token that will be used to stake */ constructor(IERC20 _stakedToken) public { stakedToken = _stakedToken; } /** * @notice Read how much `account` has staked in this contract * @param account address of an account * @return amount of total staked ERC20(this.stakedToken) by `account` */ function balanceOf(address account) external view returns (uint256) { return _balances[account]; } /** * @notice Stakes given `amount` in this contract * @param amount amount of ERC20(this.stakedToken) to stake */ function stake(uint256 amount) external { require(amount != 0, "amount == 0"); totalSupply = totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakedToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } /** * @notice Withdraws given `amount` from this contract * @param amount amount of ERC20(this.stakedToken) to withdraw */ function withdraw(uint256 amount) external { totalSupply = totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakedToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IFlashLoanReceiver.sol"; import "../interfaces/ISwapFlashLoan.sol"; import "hardhat/console.sol"; contract FlashLoanBorrowerExample is IFlashLoanReceiver { using SafeMath for uint256; // Typical executeOperation function should do the 3 following actions // 1. Check if the flashLoan was successful // 2. Do actions with the borrowed tokens // 3. Repay the debt to the `pool` function executeOperation( address pool, address token, uint256 amount, uint256 fee, bytes calldata params ) external override { // 1. Check if the flashLoan was valid require( IERC20(token).balanceOf(address(this)) >= amount, "flashloan is broken?" ); // 2. Do actions with the borrowed token bytes32 paramsHash = keccak256(params); if (paramsHash == keccak256(bytes("dontRepayDebt"))) { return; } else if (paramsHash == keccak256(bytes("reentrancy_addLiquidity"))) { ISwapFlashLoan(pool).addLiquidity( new uint256[](0), 0, block.timestamp ); } else if (paramsHash == keccak256(bytes("reentrancy_swap"))) { ISwapFlashLoan(pool).swap(1, 0, 1e6, 0, now); } else if ( paramsHash == keccak256(bytes("reentrancy_removeLiquidity")) ) { ISwapFlashLoan(pool).removeLiquidity(1e18, new uint256[](0), now); } else if ( paramsHash == keccak256(bytes("reentrancy_removeLiquidityOneToken")) ) { ISwapFlashLoan(pool).removeLiquidityOneToken(1e18, 0, 1e18, now); } // 3. Payback debt uint256 totalDebt = amount.add(fee); IERC20(token).transfer(pool, totalDebt); } function flashLoan( ISwapFlashLoan swap, IERC20 token, uint256 amount, bytes memory params ) external { swap.flashLoan(address(this), token, amount, params); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./ISwap.sol"; interface ISwapFlashLoan is ISwap { function flashLoan( address receiver, IERC20 token, uint256 amount, bytes memory params ) external; } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../../interfaces/ISwap.sol"; import "hardhat/console.sol"; contract TestSwapReturnValues { using SafeMath for uint256; ISwap public swap; IERC20 public lpToken; uint8 public n; uint256 public constant MAX_INT = 2**256 - 1; constructor( ISwap swapContract, IERC20 lpTokenContract, uint8 numOfTokens ) public { swap = swapContract; lpToken = lpTokenContract; n = numOfTokens; // Pre-approve tokens for (uint8 i; i < n; i++) { swap.getToken(i).approve(address(swap), MAX_INT); } lpToken.approve(address(swap), MAX_INT); } function test_swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) public { uint256 balanceBefore = swap.getToken(tokenIndexTo).balanceOf( address(this) ); uint256 returnValue = swap.swap( tokenIndexFrom, tokenIndexTo, dx, minDy, block.timestamp ); uint256 balanceAfter = swap.getToken(tokenIndexTo).balanceOf( address(this) ); console.log( "swap: Expected %s, got %s", balanceAfter.sub(balanceBefore), returnValue ); require( returnValue == balanceAfter.sub(balanceBefore), "swap()'s return value does not match received amount" ); } function test_addLiquidity(uint256[] calldata amounts, uint256 minToMint) public { uint256 balanceBefore = lpToken.balanceOf(address(this)); uint256 returnValue = swap.addLiquidity(amounts, minToMint, MAX_INT); uint256 balanceAfter = lpToken.balanceOf(address(this)); console.log( "addLiquidity: Expected %s, got %s", balanceAfter.sub(balanceBefore), returnValue ); require( returnValue == balanceAfter.sub(balanceBefore), "addLiquidity()'s return value does not match minted amount" ); } function test_removeLiquidity(uint256 amount, uint256[] memory minAmounts) public { uint256[] memory balanceBefore = new uint256[](n); uint256[] memory balanceAfter = new uint256[](n); for (uint8 i = 0; i < n; i++) { balanceBefore[i] = swap.getToken(i).balanceOf(address(this)); } uint256[] memory returnValue = swap.removeLiquidity( amount, minAmounts, MAX_INT ); for (uint8 i = 0; i < n; i++) { balanceAfter[i] = swap.getToken(i).balanceOf(address(this)); console.log( "removeLiquidity: Expected %s, got %s", balanceAfter[i].sub(balanceBefore[i]), returnValue[i] ); require( balanceAfter[i].sub(balanceBefore[i]) == returnValue[i], "removeLiquidity()'s return value does not match received amounts of tokens" ); } } function test_removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount ) public { uint256 balanceBefore = lpToken.balanceOf(address(this)); uint256 returnValue = swap.removeLiquidityImbalance( amounts, maxBurnAmount, MAX_INT ); uint256 balanceAfter = lpToken.balanceOf(address(this)); console.log( "removeLiquidityImbalance: Expected %s, got %s", balanceBefore.sub(balanceAfter), returnValue ); require( returnValue == balanceBefore.sub(balanceAfter), "removeLiquidityImbalance()'s return value does not match burned lpToken amount" ); } function test_removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) public { uint256 balanceBefore = swap.getToken(tokenIndex).balanceOf( address(this) ); uint256 returnValue = swap.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount, MAX_INT ); uint256 balanceAfter = swap.getToken(tokenIndex).balanceOf( address(this) ); console.log( "removeLiquidityOneToken: Expected %s, got %s", balanceAfter.sub(balanceBefore), returnValue ); require( returnValue == balanceAfter.sub(balanceBefore), "removeLiquidityOneToken()'s return value does not match received token amount" ); } } // SPDX-License-Identifier: MIT // https://etherscan.io/address/0x2b7a5a5923eca5c00c6572cf3e8e08384f563f93#code pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./LPTokenGuarded.sol"; import "../MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtilsGuarded { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; uint256 defaultWithdrawFee; LPTokenGuarded lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; mapping(address => uint256) depositTimestamp; mapping(address => uint256) withdrawFeeMultiplier; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculation in addLiquidity function // to avoid stack too deep error struct AddLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; } // Struct storing variables used in calculation in removeLiquidityImbalance function // to avoid stack too deep error struct RemoveLiquidityImbalanceInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Max withdrawFee is 1% of the value withdrawn // Fee will be redistributed to the LPs in the pool, rewarding // long term providers. uint256 public constant MAX_WITHDRAW_FEE = 10**8; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(Swap storage self) external view returns (uint256) { return _getA(self); } /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function _getA(Swap storage self) internal view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Calculates and returns A based on the ramp settings * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Retrieves the timestamp of last deposit made by the given address * @param self Swap struct to read from * @return timestamp of last deposit */ function getDepositTimestamp(Swap storage self, address user) external view returns (uint256) { return self.depositTimestamp[user]; } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param account the address that is withdrawing * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive and the associated swap fee */ function calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex ) public view returns (uint256, uint256) { uint256 dy; uint256 newY; (dy, newY) = calculateWithdrawOneTokenDY(self, tokenIndex, tokenAmount); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = _xp(self)[tokenIndex] .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); dy = dy .mul( FEE_DENOMINATOR.sub(calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount ) internal view returns (uint256, uint256) { require( tokenIndex < self.pooledTokens.length, "Token index out of range" ); // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(self.lpToken.totalSupply())); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self); for (uint256 i = 0; i < self.pooledTokens.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant iteratively. * See the StableSwap paper and Curve.fi implementation for further details. * * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex Index of token we are calculating for. * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool. * @param d the stableswap invariant * @return the price of the token, in the same precision as in xp */ function getYD( uint256 a, uint8 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @param xp a precision-adjusted set of pool balances. Array should be the same cardinality * as the pool. * @param a the amplification coefficient * n * (n - 1) in A_PRECISION. * See the StableSwap paper for details * @return the invariant, at the precision of the pool */ function getD(uint256[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA.mul(s).div(A_PRECISION).add(dP.mul(numTokens)).mul(d).div( nA.sub(A_PRECISION).mul(d).div(A_PRECISION).add( numTokens.add(1).mul(dP) ) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Get D, the StableSwap invariant, based on self Swap struct * @param self Swap struct to read from * @return The invariant, at the precision of the pool */ function getD(Swap storage self) internal view returns (uint256) { return getD(_xp(self), _getAPrecise(self)); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @param balances array of balances to scale * @return balances array "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self, uint256[] memory balances) internal view returns (uint256[] memory) { return _xp(balances, self.tokenPrecisionMultipliers); } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); uint256 supply = self.lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(ERC20(self.lpToken).decimals())).div(supply); } return 0; } /** * @notice Calculate the new balances of the tokens given the indexes of the token * that is swapped from (FROM) and the token that is swapped to (TO). * This function is used as a helper function to calculate how much TO token * the user should receive on swap. * * @param self Swap struct to read from * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @param x the new total amount of FROM token * @param xp balances of the tokens in the pool * @return the amount of TO token that should remain in the pool */ function getY( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal view returns (uint256) { uint256 numTokens = self.pooledTokens.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 a = _getAPrecise(self); uint256 d = getD(xp, a); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(a); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap(self, tokenIndexFrom, tokenIndexTo, dx); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory xp = _xp(self); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]).add( xp[tokenIndexFrom] ); uint256 y = getY(self, tokenIndexFrom, tokenIndexTo, x, xp); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(self.tokenPrecisionMultipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param account the address that is removing liquidity. required for withdraw fee calculation * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) external view returns (uint256[] memory) { return _calculateRemoveLiquidity(self, account, amount); } function _calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) internal view returns (uint256[] memory) { uint256 totalSupply = self.lpToken.totalSupply(); require(amount <= totalSupply, "Cannot exceed total supply"); uint256 feeAdjustedAmount = amount .mul( FEE_DENOMINATOR.sub(calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); uint256[] memory amounts = new uint256[](self.pooledTokens.length); for (uint256 i = 0; i < self.pooledTokens.length; i++) { amounts[i] = self.balances[i].mul(feeAdjustedAmount).div( totalSupply ); } return amounts; } /** * @notice Calculate the fee that is applied when the given user withdraws. * Withdraw fee decays linearly over 4 weeks. * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(Swap storage self, address user) public view returns (uint256) { uint256 endTime = self.depositTimestamp[user].add(4 weeks); if (endTime > block.timestamp) { uint256 timeLeftover = endTime.sub(block.timestamp); return self .defaultWithdrawFee .mul(self.withdrawFeeMultiplier[user]) .mul(timeLeftover) .div(4 weeks) .div(FEE_DENOMINATOR); } return 0; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param account address of the account depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 numTokens = self.pooledTokens.length; uint256 a = _getAPrecise(self); uint256 d0 = getD(_xp(self, self.balances), a); uint256[] memory balances1 = self.balances; for (uint256 i = 0; i < numTokens; i++) { if (deposit) { balances1[i] = balances1[i].add(amounts[i]); } else { balances1[i] = balances1[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(self, balances1), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub( calculateCurrentWithdrawFee(self, account) ) ); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param self Swap struct to read from */ function _feePerToken(Swap storage self) internal view returns (uint256) { return self.swapFee.mul(self.pooledTokens.length).div( self.pooledTokens.length.sub(1).mul(4) ); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { require( dx <= self.pooledTokens[tokenIndexFrom].balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = self.pooledTokens[tokenIndexFrom].balanceOf( address(this) ); self.pooledTokens[tokenIndexFrom].safeTransferFrom( msg.sender, address(this), dx ); // Use the actual transferred amount for AMM math uint256 transferredDx = self .pooledTokens[tokenIndexFrom] .balanceOf(address(this)) .sub(beforeBalance); (uint256 dy, uint256 dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, transferredDx ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = self.balances[tokenIndexFrom].add( transferredDx ); self.balances[tokenIndexTo] = self.balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap( msg.sender, transferredDx, dy, tokenIndexFrom, tokenIndexTo ); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param merkleProof bytes32 array that will be used to prove the existence of the caller's address in the list of * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint, bytes32[] calldata merkleProof ) external returns (uint256) { require( amounts.length == self.pooledTokens.length, "Amounts must match pooled tokens" ); uint256[] memory fees = new uint256[](self.pooledTokens.length); // current state AddLiquidityInfo memory v = AddLiquidityInfo(0, 0, 0, 0); if (self.lpToken.totalSupply() != 0) { v.d0 = getD(self); } uint256[] memory newBalances = self.balances; for (uint256 i = 0; i < self.pooledTokens.length; i++) { require( self.lpToken.totalSupply() != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = self.pooledTokens[i].balanceOf( address(this) ); self.pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = self.pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = self.balances[i].add(amounts[i]); } // invariant after change v.preciseA = _getAPrecise(self); v.d1 = getD(_xp(self, newBalances), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; if (self.lpToken.totalSupply() != 0) { uint256 feePerToken = _feePerToken(self); for (uint256 i = 0; i < self.pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(self.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(self, newBalances), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (self.lpToken.totalSupply() == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(self.lpToken.totalSupply()).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens self.lpToken.mint(msg.sender, toMint, merkleProof); emit AddLiquidity( msg.sender, amounts, fees, v.d1, self.lpToken.totalSupply() ); return toMint; } /** * @notice Update the withdraw fee for `user`. If the user is currently * not providing liquidity in the pool, sets to default value. If not, recalculate * the starting withdraw fee based on the last deposit's time & amount relative * to the new deposit. * * @param self Swap struct to read from and write to * @param user address of the user depositing tokens * @param toMint amount of pool tokens to be minted */ function updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) external { _updateUserWithdrawFee(self, user, toMint); } function _updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) internal { // If token is transferred to address 0 (or burned), don't update the fee. if (user == address(0)) { return; } if (self.defaultWithdrawFee == 0) { // If current fee is set to 0%, set multiplier to FEE_DENOMINATOR self.withdrawFeeMultiplier[user] = FEE_DENOMINATOR; } else { // Otherwise, calculate appropriate discount based on last deposit amount uint256 currentFee = calculateCurrentWithdrawFee(self, user); uint256 currentBalance = self.lpToken.balanceOf(user); // ((currentBalance * currentFee) + (toMint * defaultWithdrawFee)) * FEE_DENOMINATOR / // ((toMint + currentBalance) * defaultWithdrawFee) self.withdrawFeeMultiplier[user] = currentBalance .mul(currentFee) .add(toMint.mul(self.defaultWithdrawFee)) .mul(FEE_DENOMINATOR) .div(toMint.add(currentBalance).mul(self.defaultWithdrawFee)); } self.depositTimestamp[user] = block.timestamp; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { require(amount <= self.lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == self.pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory amounts = _calculateRemoveLiquidity( self, msg.sender, amount ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = self.balances[i].sub(amounts[i]); self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } self.lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, self.lpToken.totalSupply()); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { uint256 totalSupply = self.lpToken.totalSupply(); uint256 numTokens = self.pooledTokens.length; require( tokenAmount <= self.lpToken.balanceOf(msg.sender), ">LP.balanceOf" ); require(tokenIndex < numTokens, "Token not found"); uint256 dyFee; uint256 dy; (dy, dyFee) = calculateWithdrawOneToken( self, msg.sender, tokenAmount, tokenIndex ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); self.lpToken.burnFrom(msg.sender, tokenAmount); self.pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { require( amounts.length == self.pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= self.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); RemoveLiquidityImbalanceInfo memory v = RemoveLiquidityImbalanceInfo( 0, 0, 0, 0 ); uint256 tokenSupply = self.lpToken.totalSupply(); uint256 feePerToken = _feePerToken(self); uint256[] memory balances1 = self.balances; v.preciseA = _getAPrecise(self); v.d0 = getD(_xp(self), v.preciseA); for (uint256 i = 0; i < self.pooledTokens.length; i++) { balances1[i] = balances1[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(self, balances1), v.preciseA); uint256[] memory fees = new uint256[](self.pooledTokens.length); for (uint256 i = 0; i < self.pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(self.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(self, balances1), v.preciseA); uint256 tokenAmount = v.d0.sub(v.d2).mul(tokenSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub(calculateCurrentWithdrawFee(self, msg.sender)) ); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); self.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < self.pooledTokens.length; i++) { self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, tokenSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { for (uint256 i = 0; i < self.pooledTokens.length; i++) { IERC20 token = self.pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub( self.balances[i] ); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } /** * @notice update the default withdraw fee. This also affects deposits made in the past as well. * @param self Swap struct to update * @param newWithdrawFee new withdraw fee to be applied */ function setDefaultWithdrawFee(Swap storage self, uint256 newWithdrawFee) external { require(newWithdrawFee <= MAX_WITHDRAW_FEE, "Fee is too high"); self.defaultWithdrawFee = newWithdrawFee; emit NewWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // SPDX-License-Identifier: MIT // https://etherscan.io/address/0xC28DF698475dEC994BE00C9C9D8658A548e6304F#code pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/ISwapGuarded.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. */ contract LPTokenGuarded is ERC20Burnable, Ownable { using SafeMath for uint256; // Address of the swap contract that owns this LP token. When a user adds liquidity to the swap contract, // they receive a proportionate amount of this LPToken. ISwapGuarded public swap; // Maps user account to total number of LPToken minted by them. Used to limit minting during guarded release phase mapping(address => uint256) public mintedAmounts; /** * @notice Deploys LPToken contract with given name, symbol, and decimals * @dev the caller of this constructor will become the owner of this contract * @param name_ name of this token * @param symbol_ symbol of this token * @param decimals_ number of decimals this token will be based on */ constructor( string memory name_, string memory symbol_, uint8 decimals_ ) public ERC20(name_, symbol_) { _setupDecimals(decimals_); swap = ISwapGuarded(_msgSender()); } /** * @notice Mints the given amount of LPToken to the recipient. During the guarded release phase, the total supply * and the maximum number of the tokens that a single account can mint are limited. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint * @param merkleProof the bytes32 array data that is used to prove recipient's address exists in the merkle tree * stored in the allowlist contract. If the pool is not guarded, this parameter is ignored. */ function mint( address recipient, uint256 amount, bytes32[] calldata merkleProof ) external onlyOwner { require(amount != 0, "amount == 0"); // If the pool is in the guarded launch phase, the following checks are done to restrict deposits. // 1. Check if the given merkleProof corresponds to the recipient's address in the merkle tree stored in the // allowlist contract. If the account has been already verified, merkleProof is ignored. // 2. Limit the total number of this LPToken minted to recipient as defined by the allowlist contract. // 3. Limit the total supply of this LPToken as defined by the allowlist contract. if (swap.isGuarded()) { IAllowlist allowlist = swap.getAllowlist(); require( allowlist.verifyAddress(recipient, merkleProof), "Invalid merkle proof" ); uint256 totalMinted = mintedAmounts[recipient].add(amount); require( totalMinted <= allowlist.getPoolAccountLimit(address(swap)), "account deposit limit" ); require( totalSupply().add(amount) <= allowlist.getPoolCap(address(swap)), "pool total supply limit" ); mintedAmounts[recipient] = totalMinted; } _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that swap.updateUserWithdrawFees are called everytime. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override(ERC20) { super._beforeTokenTransfer(from, to, amount); swap.updateUserWithdrawFee(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./IAllowlist.sol"; interface ISwapGuarded { // pool data view functions function getA() external view returns (uint256); function getAllowlist() external view returns (IAllowlist); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline, bytes32[] calldata merkleProof ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); // withdraw fee update function function updateUserWithdrawFee(address recipient, uint256 transferAmount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "../interfaces/IAllowlist.sol"; /** * @title Allowlist * @notice This contract is a registry holding information about how much each swap contract should * contain upto. Swap.sol will rely on this contract to determine whether the pool cap is reached and * also whether a user's deposit limit is reached. */ contract Allowlist is Ownable, IAllowlist { using SafeMath for uint256; // Represents the root node of merkle tree containing a list of eligible addresses bytes32 public merkleRoot; // Maps pool address -> maximum total supply mapping(address => uint256) private poolCaps; // Maps pool address -> maximum amount of pool token mintable per account mapping(address => uint256) private accountLimits; // Maps account address -> boolean value indicating whether it has been checked and verified against the merkle tree mapping(address => bool) private verified; event PoolCap(address indexed poolAddress, uint256 poolCap); event PoolAccountLimit(address indexed poolAddress, uint256 accountLimit); event NewMerkleRoot(bytes32 merkleRoot); /** * @notice Creates this contract and sets the PoolCap of 0x0 with uint256(0x54dd1e) for * crude checking whether an address holds this contract. * @param merkleRoot_ bytes32 that represent a merkle root node. This is generated off chain with the list of * qualifying addresses. */ constructor(bytes32 merkleRoot_) public { merkleRoot = merkleRoot_; // This value will be used as a way of crude checking whether an address holds this Allowlist contract // Value 0x54dd1e has no inherent meaning other than it is arbitrary value that checks for // user error. poolCaps[address(0x0)] = uint256(0x54dd1e); emit PoolCap(address(0x0), uint256(0x54dd1e)); emit NewMerkleRoot(merkleRoot_); } /** * @notice Returns the max mintable amount of the lp token per account in given pool address. * @param poolAddress address of the pool * @return max mintable amount of the lp token per account */ function getPoolAccountLimit(address poolAddress) external view override returns (uint256) { return accountLimits[poolAddress]; } /** * @notice Returns the maximum total supply of the pool token for the given pool address. * @param poolAddress address of the pool */ function getPoolCap(address poolAddress) external view override returns (uint256) { return poolCaps[poolAddress]; } /** * @notice Returns true if the given account's existence has been verified against any of the past or * the present merkle tree. Note that if it has been verified in the past, this function will return true * even if the current merkle tree does not contain the account. * @param account the address to check if it has been verified * @return a boolean value representing whether the account has been verified in the past or the present merkle tree */ function isAccountVerified(address account) external view returns (bool) { return verified[account]; } /** * @notice Checks the existence of keccak256(account) as a node in the merkle tree inferred by the merkle root node * stored in this contract. Pools should use this function to check if the given address qualifies for depositing. * If the given account has already been verified with the correct merkleProof, this function will return true when * merkleProof is empty. The verified status will be overwritten if the previously verified user calls this function * with an incorrect merkleProof. * @param account address to confirm its existence in the merkle tree * @param merkleProof data that is used to prove the existence of given parameters. This is generated * during the creation of the merkle tree. Users should retrieve this data off-chain. * @return a boolean value that corresponds to whether the address with the proof has been verified in the past * or if they exist in the current merkle tree. */ function verifyAddress(address account, bytes32[] calldata merkleProof) external override returns (bool) { if (merkleProof.length != 0) { // Verify the account exists in the merkle tree via the MerkleProof library bytes32 node = keccak256(abi.encodePacked(account)); if (MerkleProof.verify(merkleProof, merkleRoot, node)) { verified[account] = true; return true; } } return verified[account]; } // ADMIN FUNCTIONS /** * @notice Sets the account limit of allowed deposit amounts for the given pool * @param poolAddress address of the pool * @param accountLimit the max number of the pool token a single user can mint */ function setPoolAccountLimit(address poolAddress, uint256 accountLimit) external onlyOwner { require(poolAddress != address(0x0), "0x0 is not a pool address"); accountLimits[poolAddress] = accountLimit; emit PoolAccountLimit(poolAddress, accountLimit); } /** * @notice Sets the max total supply of LPToken for the given pool address * @param poolAddress address of the pool * @param poolCap the max total supply of the pool token */ function setPoolCap(address poolAddress, uint256 poolCap) external onlyOwner { require(poolAddress != address(0x0), "0x0 is not a pool address"); poolCaps[poolAddress] = poolCap; emit PoolCap(poolAddress, poolCap); } /** * @notice Updates the merkle root that is stored in this contract. This can only be called by * the owner. If more addresses are added to the list, a new merkle tree and a merkle root node should be generated, * and merkleRoot should be updated accordingly. * @param merkleRoot_ a new merkle root node that contains a list of deposit allowed addresses */ function updateMerkleRoot(bytes32 merkleRoot_) external onlyOwner { merkleRoot = merkleRoot_; emit NewMerkleRoot(merkleRoot_); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./OwnerPausable.sol"; import "./SwapUtilsGuarded.sol"; import "../MathUtils.sol"; import "./Allowlist.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapGuarded is OwnerPausable, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; using SwapUtilsGuarded for SwapUtilsGuarded.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtilsGuarded.sol SwapUtilsGuarded.Swap public swapStorage; // Address to allowlist contract that holds information about maximum totaly supply of lp tokens // and maximum mintable amount per user address. As this is immutable, this will become a constant // after initialization. IAllowlist private immutable allowlist; // Boolean value that notates whether this pool is guarded or not. When isGuarded is true, // addLiquidity function will be restricted by limits defined in allowlist contract. bool private guarded = true; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Deploys this Swap contract with given parameters as default * values. This will also deploy a LPToken that represents users * LP position. The owner of LPToken will be this contract - which means * only this contract is allowed to mint new tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param _allowlist address of allowlist contract for guarded launch */ constructor( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, IAllowlist _allowlist ) public OwnerPausable() ReentrancyGuard() { // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtilsGuarded.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtilsGuarded.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee, _allowlist parameters require(_a < SwapUtilsGuarded.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtilsGuarded.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtilsGuarded.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); require( _withdrawFee < SwapUtilsGuarded.MAX_WITHDRAW_FEE, "_withdrawFee exceeds maximum" ); require( _allowlist.getPoolCap(address(0x0)) == uint256(0x54dd1e), "Allowlist check failed" ); // Initialize swapStorage struct swapStorage.lpToken = new LPTokenGuarded( lpTokenName, lpTokenSymbol, SwapUtilsGuarded.POOL_PRECISION_DECIMALS ); swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(SwapUtilsGuarded.A_PRECISION); swapStorage.futureA = _a.mul(SwapUtilsGuarded.A_PRECISION); swapStorage.initialATime = 0; swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; swapStorage.defaultWithdrawFee = _withdrawFee; // Initialize variables related to guarding the initial deposits allowlist = _allowlist; guarded = true; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) external view returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Reads and returns the address of the allowlist that is set during deployment of this contract * @return the address of the allowlist contract casted to the IAllowlist interface */ function getAllowlist() external view returns (IAllowlist) { return allowlist; } /** * @notice Return timestamp of last deposit of given address * @return timestamp of the last deposit made by the given address */ function getDepositTimestamp(address user) external view returns (uint256) { return swapStorage.getDepositTimestamp(user); } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param account address that is depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { return swapStorage.calculateTokenAmount(account, amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param account the address that is withdrawing tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(address account, uint256 amount) external view returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(account, amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param account the address that is withdrawing tokens * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount) { (availableTokenAmount, ) = swapStorage.calculateWithdrawOneToken( account, tokenAmount, tokenIndex ); } /** * @notice Calculate the fee that is applied when the given user withdraws. The withdraw fee * decays linearly over period of 4 weeks. For example, depositing and withdrawing right away * will charge you the full amount of withdraw fee. But withdrawing after 4 weeks will charge you * no additional fees. * @dev returned value should be divided by FEE_DENOMINATOR to convert to correct decimals * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(address user) external view returns (uint256) { return swapStorage.calculateCurrentWithdrawFee(user); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with given amounts during guarded launch phase. Only users * with valid address and proof can successfully call this function. When this function is called * after the guarded release phase is over, the merkleProof is ignored. * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @param merkleProof data generated when constructing the allowlist merkle tree. Users can * get this data off chain. Even if the address is in the allowlist, users must include * a valid proof for this call to succeed. If the pool is no longer in the guarded release phase, * this parameter is ignored. * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline, bytes32[] calldata merkleProof ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint, merkleProof); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the user withdraw fee. This function can only be called by * the pool token. Should be used to update the withdraw fee on transfer of pool tokens. * Transferring your pool token will reset the 4 weeks period. If the recipient is already * holding some pool tokens, the withdraw fee will be discounted in respective amounts. * @param recipient address of the recipient of pool token * @param transferAmount amount of pool token to transfer */ function updateUserWithdrawFee(address recipient, uint256 transferAmount) external { require( msg.sender == address(swapStorage.lpToken), "Only callable by pool token" ); swapStorage.updateUserWithdrawFee(recipient, transferAmount); } /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Update the withdraw fee. This fee decays linearly over 4 weeks since * user's last deposit. * @param newWithdrawFee new withdraw fee to be applied on future deposits */ function setDefaultWithdrawFee(uint256 newWithdrawFee) external onlyOwner { swapStorage.setDefaultWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } /** * @notice Disables the guarded launch phase, removing any limits on deposit amounts and addresses */ function disableGuard() external onlyOwner { guarded = false; } /** * @notice Reads and returns current guarded status of the pool * @return guarded_ boolean value indicating whether the deposits should be guarded */ function isGuarded() external view returns (bool) { return guarded; } } // 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.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; /** * @title OwnerPausable * @notice An ownable contract allows the owner to pause and unpause the * contract without a delay. * @dev Only methods using the provided modifiers will be paused. */ contract OwnerPausable is Ownable, Pausable { /** * @notice Pause the contract. Revert if already paused. */ function pause() external onlyOwner { Pausable._pause(); } /** * @notice Unpause the contract. Revert if already unpaused. */ function unpause() external onlyOwner { Pausable._unpause(); } } // 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.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Generic ERC20 token * @notice This contract simulates a generic ERC20 token that is mintable and burnable. */ contract GenericERC20 is ERC20, Ownable { /** * @notice Deploy this contract with given name, symbol, and decimals * @dev the caller of this constructor will become the owner of this contract * @param name_ name of this token * @param symbol_ symbol of this token * @param decimals_ number of decimals this token will be based on */ constructor( string memory name_, string memory symbol_, uint8 decimals_ ) public ERC20(name_, symbol_) { _setupDecimals(decimals_); } /** * @notice Mints given amount of tokens to recipient * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "amount == 0"); _mint(recipient, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./interfaces/ISwap.sol"; import "./helper/BaseBoringBatchable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title GeneralizedSwapMigrator * @notice This contract is responsible for migration liquidity between pools * Users can use this contract to remove their liquidity from the old pools and add them to the new * ones with a single transaction. */ contract GeneralizedSwapMigrator is Ownable, BaseBoringBatchable { using SafeERC20 for IERC20; struct MigrationData { address newPoolAddress; IERC20 oldPoolLPTokenAddress; IERC20 newPoolLPTokenAddress; IERC20[] tokens; } uint256 private constant MAX_UINT256 = 2**256 - 1; mapping(address => MigrationData) public migrationMap; event AddMigrationData(address indexed oldPoolAddress, MigrationData mData); event Migrate( address indexed migrator, address indexed oldPoolAddress, uint256 oldLPTokenAmount, uint256 newLPTokenAmount ); constructor() public Ownable() {} /** * @notice Add new migration data to the contract * @param oldPoolAddress pool address to migrate from * @param mData MigrationData struct that contains information of the old and new pools * @param overwrite should overwrite existing migration data */ function addMigrationData( address oldPoolAddress, MigrationData memory mData, bool overwrite ) external onlyOwner { // Check if (!overwrite) { require( address(migrationMap[oldPoolAddress].oldPoolLPTokenAddress) == address(0), "cannot overwrite existing migration data" ); } require( address(mData.oldPoolLPTokenAddress) != address(0), "oldPoolLPTokenAddress == 0" ); require( address(mData.newPoolLPTokenAddress) != address(0), "newPoolLPTokenAddress == 0" ); for (uint8 i = 0; i < 32; i++) { address oldPoolToken; try ISwap(oldPoolAddress).getToken(i) returns (IERC20 token) { oldPoolToken = address(token); } catch { require(i > 0, "Failed to get tokens underlying Saddle pool."); oldPoolToken = address(0); } try ISwap(mData.newPoolAddress).getToken(i) returns (IERC20 token) { require( oldPoolToken == address(token) && oldPoolToken == address(mData.tokens[i]), "Failed to match tokens list" ); } catch { require(i > 0, "Failed to get tokens underlying Saddle pool."); require( oldPoolToken == address(0) && i == mData.tokens.length, "Failed to match tokens list" ); break; } } // Effect migrationMap[oldPoolAddress] = mData; // Interaction // Approve old LP Token to be used for withdraws. mData.oldPoolLPTokenAddress.approve(oldPoolAddress, MAX_UINT256); // Approve underlying tokens to be used for deposits. for (uint256 i = 0; i < mData.tokens.length; i++) { mData.tokens[i].safeApprove(mData.newPoolAddress, 0); mData.tokens[i].safeApprove(mData.newPoolAddress, MAX_UINT256); } emit AddMigrationData(oldPoolAddress, mData); } /** * @notice Migrates saddle LP tokens from a pool to another * @param oldPoolAddress pool address to migrate from * @param amount amount of LP tokens to migrate * @param minAmount of new LP tokens to receive */ function migrate( address oldPoolAddress, uint256 amount, uint256 minAmount ) external returns (uint256) { // Check MigrationData memory mData = migrationMap[oldPoolAddress]; require( address(mData.oldPoolLPTokenAddress) != address(0), "migration is not available" ); // Interactions // Transfer old LP token from the caller mData.oldPoolLPTokenAddress.safeTransferFrom( msg.sender, address(this), amount ); // Remove liquidity from the old pool uint256[] memory amounts = ISwap(oldPoolAddress).removeLiquidity( amount, new uint256[](mData.tokens.length), MAX_UINT256 ); // Add acquired liquidity to the new pool uint256 mintedAmount = ISwap(mData.newPoolAddress).addLiquidity( amounts, minAmount, MAX_UINT256 ); // Transfer new LP Token to the caller mData.newPoolLPTokenAddress.safeTransfer(msg.sender, mintedAmount); emit Migrate(msg.sender, oldPoolAddress, amount, mintedAmount); return mintedAmount; } /** * @notice Rescues any token that may be sent to this contract accidentally. * @param token Amount of old LPToken to migrate * @param to Minimum amount of new LPToken to receive */ function rescue(IERC20 token, address to) external onlyOwner { token.safeTransfer(to, token.balanceOf(address(this))); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // solhint-disable avoid-low-level-calls // solhint-disable no-inline-assembly // Audit on 5-Jan-2021 by Keno and BoringCrypto // WARNING!!! // Combining BoringBatchable with msg.value can cause double spending issues // https://www.paradigm.xyz/2021/08/two-rights-might-make-a-wrong/ contract BaseBoringBatchable { /// @dev Helper function to extract a useful revert message from a failed call. /// If the returned data is malformed or not correctly abi encoded then this call can fail itself. function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } /// @notice Allows batched call to self (this contract). /// @param calls An array of inputs for each call. /// @param revertOnFail If True then reverts after a failed call and stops doing further calls. // F1: External is ok here because this is the batch function, adding it to a batch makes no sense // F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value // C3: The length of the loop is fully under user control, so can't be exploited // C7: Delegatecall is only used on the same contract, so it's safe function batch(bytes[] calldata calls, bool revertOnFail) external payable { for (uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory result) = address(this).delegatecall( calls[i] ); if (!success && revertOnFail) { revert(_getRevertMsg(result)); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../Swap.sol"; import "./MetaSwapUtils.sol"; /** * @title MetaSwap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * MetaSwap is a modified version of Swap that allows Swap's LP token to be utilized in pooling with other tokens. * As an example, if there is a Swap pool consisting of [DAI, USDC, USDT], then a MetaSwap pool can be created * with [sUSD, BaseSwapLPToken] to allow trades between either the LP token or the underlying tokens and sUSD. * Note that when interacting with MetaSwap, users cannot deposit or withdraw via underlying tokens. In that case, * `MetaSwapDeposit.sol` can be additionally deployed to allow interacting with unwrapped representations of the tokens. * * @dev Most of the logic is stored as a library `MetaSwapUtils` for the sake of reducing contract's * deployment size. */ contract MetaSwap is Swap { using MetaSwapUtils for SwapUtils.Swap; MetaSwapUtils.MetaSwap public metaSwapStorage; uint256 constant MAX_UINT256 = 2**256 - 1; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwapUnderlying( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual override returns (uint256) { return MetaSwapUtils.getVirtualPrice(swapStorage, metaSwapStorage); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual override returns (uint256) { return MetaSwapUtils.calculateSwap( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx ); } /** * @notice Calculate amount of tokens you receive on swap. For this function, * the token indices are flattened out so that underlying tokens are represented. * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return MetaSwapUtils.calculateSwapUnderlying( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx ); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view virtual override returns (uint256) { return MetaSwapUtils.calculateTokenAmount( swapStorage, metaSwapStorage, amounts, deposit ); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view virtual override returns (uint256) { return MetaSwapUtils.calculateWithdrawOneToken( swapStorage, metaSwapStorage, tokenAmount, tokenIndex ); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice This overrides Swap's initialize function to prevent initializing * without the address of the base Swap contract. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) public virtual override initializer { revert("use initializeMetaSwap() instead"); } /** * @notice Initializes this MetaSwap contract with the given parameters. * MetaSwap uses an existing Swap pool to expand the available liquidity. * _pooledTokens array should contain the base Swap pool's LP token as * the last element. For example, if there is a Swap pool consisting of * [DAI, USDC, USDT]. Then a MetaSwap pool can be created with [sUSD, BaseSwapLPToken] * as _pooledTokens. * * This will also deploy the LPToken that represents users' * LP position. The owner of LPToken will be this contract - which means * only this contract is allowed to mint new tokens. * * @param _pooledTokens an array of ERC20s this pool will accept. The last * element must be an existing Swap pool's LP token's address. * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with */ function initializeMetaSwap( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress, ISwap baseSwap ) external virtual initializer { Swap.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress ); // MetaSwap initializer metaSwapStorage.baseSwap = baseSwap; metaSwapStorage.baseVirtualPrice = baseSwap.getVirtualPrice(); metaSwapStorage.baseCacheLastUpdated = block.timestamp; // Read all tokens that belong to baseSwap { uint8 i; for (; i < 32; i++) { try baseSwap.getToken(i) returns (IERC20 token) { metaSwapStorage.baseTokens.push(token); token.safeApprove(address(baseSwap), MAX_UINT256); } catch { break; } } require(i > 1, "baseSwap must pool at least 2 tokens"); } // Check the last element of _pooledTokens is owned by baseSwap IERC20 baseLPToken = _pooledTokens[_pooledTokens.length - 1]; require( LPToken(address(baseLPToken)).owner() == address(baseSwap), "baseLPToken is not owned by baseSwap" ); // Pre-approve the baseLPToken to be used by baseSwap baseLPToken.safeApprove(address(baseSwap), MAX_UINT256); } /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.swap( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx, minDy ); } /** * @notice Swap two tokens using this pool and the base pool. * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.swapUnderlying( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx, minDy ); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.addLiquidity( swapStorage, metaSwapStorage, amounts, minToMint ); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.removeLiquidityOneToken( swapStorage, metaSwapStorage, tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.removeLiquidityImbalance( swapStorage, metaSwapStorage, amounts, maxBurnAmount ); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../../MathUtils.sol"; contract TestMathUtils { using MathUtils for uint256; function difference(uint256 a, uint256 b) public pure returns (uint256) { return a.difference(b); } function within1(uint256 a, uint256 b) public pure returns (bool) { return a.within1(b); } }
Check the last element of _pooledTokens is owned by baseSwap
IERC20 baseLPToken = _pooledTokens[_pooledTokens.length - 1];
970,736
[ 1, 1564, 326, 1142, 930, 434, 389, 1631, 20212, 5157, 353, 16199, 635, 1026, 12521, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 467, 654, 39, 3462, 1026, 14461, 1345, 273, 389, 1631, 20212, 5157, 63, 67, 1631, 20212, 5157, 18, 2469, 300, 404, 15533, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; interface IContractPublisher { struct CustomContractInstance { string contractId; uint256 publishTimestamp; string publishMetadataUri; bytes32 bytecodeHash; address implementation; } struct CustomContract { uint256 publicId; uint256 total; CustomContractInstance latest; mapping(uint256 => CustomContractInstance) instances; } struct CustomContractSet { EnumerableSet.Bytes32Set contractIds; mapping(bytes32 => CustomContract) contracts; } struct PublicContract { address publisher; string contractId; } /// @dev Emitted when the registry is paused. event Paused(bool isPaused); /// @dev Emitted when a publisher's approval of an operator is updated. event Approved(address indexed publisher, address indexed operator, bool isApproved); /// @dev Emitted when a contract is published. event ContractPublished( address indexed operator, address indexed publisher, CustomContractInstance publishedContract ); /// @dev Emitted when a contract is unpublished. event ContractUnpublished(address indexed operator, address indexed publisher, string indexed contractId); /// @dev Emitted when a published contract is added to the public list. event AddedContractToPublicList(address indexed publisher, string indexed contractId); /// @dev Emitted when a published contract is removed from the public list. event RemovedContractToPublicList(address indexed publisher, string indexed contractId); /** * @notice Returns whether a publisher has approved an operator to publish / unpublish contracts on their behalf. * * @param publisher The address of the publisher. * @param operator The address of the operator who publishes/unpublishes on behalf of the publisher. * * @return isApproved Whether the publisher has approved the operator to publish / unpublish contracts on their behalf. */ function isApprovedByPublisher(address publisher, address operator) external view returns (bool isApproved); /** * @notice Lets a publisher (caller) approve an operator to publish / unpublish contracts on their behalf. * * @param operator The address of the operator who publishes/unpublishes on behalf of the publisher. * @param toApprove whether to an operator to publish / unpublish contracts on the publisher's behalf. */ function approveOperator(address operator, bool toApprove) external; /** * @notice Returns the latest version of all contracts published by a publisher. * * @return published An array of all contracts published by the publisher. */ function getAllPublicPublishedContracts() external view returns (CustomContractInstance[] memory published); /** * @notice Returns the latest version of all contracts published by a publisher. * * @param publisher The address of the publisher. * * @return published An array of all contracts published by the publisher. */ function getAllPublishedContracts(address publisher) external view returns (CustomContractInstance[] memory published); /** * @notice Returns all versions of a published contract. * * @param publisher The address of the publisher. * @param contractId The identifier for a published contract (that can have multiple verisons). * * @return published The desired contracts published by the publisher. */ function getPublishedContractVersions(address publisher, string memory contractId) external view returns (CustomContractInstance[] memory published); /** * @notice Returns the latest version of a contract published by a publisher. * * @param publisher The address of the publisher. * @param contractId The identifier for a published contract (that can have multiple verisons). * * @return published The desired contract published by the publisher. */ function getPublishedContract(address publisher, string memory contractId) external view returns (CustomContractInstance memory published); /** * @notice Returns the public id of a published contract, if it is public. * * @param publisher The address of the publisher. * @param contractId The identifier for a published contract (that can have multiple verisons). * * @return publicId the public id of a published contract. */ function getPublicId(address publisher, string memory contractId) external returns (uint256 publicId); /** * @notice Let's an account publish a contract. The account must be approved by the publisher, or be the publisher. * * @param publisher The address of the publisher. * @param publishMetadataUri The IPFS URI of the publish metadata. * @param bytecodeHash The keccak256 hash of the contract bytecode. * @param implementation (Optional) An implementation address that proxy contracts / clones can point to. Default value * if such an implementation does not exist - address(0); * @param contractId The identifier for a published contract (that can have multiple verisons). * */ function publishContract( address publisher, string memory publishMetadataUri, bytes32 bytecodeHash, address implementation, string memory contractId ) external; /** * @notice Lets an account unpublish a contract and all its versions. The account must be approved by the publisher, or be the publisher. * * @param publisher The address of the publisher. * @param contractId The identifier for a published contract (that can have multiple verisons). */ function unpublishContract(address publisher, string memory contractId) external; /** * @notice Lets an account add a published contract (and all its versions). The account must be approved by the publisher, or be the publisher. * * @param publisher The address of the publisher. * @param contractId The identifier for a published contract (that can have multiple verisons). */ function addToPublicList(address publisher, string memory contractId) external; /** * @notice Lets an account remove a published contract (and all its versions). The account must be approved by the publisher, or be the publisher. * * @param publisher The address of the publisher. * @param contractId The identifier for a published contract (that can have multiple verisons). */ function removeFromPublicList(address publisher, string memory contractId) external; }
@dev Emitted when a publisher's approval of an operator is updated.
event Approved(address indexed publisher, address indexed operator, bool isApproved);
12,852,589
[ 1, 1514, 11541, 1347, 279, 12855, 1807, 23556, 434, 392, 3726, 353, 3526, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 1716, 685, 2155, 12, 2867, 8808, 12855, 16, 1758, 8808, 3726, 16, 1426, 353, 31639, 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 ]
./full_match/56/0xe2cD240AD9527f37597BF4cF94F2dDabA1FAd3E6/sources/project_/contracts/CopyContract.sol
Copy with percentage
return amount * _copyPercentage / ONE_HUNDRED_PERCENT;
3,235,674
[ 1, 2951, 598, 11622, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1082, 202, 2463, 3844, 380, 389, 3530, 16397, 342, 15623, 67, 44, 5240, 5879, 67, 3194, 19666, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library Counters { struct Counter { 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; } } library SafeMath { 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); } } function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; 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 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); } 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); } } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { _transferOwnership(_msgSender()); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } library Address { function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } 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"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } 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 ) 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); } } } } interface IERC721Receiver { function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } abstract contract ERC165 is IERC165 { function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) external view returns (uint256 balance); 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; } 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); } interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } 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; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } 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; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } 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())) : ""; } function _baseURI() internal view virtual returns (string memory) { return ""; } 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); } function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom( address from, address to, uint256 tokenId ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } 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); } 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"); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } 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)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } 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" ); } 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); } 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); } 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); _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } 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); } 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; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { mapping(address => mapping(uint256 => uint256)) private _ownedTokens; mapping(uint256 => uint256) private _ownedTokensIndex; uint256[] private _allTokens; mapping(uint256 => uint256) private _allTokensIndex; function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index delete _allTokensIndex[tokenId]; _allTokens.pop(); } } //MetaOtters contract MetaOtters is ERC721Enumerable, Ownable { using SafeMath for uint256; using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private _tokenIdTracker; uint256 public unitPrice = 8 * 10**16; // .08 eth uint256 public unitPrice_Presale = 3 * 10**16; //.03 eth uint256 public constant MAX_ELEMENTS = 8888; uint256 public constant MAX_PER_MINT = 10; uint256 public constant MAX_BY_MINT_WHITELIST = 3; uint256 public constant MAX_RESERVE_AMOUNT = 500; bool public isSaleOpen = false; bool public isPresaleOpen = false; bool public isOwnershipChangable =false; mapping(address => bool) private _whiteList; mapping(address => uint256) private _whiteListClaimed; uint256 public _reservedCount = 0; uint256 private _maxNumPerReserve = 100; string public baseTokenURI; string public uriExtension = ".json"; event CreateOtters(uint256 indexed id); constructor(string memory NFTbaseURI) ERC721("MetaOtters", "MO") { setBaseURI(NFTbaseURI); } modifier onlySaleIsOpen { if (_msgSender() != owner()) { require(isSaleOpen, "Sale is not open"); } _; } //URI functions =>override view URI , set baseURI when contract is deployed. function _baseURI() internal view virtual override returns (string memory) { return baseTokenURI; } function setBaseURI(string memory inputbaseURI) public onlyOwner { baseTokenURI = inputbaseURI; } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriExtension)) : ""; } //saleopen functions => change sale open status, change presale open status; function setSaleOpen(bool _isSaleOpen) external onlyOwner { isSaleOpen = _isSaleOpen; } function setPresaleOpen(bool _isPresaleOpen) external onlyOwner { isPresaleOpen = _isPresaleOpen; } //total supply functions => public check the current total amount of minted tokens; function _totalSupply() internal view returns (uint256) { return _tokenIdTracker.current(); } //reserve functions for owner => owner mint reserveNFTs, change max reserve mint amount per time; function reserveTokens(uint256 _Amount) public onlyOwner { uint256 reserveAmount = _Amount; require(reserveAmount > 0 && reserveAmount <= _maxNumPerReserve,"invalid amount"); require(_reservedCount + reserveAmount <= MAX_RESERVE_AMOUNT, "Max reserve exceeded"); for (uint256 i = 0; i < reserveAmount; i++) { _reservedCount++; _mintAnOtter(msg.sender); } } function setMaxPerReserve(uint256 maxNum) public onlyOwner { _maxNumPerReserve = maxNum; } /* // mintpass function for public => check if current user has mintpass or not. function hasMintPass(address sender) public view returns (bool){ if(sender==address(0)){ return false; } else if (isWhitelisted(sender)) { return true; } return false; } */ // mint functions for public => mint after sale is open, presalemint for addresses has mintpass; function mint(address _to, uint256 _mintAmount) public payable onlySaleIsOpen { uint256 idcurrent= _tokenIdTracker.current(); require( idcurrent < MAX_ELEMENTS, "All MetaOtters are sold out"); require( idcurrent + _mintAmount <= MAX_ELEMENTS, "Max limit"); require(_mintAmount > 0 && _mintAmount<= MAX_PER_MINT, "Exceeds number"); require(msg.value >= mintcost(_mintAmount), "Value below cost"); for (uint256 i = 0; i < _mintAmount; i++) { _mintAnOtter(_to); } } function presaleMint(uint256 _mintAmount) public payable { require(isPresaleOpen, "Presale is not open"); //ensure presale is open; require(isWhitelisted(msg.sender), "Must be whitelisted"); require(_mintAmount > 0 && _mintAmount<= MAX_BY_MINT_WHITELIST, "Incorrect amount to claim"); //ensure mintAmount less than max limit of whitelist addresses; require(_whiteListClaimed[msg.sender] + _mintAmount <= MAX_BY_MINT_WHITELIST, "Purchase exceeds max allowed");//ensure total mint amount of whitelist addr not excceds max limit; uint256 idcurrent= _tokenIdTracker.current(); require(idcurrent < MAX_ELEMENTS, "All MettaOtters are sold out"); require(idcurrent + _mintAmount <= MAX_ELEMENTS, "Max limit"); require(msg.value >= mintcost_Presale(_mintAmount), "Value below cost"); for (uint256 i = 0; i < _mintAmount; i++) { _whiteListClaimed[msg.sender] += 1; _mintAnOtter(msg.sender); } } //_tokenIdTracker =0 when initial. the first mint starts from 1. function _mintAnOtter(address _to) private { _tokenIdTracker.increment(); uint256 id = _tokenIdTracker.current(); _safeMint(_to, id); emit CreateOtters(id); } function mintcost(uint256 _count) public view returns (uint256) { return unitPrice.mul(_count); } function mintcost_Presale(uint256 _count) public view returns (uint256) { return unitPrice_Presale.mul(_count); } // price functions => public check price for each token, owner change unit price if needed. function setunitPrice(uint256 _price) public onlyOwner { unitPrice =_price; } function setunitPrice_Presale(uint256 _price) public onlyOwner { unitPrice_Presale =_price; } function getunitPrice() public view returns(uint256){ return unitPrice; } //whitelist functions => add, check, remove; function addToWhiteList(address[] calldata addresses) external onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { require(addresses[i] != address(0), "Null address found"); _whiteList[addresses[i]] = true; _whiteListClaimed[addresses[i]] > 0 ? _whiteListClaimed[addresses[i]] : 0; } } function isWhitelisted(address addr) public view returns (bool) { return _whiteList[addr]; } function removeFromWhiteList(address[] calldata addresses) external onlyOwner { for (uint256 i = 0; i < addresses.length; i++) { require(addresses[i] != address(0), "Null address found"); _whiteList[addresses[i]] = false; } } // wallet of owner function for public => check the ownered ids for input address; function walletOfOwner(address ownerAddress) external view returns (uint256[] memory) { uint256 tokenCount = balanceOf(ownerAddress); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i = 0; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(ownerAddress, i); } return tokensId; } //withdraw functions for owner=> withdrawAll, withdraw certain amount; function withdrawAll() external onlyOwner { uint256 contractBalance = address(this).balance; require(contractBalance > 0,"insufficient balance."); _withdraw(owner(), contractBalance); } function withdraw(uint256 _withdrawAmount) external onlyOwner{ uint256 contractBalance = address(this).balance; require(contractBalance > 0,"insufficient balance."); require(_withdrawAmount <= contractBalance, "withdraw amount exceeds current contract balance"); _withdraw(owner(),_withdrawAmount); } function _withdraw(address _address, uint256 _amount) private { (bool success, ) = payable(_address).call{ value: _amount }(""); require(success, "Failed to widthdraw Ether"); } //set enable/disable switch for renounce or transfer ownership. In case irreparable loss caused by owner misoperation. function flipOwnershipChangable() external onlyOwner { isOwnershipChangable = !isOwnershipChangable; } function renounceOwnership() public onlyOwner override { require(isOwnershipChangable,"Renounce ownership disabled. flip changlable state to enable. Be careful renounceownership will leave the contract with no owner!"); _transferOwnership(address(0)); } function transferOwnership(address newOwner) public onlyOwner override { require(newOwner != address(0), "Ownable: new owner is the zero address"); require(isOwnershipChangable,"Changing ownership disabled. flip changlable state to enable. Be careful you are trying to transfer contract ownership to somebody else!"); require(newOwner != owner(),"The address is already the contract owner"); _transferOwnership(newOwner); } //tokenByIndex is for all NFTs, index starts from 0 whereas token starts from 1. //tokenOfOwnerByIndex is for NFT owners, index starts from 0 whereas token starts from 1. }
ensure presale is open;
require(isPresaleOpen, "Presale is not open");
13,820,040
[ 1, 15735, 4075, 5349, 353, 1696, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 12, 291, 12236, 5349, 3678, 16, 315, 12236, 5349, 353, 486, 1696, 8863, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-02-17 */ // SPDX-License-Identifier: MIT // Scroll down to the bottom to find the contract of interest. // 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/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; // import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // 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/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; // import "@openzeppelin/contracts/token/ERC721/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); } // 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/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/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/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; // import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; // import "@openzeppelin/contracts/utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: /Users/User/Documents/memotics/eth/contracts/NFT.sol // Creator: Chiru Labs pragma solidity ^0.8.4; // import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; // import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; // import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; // import "@openzeppelin/contracts/utils/Address.sol"; // import "@openzeppelin/contracts/utils/Context.sol"; // import "@openzeppelin/contracts/utils/Strings.sol"; // import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintedQueryForZeroAddress(); error BurnedQueryForZeroAddress(); error AuxQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerIndexOutOfBounds(); error OwnerQueryForNonexistentToken(); error TokenIndexOutOfBounds(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For storing miscellaneous variables. uint64 aux; } // The id of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } function _getAux(address owner) internal view returns (uint64) { if (owner == address(0)) revert AuxQueryForZeroAddress(); return _addressData[owner].aux; } function _setAux(address owner, uint64 aux) internal { if (owner == address(0)) revert AuxQueryForZeroAddress(); _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64 - 1) // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256 - 1) unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @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 { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } /** * @title ERC721A Burnable Token * @dev ERC721A Token that can be irreversibly burned (destroyed). */ abstract contract ERC721ABurnable is Context, ERC721A { /** * @dev Burns `tokenId`. See {ERC721A-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); _burn(tokenId); } } pragma solidity ^0.8.4; pragma abicoder v2; // import "@openzeppelin/contracts/utils/Strings.sol"; // import "@openzeppelin/contracts/access/Ownable.sol"; contract NeoFortuneTigers is ERC721A, ERC721ABurnable, Ownable { using Strings for uint256; /// @dev The amount of Ether in each token. mapping(uint256 => uint256) internal _funds; /// @dev The messages of the tokens. mapping(uint256 => string) internal _messages; /// @dev The revealed URI for token metadata. string internal _revealedURI; /// @dev The revealed URI postfix for token metadata. string internal _revealedURIPostfix; /// @dev The total amount of tokens that can be minted. uint16 public maxTokens = 8; /// @dev Whether the metadata is locked. bool public metadataLocked; /// @dev For gas optimization. bool private _reentrancyGuard; constructor() ERC721A("Neo Fortune Tigers", "NFT") {} modifier nonReentrant() { if (_reentrancyGuard) revert(); _reentrancyGuard = true; _; _reentrancyGuard = false; } /// @dev Locks all metadata. WARNING: Irreversible! function lockMetadata() external onlyOwner { if (bytes(_revealedURI).length == 0) revert(); metadataLocked = true; } /// @dev Sets base URI for all token IDs. function setRevealedURI(string calldata uri, string calldata postfix) external onlyOwner { if (metadataLocked) revert(); _revealedURI = uri; _revealedURIPostfix = postfix; } /// @dev Returns the total number minted. function totalMinted() public view returns (uint256) { return _currentIndex - _startTokenId(); } /// @dev Returns the total number burned. function totalBurned() public view returns (uint256) { return _burnCounter; } /// @dev Mints a batch. function _mintBatch(address to, uint256 quantity) internal { unchecked { if (totalMinted() + quantity > maxTokens) revert(); } _mint(to, quantity, "", false); } /// @dev Mint tokens for the creator. function selfMint(uint256 quantity) external onlyOwner { _mintBatch(msg.sender, quantity); } /// @dev Force mint for the addresses. function forceMint(address[] calldata to) external onlyOwner { unchecked { for (uint256 i; i < to.length; ++i) { _mintBatch(to[i], 1); } } } /// @dev Deposit Ether into the NFT. function depositFunds(uint256 id) external payable { _funds[id] += msg.value; } /// @dev Withdraw Ether from the NFT. function withdrawFunds(uint256 id) external nonReentrant { address sender = msg.sender; require(ownerOf(id) == sender, "Unauthorized!"); uint256 amount = _funds[id]; require(amount != 0, "No funds."); _funds[id] = 0; payable(sender).transfer(amount); } /// @dev Returns the amount of Ether in the NFTs. function fundsOf(uint256[] calldata ids) external view returns (uint256[] memory) { unchecked { uint256 n = ids.length; uint256[] memory a = new uint256[](n); for (uint256 i; i < n; ++i) { a[i] = _funds[ids[i]]; } return a; } } /// @dev Sets the message of the NFT. function setMessage(uint256 id, string calldata value) external { address sender = msg.sender; require(ownerOf(id) == sender, "Unauthorized!"); _messages[id] = value; } /// @dev Returns messages in the NFTs. function messagesOf(uint256[] calldata ids) external view returns (string[] memory) { unchecked { uint256 n = ids.length; string[] memory a = new string[](n); for (uint256 i; i < n; ++i) { a[i] = _messages[ids[i]]; } return a; } } /// @dev Returns the tokenURI for the token. function tokenURI(uint256 id) public view override returns (string memory) { require(_exists(id), "Token not found."); return string(abi.encodePacked(_revealedURI, id.toString(), _revealedURIPostfix)); } /// @dev Returns the tokenIds of the address. function tokensOfOwner(address owner) external view returns (uint256[] memory) { unchecked { uint256[] memory a = new uint256[](balanceOf(owner)); uint256 end = _currentIndex; uint256 tokenIdsIdx; address currOwnershipAddr; for (uint256 i; i < end; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { a[tokenIdsIdx++] = i; } } return a; } } /// @dev Returns the number of tokens minted by the address. function numberMinted(address owner) external view returns (uint256) { return _numberMinted(owner); } /// @dev Returns the number of tokens burned by the address. function numberBurned(address owner) external view returns (uint256) { return _numberBurned(owner); } /// @dev Returns the raw start timestamp of ownership of the token. function rawStartTimestampOf(uint256 id, bool burned) public view returns (uint256) { TokenOwnership memory ownership = _ownerships[id]; if (burned) { return ownership.burned ? ownership.startTimestamp : 0; } else { return ownership.burned ? 0 : ownershipOf(id).startTimestamp; } } /// @dev Returns the raw owner of the tokens. function rawOwnerOf(uint256 id, bool burned) public view returns (address) { TokenOwnership memory ownership = _ownerships[id]; if (burned) { return ownership.burned ? ownership.addr : address(0); } else { return ownership.burned ? address(0) : ownerOf(id); } } /// @dev Returns the raw start timestamp of ownership of the tokens. function rawStartTimestampsOf(uint256[] calldata ids, bool burned) external view returns (uint256[] memory) { unchecked { uint256 n = ids.length; uint256[] memory a = new uint256[](n); for (uint256 i; i < n; ++i) { a[i] = rawStartTimestampOf(ids[i], burned); } return a; } } /// @dev Returns the raw owners of the tokens. function rawOwnersOf(uint256[] calldata ids, bool burned) external view returns (address[] memory) { unchecked { uint256 n = ids.length; address[] memory a = new address[](n); for (uint256 i; i < n; ++i) { a[i] = rawOwnerOf(ids[i], burned); } return a; } } /// @dev See {IERC721-isApprovedForAll}. function isApprovedForAll(address owner, address operator) public view override returns (bool) { // OpenSea proxy registry addresses: // - Mainnet: 0xa5409ec958C83C3f309868babACA7c86DCB077c1 // - Rinkeby: 0xF57B2c51dED3A29e6891aba85459d600256Cf317 // Whitelist the proxy contract. return (operator == 0xa5409ec958C83C3f309868babACA7c86DCB077c1 || ERC721A.isApprovedForAll(owner, operator)); } /// @dev See {ERC721A-_startTokenId}. function _startTokenId() internal view virtual override returns (uint256) { return 1; } }
@dev Mint tokens for the creator.
function selfMint(uint256 quantity) external onlyOwner { _mintBatch(msg.sender, quantity); }
6,712,690
[ 1, 49, 474, 2430, 364, 326, 11784, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 365, 49, 474, 12, 11890, 5034, 10457, 13, 3903, 1338, 5541, 288, 203, 3639, 389, 81, 474, 4497, 12, 3576, 18, 15330, 16, 10457, 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 ]
pragma solidity ^0.5.0; import "openzeppelin-solidity/contracts/access/Roles.sol"; import "openzeppelin-solidity/contracts/access/roles/PauserRole.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; //import "github.com/OpenZeppelin/openzeppelin-solidity/contracts/access/Roles.sol"; //import "github.com/OpenZeppelin/openzeppelin-solidity/contracts/access/roles/PauserRole.sol"; //import "github.com/OpenZeppelin/openzeppelin-solidity/contracts/ownership/Ownable.sol"; /// @title Online Educational Platform /// @author Jafett Sandi /// @notice This contracts is not intended for Production use yet. /// @dev All function calls are currently implemented without side effects contract EducationPlatform is Ownable { using Roles for Roles.Role; // We want to use the Roles library Roles.Role universityOwners; //Stores University owner Roles Roles.Role teachers; // Stores teacher Roles Roles.Role students; // Stores student Roles; // ID Generators for universities and platform users uint public universityIdGenerator; uint public UserIdGenerator; mapping (uint => University) public universities; // Mapping to keep track of the Universities mapping (address => University) public mapUniversity; mapping (address => PlatformMember) public platformUsers; // Mapping to keep track of the Students in the platform address [] public platformUsersList; uint contractBalance; struct University { uint id; string name; string description; string website; string phoneNumber; bool open; uint courseIdGenerator; address payable UniversityOwner; mapping (uint => Course) courses; //Mappint to track all classes available for this University } // This structs is to store the information of a Platform member. Has a flag to identify if the member is Owner or not. struct PlatformMember { uint id; string fullName; string email; address userAddress; bool isUniversityOwner; } struct Course { uint id; string courseName; uint cost; uint courseBalance; bool active; uint activeStudents; uint seatsAvailable; //to simulate a student buying multiple seats for a course uint totalSeats; address payable courseOwner; } function getOwnerUniversity(address _ownerAddress) public view returns(uint id, string memory name, uint courseIdGenerator){ id = mapUniversity[_ownerAddress].id; name = mapUniversity[_ownerAddress].name; courseIdGenerator = mapUniversity[_ownerAddress].courseIdGenerator; return(id, name, courseIdGenerator); } /// @author Jafett Sandi /// @notice Gets a course based on an address and CourseId /// @param _ownerAddress The address of the owner of the course /// @param _courseId The id of the course /// @return courseName, cost, active, activeStudents, seatsAvailable, totalSeats function getOwnerCourseByAddress(address _ownerAddress, uint _courseId) public view returns(string memory courseName, uint cost, bool active, uint activeStudents, uint seatsAvailable, uint totalSeats) { courseName = mapUniversity[_ownerAddress].courses[_courseId].courseName; cost = mapUniversity[_ownerAddress].courses[_courseId].cost; active = mapUniversity[_ownerAddress].courses[_courseId].active; activeStudents = mapUniversity[_ownerAddress].courses[_courseId].activeStudents; seatsAvailable = mapUniversity[_ownerAddress].courses[_courseId].seatsAvailable; totalSeats = mapUniversity[_ownerAddress].courses[_courseId].totalSeats; return (courseName, cost, active, activeStudents, seatsAvailable, totalSeats); } function getNumberPlatformUser() public view returns(uint number){ number = platformUsersList.length; return number; } function isUnivOwner(address _address) public view returns(bool){ return universityOwners.bearer[_address]; } // Events event LogUniversityAdded(string name, string desc, uint universityId); event LogCourseAdded(string _courseName, uint cost, uint _seatsAvailable, uint courseId); // Modifiers modifier validAddress(address _address) { require(_address != address(0), "ADDRESS CANNOT BE THE ZERO ADDRESS"); _; } modifier isUniversityOwner(address _addr) { require(universityOwners.has(_addr), "DOES NOT HAVE UNIVERSITY OWNER ROLE"); _; } modifier isStudent(address _addr) { require(students.has(_addr), "DOES NOT HAVE STUDENT ROLE"); _; } modifier enoughSeats(uint _universityId, uint _courseId, uint _quantity) { require((universities[_universityId].courses[_courseId].seatsAvailable >= _quantity), "NOT ENOUGH SEATS IN THIS COURSE - CONTACT UNIVERSITY OWNER"); _; } modifier ownerAtUniversity(uint _universityId) { require((universities[_universityId].UniversityOwner == msg.sender), "DOES NOT BELONG TO THE UNIVERSITY OWNERS OR IS INACTIVE"); require(universityOwners.has(msg.sender), "DOES NOT HAVE UNIVERSITY OWNER ROLE"); _; } modifier courseIsActive(uint _universityId, uint _courseId) { require((universities[_universityId].courses[_courseId].active == true), "COURSE IS INACTIVE - CONTACT UNIVERSITY OWNER"); _; } modifier paidEnough(uint _universityId, uint _courseId, uint _quantity) { uint coursePrice = universities[_universityId].courses[_courseId].cost; require((universities[_universityId].courses[_courseId].seatsAvailable >= _quantity), "NOT ENOUGH SEATS IN THIS COURSE - CONTACT UNIVERSITY OWNER"); require(msg.value >= (coursePrice * _quantity), "NOT ENOUGH FEES PAID"); _; } modifier checkValue(uint _universityId, uint _courseId, uint _quantity, address payable _addr) { //refund them after pay for item _; uint coursePrice = universities[_universityId].courses[_courseId].cost * _quantity; uint total2RefundAfterPay = msg.value - coursePrice; _addr.transfer(total2RefundAfterPay); } modifier checkActive(uint _universityId, uint _courseId){ bool isActive = universities[_universityId].courses[_courseId].active; require(isActive == true, "THE COURSE IS NOT ACTIVE, YOU CANNOT REGISTER"); _; } /// @author Jafett Sandi /// @notice Adds a University to the platform /// @param _name The name of the University /// @param _description The description of the University /// @param _website The website URL of the University /// @param _phoneNumber The PhoneNumber of the University function addUniversity(string memory _name, string memory _description, string memory _website, string memory _phoneNumber) public onlyOwner { University memory newUniversity; newUniversity.name = _name; newUniversity.description = _description; newUniversity.website = _website; newUniversity.phoneNumber = _phoneNumber; newUniversity.open = false; newUniversity.id = universityIdGenerator; universities[universityIdGenerator] = newUniversity; universityIdGenerator += 1; emit LogUniversityAdded(_name, _description, universityIdGenerator); } /// @author Jafett Sandi /// @notice Adds a course to a University /// @param _universityId The id of the University /// @param _courseName The name of the course /// @param _cost Thecost of the course /// @param _seatsAvailable The seatsAvailablefor the course /// @return true function addCourse(uint _universityId, string memory _courseName, uint _cost, uint _seatsAvailable) public ownerAtUniversity(_universityId) returns (bool) { Course memory newCourse; newCourse.courseName = _courseName; newCourse.seatsAvailable = _seatsAvailable; newCourse.totalSeats = _seatsAvailable; newCourse.cost = _cost; newCourse.active = true; newCourse.activeStudents = 0; newCourse.courseOwner = universities[_universityId].UniversityOwner; uint courseId = universities[_universityId].courseIdGenerator; newCourse.id = courseId; universities[_universityId].courses[courseId] = newCourse; universities[_universityId].courseIdGenerator += 1; emit LogCourseAdded(_courseName, _cost, _seatsAvailable, courseId); return true; } /// @author Jafett Sandi /// @notice Updates a course's information /// @param _universityId The id of the University /// @param _courseId The id of the course to update /// @param _courseName The name of the course /// @param _cost Thecost of the course /// @param _seatsAvailable The seatsAvailablefor the course /// @param _isActive Is the course active? /// @return true function updateCourse(uint _universityId, uint _courseId, string memory _courseName, uint _cost, uint _seatsAvailable, bool _isActive) public ownerAtUniversity(_universityId) returns (bool) { Course memory newCourse; newCourse.courseName = _courseName; newCourse.seatsAvailable = _seatsAvailable; newCourse.totalSeats = _seatsAvailable; newCourse.cost = _cost; newCourse.active = _isActive; universities[_universityId].courses[_courseId] = newCourse; return true; } /// @author Jafett Sandi /// @notice Get University details /// @param _uniId The id of the University /// @return _uniId, name, description, website, phone function getUniversity(uint _uniId) public view returns (uint id, string memory name, string memory description, string memory website, string memory phone) { name = universities[_uniId].name; website = universities[_uniId].website; description = universities[_uniId].description; phone = universities[_uniId].phoneNumber; return (_uniId, name, description, website, phone); } /// @author Jafett Sandi /// @notice Used to generate a courseId /// @param _universityId The id of the University /// @return courseId function getCourseId (uint _universityId) public view returns(uint){ uint courseIdGenerator = universities[_universityId].courseIdGenerator; return courseIdGenerator; } /// @author Jafett Sandi /// @notice Get the owner of a university /// @param _universityId The id of the University /// @return universityOwner Address of the university owner function getUniversityOwner (uint _universityId) public view returns(address universityOwner){ universityOwner = universities[_universityId].UniversityOwner; return universityOwner; } /// @author Jafett Sandi /// @notice Get the details of a university course /// @param _universityId The id of the University /// @param _courseId The courseId of the course /// @return All information about a course function getUniversityCourse(uint _universityId, uint _courseId) public view returns( uint universityId, uint courseId, string memory courseName, uint cost, bool active, uint activeStudents, uint seatsAvailable, uint totalSeats, uint balance){ courseName = universities[_universityId].courses[_courseId].courseName; courseId = universities[_universityId].courses[_courseId].id; cost = universities[_universityId].courses[_courseId].cost; active = universities[_universityId].courses[_courseId].active; activeStudents = universities[_universityId].courses[_courseId].activeStudents; seatsAvailable = universities[_universityId].courses[_courseId].seatsAvailable; totalSeats = universities[_universityId].courses[_courseId].totalSeats; balance = universities[_universityId].courses[_courseId].courseBalance; return (universityId, courseId, courseName, cost, active, activeStudents, seatsAvailable, totalSeats,balance); } /// @author Jafett Sandi /// @notice Toggles the state of a course /// @param _universityId The id of the University /// @param _courseId The id of the course /// @param _state The state to toggle the course function toggleActiveCourse(uint _universityId, uint _courseId, bool _state) public { universities[_universityId].courses[_courseId].active = _state; } /// @author Jafett Sandi /// @notice Gets a platform member information /// @param _address The address of the member /// @return All information about a platform member function getPlatformMember(address _address) public view returns ( uint id, string memory fullname, string memory email, address userAddress, bool isUnivOwner) { fullname = platformUsers[_address].fullName; email = platformUsers[_address].email; id = platformUsers[_address].id; userAddress = platformUsers[_address].userAddress; isUnivOwner = platformUsers[_address].isUniversityOwner; return (id, fullname, email, userAddress, isUnivOwner); } /* Roles and membership */ /// @author Jafett Sandi /// @notice Adds an owner to the platform /// @param _ownerAddr The address of the member /// @param _universityId The id of the University /// @param _name The name of the owner of the University /// @param _email The email address of the member /// @return bool function addUniversityOwner(address payable _ownerAddr, uint _universityId, string memory _name, string memory _email) public onlyOwner validAddress(_ownerAddr) returns (bool) { PlatformMember memory newPlatformMember; newPlatformMember.fullName = _name; newPlatformMember.email = _email; newPlatformMember.id = UserIdGenerator; newPlatformMember.isUniversityOwner = true; newPlatformMember.userAddress = _ownerAddr; universityOwners.add(_ownerAddr); platformUsers[_ownerAddr] = newPlatformMember; UserIdGenerator += 1; universities[_universityId].UniversityOwner = _ownerAddr; universities[_universityId].open = true; mapUniversity[_ownerAddr] = universities[_universityId]; platformUsersList.push(_ownerAddr); return true; } /// @author Jafett Sandi /// @notice Registers a new user into the Platform - Owner or Student /// @param _addr The address of the member /// @param _name The name of the member /// @param _email The email address of the member /// @return bool function addStudent(address _addr, string memory _name, string memory _email) public validAddress(_addr) returns (bool) { PlatformMember memory newPlatformMember; newPlatformMember.fullName = _name; newPlatformMember.email = _email; newPlatformMember.id = UserIdGenerator; students.add(_addr); newPlatformMember.isUniversityOwner = false; platformUsers[_addr] = newPlatformMember; UserIdGenerator += 1; return true; } function getCourseBalance(uint _univId ,uint _courseId) public view returns (uint){ return universities[_univId].courses[_courseId].courseBalance; } /* Students specific functions - Buy/Pay course */ /// @author Jafett Sandi /// @notice Buy a course /// @param _uniId The id of the university /// @param _courseId The id of the course /// @param _quantity The number of seats to buy function buyCourse(uint _uniId, uint _courseId, uint _quantity) public payable //isStudent(msg.sender) //checkValue(_uniId, _courseId, _quantity, msg.sender) paidEnough(_uniId, _courseId, _quantity) checkActive(_uniId, _courseId) { universities[_uniId].courses[_courseId].courseBalance += msg.value; universities[_uniId].courses[_courseId].seatsAvailable -= _quantity; } /// @author Jafett Sandi /// @notice Withdraw the course funds /// @param _uniId The id of the university /// @param _courseId The id of the course function withdrawCourseFunds(uint _uniId, uint _courseId) public payable { require(msg.sender == universities[_uniId].courses[_courseId].courseOwner, "Need to be the course owner"); uint courseBalance = universities[_uniId].courses[_courseId].courseBalance; universities[_uniId].courses[_courseId].courseBalance = 0; msg.sender.transfer(courseBalance); } }
Mapping to keep track of the Students in the platform
mapping (address => PlatformMember) public platformUsers;
5,493,409
[ 1, 3233, 358, 3455, 3298, 434, 326, 934, 1100, 4877, 316, 326, 4072, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 261, 2867, 516, 11810, 4419, 13, 1071, 4072, 6588, 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 ]
./partial_match/1/0x2F1901f2A82fcC3Ee9010b809938816B3b06FA6A/sources/GasStationExact.sol
* @notice Withdraws the contract balance @param amount The amount of eth (in wei) to withdraw @param payee The address to pay/
function withdraw(uint256 amount, address payable payee) external onlyOwner { if (payee == address(0)) { revert ZeroAddress(); } emit FundsWithdrawn(amount, payee); payee.transfer(amount); }
2,604,647
[ 1, 1190, 9446, 87, 326, 6835, 11013, 225, 3844, 1021, 3844, 434, 13750, 261, 267, 732, 77, 13, 358, 598, 9446, 225, 8843, 1340, 1021, 1758, 358, 8843, 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, 225, 445, 598, 9446, 12, 11890, 5034, 3844, 16, 1758, 8843, 429, 8843, 1340, 13, 3903, 1338, 5541, 288, 203, 565, 309, 261, 10239, 1340, 422, 1758, 12, 20, 3719, 288, 203, 1377, 15226, 12744, 1887, 5621, 203, 565, 289, 203, 565, 3626, 478, 19156, 1190, 9446, 82, 12, 8949, 16, 8843, 1340, 1769, 203, 565, 8843, 1340, 18, 13866, 12, 8949, 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 ]
./full_match/8453/0x4732Cf2CC6435f3AF3DB9723c0CE0C781d326F52/sources/contracts/providers/EtherVault.sol
* arnWithdrawal Functions exactly like #withdrawal, but takes an ARN. For this provider, it will revert if the arn isn't ethereum. @param keyId the key you want to use to withdrawal with/from @param arn the asset resource name to withdrawal @param amount the amount of ether, in gwei, to withdrawal from the balance./ ensure that the arn is the ethereum arn use a standard withdrawal
function arnWithdrawal(uint256 keyId, bytes32 arn, uint256 amount) external { require(arn == ethArn, 'INVALID_ARN'); _withdrawal(keyId, amount); }
11,564,334
[ 1, 1303, 1190, 9446, 287, 15486, 8950, 3007, 598, 9446, 287, 16, 1496, 5530, 392, 15767, 18, 2457, 333, 2893, 16, 518, 903, 15226, 309, 326, 26399, 5177, 1404, 13750, 822, 379, 18, 225, 30914, 225, 326, 498, 1846, 2545, 358, 999, 358, 598, 9446, 287, 598, 19, 2080, 225, 26399, 565, 326, 3310, 1058, 508, 358, 598, 9446, 287, 225, 3844, 326, 3844, 434, 225, 2437, 16, 316, 314, 1814, 77, 16, 358, 598, 9446, 287, 628, 326, 11013, 18, 19, 3387, 716, 326, 26399, 353, 326, 13750, 822, 379, 26399, 999, 279, 4529, 598, 9446, 287, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 26399, 1190, 9446, 287, 12, 11890, 5034, 30914, 16, 1731, 1578, 26399, 16, 2254, 5034, 3844, 13, 3903, 288, 203, 3639, 2583, 12, 1303, 422, 13750, 5046, 16, 296, 9347, 67, 4391, 8284, 203, 203, 3639, 389, 1918, 9446, 287, 12, 856, 548, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.2; // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol interface IERC20 { function TRANSFER40(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function APPROVE301(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM794(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TOTALSUPPLY553() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF929(address who) external view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE927(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING event TRANSFER76(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL126(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.2; library SafeMath { function MUL714(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-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function DIV136(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function SUB719(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); uint256 c = a - b; return c; } function ADD820(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MOD689(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.2; contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; function TOTALSUPPLY553() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF929(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[owner]; } function ALLOWANCE927(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowed[owner][spender]; } function TRANSFER40(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER980(msg.sender, to, value); return true; } function APPROVE301(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE717(msg.sender, spender, value); return true; } function TRANSFERFROM794(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER980(from, to, value); _APPROVE717(from, msg.sender, _allowed[from][msg.sender].SUB719(value)); return true; } function INCREASEALLOWANCE41(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE717(msg.sender, spender, _allowed[msg.sender][spender].ADD820(addedValue)); return true; } function DECREASEALLOWANCE194(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE717(msg.sender, spender, _allowed[msg.sender][spender].SUB719(subtractedValue)); return true; } function _TRANSFER980(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(to != address(0)); _balances[from] = _balances[from].SUB719(value); _balances[to] = _balances[to].ADD820(value); emit TRANSFER76(from, to, value); } function _MINT201(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.ADD820(value); _balances[account] = _balances[account].ADD820(value); emit TRANSFER76(address(0), account, value); } function _BURN23(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.SUB719(value); _balances[account] = _balances[account].SUB719(value); emit TRANSFER76(account, address(0), value); } function _APPROVE717(address owner, address spender, uint256 value) internal { //inject NONSTANDARD NAMING require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit APPROVAL126(owner, spender, value); } function _BURNFROM444(address account, uint256 value) internal { //inject NONSTANDARD NAMING _BURN23(account, value); _APPROVE717(account, msg.sender, _allowed[account][msg.sender].SUB719(value)); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.2; contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function NAME174() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL647() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS617() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol pragma solidity ^0.5.2; contract ERC20Burnable is ERC20 { function BURN273(uint256 value) public { //inject NONSTANDARD NAMING _BURN23(msg.sender, value); } function BURNFROM876(address from, uint256 value) public { //inject NONSTANDARD NAMING _BURNFROM444(from, value); } } // File: contracts/BNS.sol pragma solidity ^0.5.0; contract BNS is ERC20, ERC20Detailed, ERC20Burnable { constructor() ERC20Detailed('BNS Token', 'BNS', 8) public { _MINT201(msg.sender, 2_500_000_000 * 10 ** 8); } }
inject NONSTANDARD NAMING
function ALLOWANCE927(address owner, address spender) public view returns (uint256) {
7,307,571
[ 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, 445, 18592, 4722, 29, 5324, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 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 ]
pragma solidity ^0.5.16; import "./CappedDelivery.sol"; /** * @title MintedCappedDelivery * @author Vittorio Minacori (https://github.com/vittominacori) * @dev Contract to distribute tokens by mint function */ contract MintedCappedDelivery is CappedDelivery { /** * @param token Address of the token being distributed * @param cap Max amount of token to be distributed * @param allowMultipleSend Allow multiple send to same address */ constructor(address token, uint256 cap, bool allowMultipleSend) public CappedDelivery(token, cap, allowMultipleSend) {} // solhint-disable-line no-empty-blocks /** * @dev distribute token * @param account Address being distributing * @param amount Amount of token distributed */ function _distributeTokens(address account, uint256 amount) internal { _token.mint(account, amount); } }
* @param token Address of the token being distributed @param cap Max amount of token to be distributed @param allowMultipleSend Allow multiple send to same address/* @dev distribute token @param account Address being distributing @param amount Amount of token distributed/
function _distributeTokens(address account, uint256 amount) internal { _token.mint(account, amount); }
13,027,346
[ 1, 2316, 5267, 434, 326, 1147, 3832, 16859, 225, 3523, 4238, 3844, 434, 1147, 358, 506, 16859, 225, 1699, 8438, 3826, 7852, 3229, 1366, 358, 1967, 1758, 19, 225, 25722, 1147, 225, 2236, 5267, 3832, 1015, 665, 8490, 225, 3844, 16811, 434, 1147, 16859, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2251, 887, 5157, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 2713, 288, 203, 3639, 389, 2316, 18, 81, 474, 12, 4631, 16, 3844, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-03-12 */ // SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.9; interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view 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); } pragma solidity >=0.5.0; interface IWETH { function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } /** * @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; } } abstract contract Context { //function _msgSender() internal view virtual returns (address payable) { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @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); } } } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { 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; } } pragma solidity >=0.5.0; interface IDEGENSwapFactory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function pairExist(address pair) external view returns (bool); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; function routerInitialize(address) external; function routerAddress() external view returns (address); } pragma solidity >=0.5.0; interface IDEGENSwapPair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function baseToken() external view returns (address); function getTotalFee() external view returns (uint); 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 updateTotalFee(uint totalFee) external returns (bool); 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, address _baseToken); 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, uint amount0Fee, uint amount1Fee, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; function setBaseToken(address _baseToken) external; } pragma solidity >=0.6.2; interface IDEGENSwapRouter01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } pragma solidity >=0.6.2; interface IDEGENSwapRouter is IDEGENSwapRouter01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function pairFeeAddress(address pair) external view returns (address); function adminFee() external view returns (uint256); function feeAddressGet() external view returns (address); } contract TheRareAntiquitiesTokenLtd is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; address public WETH; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; mapping (address => bool) private botWallets; bool botscantrade = false; bool public canTrade = false; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 500000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; address public marketingWallet; // marketing wallet address address public antiquitiesWallet; // antiquities Wallet address string private _name = "The Rare Antiquities Token Ltd"; string private _symbol = "RAT"; uint8 private _decimals = 9; uint256 private _taxFee = 100; // reflection tax in BPS uint256 private _previousTaxFee = _taxFee; uint256 private _liquidityFee; // this variable is unused, ignore this, do NOT change! uint256 private _previousLiquidityFee = _liquidityFee; uint256 private _marketingFee = 200; // marketing tax in BPS | 200 = 2% uint256 private _antiquitiesFee = 300; // antiquities tax in BPS uint256 public _totalTax = _taxFee + _marketingFee + _antiquitiesFee; IDEGENSwapRouter public degenSwapRouter; address public degenSwapPair; address public depwallet; uint256 public _maxTxAmount = 500000000000 * 10**9; // total supply by default, can be changed at will uint256 public _maxWallet = 5000000000 * 10**9; // 1% max wallet by default, can be changed at will modifier onlyExchange() { bool isPair = false; if(msg.sender == degenSwapPair) isPair = true; require( msg.sender == address(degenSwapRouter) || isPair , "DEGEN: NOT_ALLOWED" ); _; } constructor (address _marketingWallet, address _antiquitiesWallet) { _rOwned[_msgSender()] = _rTotal; marketingWallet = _marketingWallet; antiquitiesWallet = _antiquitiesWallet; degenSwapRouter = IDEGENSwapRouter(0x4bf3E2287D4CeD7796bFaB364C0401DFcE4a4f7F); //DegenSwap Router 0x4bf3E2287D4CeD7796bFaB364C0401DFcE4a4f7F WETH = degenSwapRouter.WETH(); // Create a uniswap pair for this new token degenSwapPair = IDEGENSwapFactory(degenSwapRouter.factory()) .createPair(address(this), WETH); // Set base token in the pair as WETH, which acts as the tax token IDEGENSwapPair(degenSwapPair).setBaseToken(WETH); IDEGENSwapPair(degenSwapPair).updateTotalFee(_marketingFee + _antiquitiesFee); _approve(_msgSender(), address(degenSwapRouter), _tTotal); depwallet = 0xa27445dD0Fbe56B95C2401076f03d26C8E61F312; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[depwallet] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) public { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) public onlyOwner() { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _updatePairsFee(uint256 fee) internal { IDEGENSwapPair(degenSwapPair).updateTotalFee(fee); } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function setMarketingWallet(address walletAddress) public onlyOwner { marketingWallet = walletAddress; } function setAntiquitiesWallet(address walletAddress) public onlyOwner { antiquitiesWallet = walletAddress; } function _setmaxwalletamount(uint256 amount) external onlyOwner() { require(amount >= 2500000000, "ERR: max wallet amount should exceed 0.5% of the supply"); _maxWallet = amount * 10**9; } function setmaxTxAmount(uint256 amount) external onlyOwner() { require(amount >= 2500000000, "ERR: max tx amount should exceed 0.5% of the supply"); _maxTxAmount = amount * 10**9; } function clearStuckBalance() public { payable(marketingWallet).transfer(address(this).balance); } function claimERCtoknes(IERC20 tokenAddress) external { tokenAddress.transfer(marketingWallet, tokenAddress.balanceOf(address(this))); } function addBotWallet(address botwallet) external onlyOwner() { require(botwallet != degenSwapPair,"Cannot add pair as a bot"); require(botwallet != address(this),"Cannot add CA as a bot"); botWallets[botwallet] = true; } function removeBotWallet(address botwallet) external onlyOwner() { botWallets[botwallet] = false; } function getBotWalletStatus(address botwallet) public view returns (bool) { return botWallets[botwallet]; } function EnableTrading()external onlyOwner() { canTrade = true; } function setFees(uint256 _reflectionTaxBPS, uint256 _marketingTaxBPS, uint256 _antiquitiesTaxBPS) public onlyOwner { _taxFee = _reflectionTaxBPS; _marketingFee = _marketingTaxBPS; _antiquitiesFee = _antiquitiesTaxBPS; _totalTax = _taxFee + _marketingFee + _antiquitiesFee; require(_totalTax <= 1500, "total tax cannot exceed 15%"); require((_marketingFee + _antiquitiesFee) >= 100, "ERR: marketing + antiquities tax must be over 1%"); _updatePairsFee(_marketingFee + _antiquitiesFee); } function setBaseToken() public onlyOwner { IDEGENSwapPair(degenSwapPair).setBaseToken(WETH); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div( 10**4 ); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div( 10**4 ); } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _liquidityFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == degenSwapPair && to != depwallet) { require(balanceOf(to) + amount <= _maxWallet, "check max wallet"); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!canTrade){ require(sender == owner()); // only owner allowed to trade or add liquidity } if(botWallets[sender] || botWallets[recipient]){ require(botscantrade, "bots arent allowed to trade"); } if(!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function depositLPFee(uint256 amount, address token) public onlyExchange { uint256 allowanceT = IERC20(token).allowance(msg.sender, address(this)); if(allowanceT >= amount) { IERC20(token).transferFrom(msg.sender, address(this), amount); // _marketingFee + _antiquitiesFee antiquitiesWallet // calculate individual tax amount uint256 marketingAmount = (amount * _marketingFee) / (_marketingFee + _antiquitiesFee); uint256 antiquitiesAmount = amount - marketingAmount; // send WETH to respective wallet IERC20(token).transfer(marketingWallet, marketingAmount); IERC20(token).transfer(antiquitiesWallet, antiquitiesAmount); } } }
this variable is unused, ignore this, do NOT change!
uint256 private _liquidityFee;
10,931,988
[ 1, 2211, 2190, 353, 10197, 16, 2305, 333, 16, 741, 4269, 2549, 5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 3238, 389, 549, 372, 24237, 14667, 31, 377, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/44787/0xA49C2beE46A80c17A1B26DCADe088AFB19687AB5/sources/contracts/SpecificGroupStrategy.sol
* @notice Returns the number of blocked group strategies. @return The length of blocked groups./
function getNumberOfBlockedStrategies() external view returns (uint256) { return blockedStrategies.length(); }
13,251,080
[ 1, 1356, 326, 1300, 434, 14547, 1041, 20417, 18, 327, 1021, 769, 434, 14547, 3252, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 14981, 23722, 1585, 15127, 1435, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 14547, 1585, 15127, 18, 2469, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x97549c25F5d51c5174Fb078e6d1b96032F9e393c/sources/contracts/configuration/ConfigurationManager.sol
* @inheritdoc IConfigurationManager/
function setCap(address target, uint256 value) external override onlyOwner { if (target == address(0)) revert ConfigurationManager__TargetCannotBeTheZeroAddress(); _caps[target] = value; emit SetCap(target, value); }
16,393,522
[ 1, 36, 10093, 467, 1750, 1318, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 4664, 12, 2867, 1018, 16, 2254, 5034, 460, 13, 3903, 3849, 1338, 5541, 288, 203, 3639, 309, 261, 3299, 422, 1758, 12, 20, 3719, 15226, 4659, 1318, 972, 2326, 4515, 1919, 1986, 7170, 1887, 5621, 203, 3639, 389, 22984, 63, 3299, 65, 273, 460, 31, 203, 3639, 3626, 1000, 4664, 12, 3299, 16, 460, 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 ]
./full_match/1/0x56102B469d7B0650E92426611Eb2Ea84C0cA9b2A/sources/contracts/QuestFactory.sol
@dev Create an erc20 quest @param rewardTokenAddress_ The contract address of the reward token @param endTime_ The end time of the quest @param startTime_ The start time of the quest @param totalParticipants_ The total amount of participants (accounts) the quest will have @param rewardAmount_ The reward amount for an erc20 quest @param questId_ The id of the quest @return address the quest contract address
function createQuest( address rewardTokenAddress_, uint256 endTime_, uint256 startTime_, uint256 totalParticipants_, uint256 rewardAmount_, string memory questId_ ) external checkQuest(questId_, rewardTokenAddress_) returns (address) { address newQuest = createQuestInternal( rewardTokenAddress_, endTime_, startTime_, totalParticipants_, rewardAmount_, questId_, 0 ); QuestContract(newQuest).transferOwnership(msg.sender); return newQuest; }
3,008,727
[ 1, 1684, 392, 6445, 71, 3462, 225, 456, 225, 19890, 1345, 1887, 67, 1021, 6835, 1758, 434, 326, 19890, 1147, 225, 13859, 67, 1021, 679, 813, 434, 326, 225, 456, 225, 8657, 67, 1021, 787, 813, 434, 326, 225, 456, 225, 2078, 1988, 27620, 67, 1021, 2078, 3844, 434, 22346, 261, 13739, 13, 326, 225, 456, 903, 1240, 225, 19890, 6275, 67, 1021, 19890, 3844, 364, 392, 6445, 71, 3462, 225, 456, 225, 225, 456, 548, 67, 1021, 612, 434, 326, 225, 456, 327, 1758, 326, 225, 456, 6835, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 752, 30791, 12, 203, 3639, 1758, 19890, 1345, 1887, 67, 16, 203, 3639, 2254, 5034, 13859, 67, 16, 203, 3639, 2254, 5034, 8657, 67, 16, 203, 3639, 2254, 5034, 2078, 1988, 27620, 67, 16, 203, 3639, 2254, 5034, 19890, 6275, 67, 16, 203, 3639, 533, 3778, 225, 456, 548, 67, 203, 565, 262, 3903, 866, 30791, 12, 456, 548, 67, 16, 19890, 1345, 1887, 67, 13, 1135, 261, 2867, 13, 288, 203, 3639, 1758, 394, 30791, 273, 752, 30791, 3061, 12, 203, 5411, 19890, 1345, 1887, 67, 16, 203, 5411, 13859, 67, 16, 203, 5411, 8657, 67, 16, 203, 5411, 2078, 1988, 27620, 67, 16, 203, 5411, 19890, 6275, 67, 16, 203, 5411, 225, 456, 548, 67, 16, 203, 5411, 374, 203, 3639, 11272, 203, 203, 3639, 4783, 395, 8924, 12, 2704, 30791, 2934, 13866, 5460, 12565, 12, 3576, 18, 15330, 1769, 203, 203, 3639, 327, 394, 30791, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/97/0x8B4032b71C804517D54878d78730c230F768Ad57/sources/tests/BSC ChainLinkTests/PWA.sol
/ Projects functionality/ lists a new project address addr = address(bytes20(bytes(_address))); IERC20 projectTokenAddr = IERC20(addr);
function listProject( address _address, string memory _logoURI, string memory _sparklineURI ) public onlyOwner { PWProject memory tolist = PWProject( _logoURI, _sparklineURI, ); projects.push(tolist); projectsIds[_address] = projectCount; projectCount++; emit ProjectListed(msg.sender, _address); }
5,018,642
[ 1, 19, 30491, 14176, 19, 6035, 279, 394, 1984, 1758, 3091, 273, 1758, 12, 3890, 3462, 12, 3890, 24899, 2867, 3719, 1769, 467, 654, 39, 3462, 1984, 1345, 3178, 273, 467, 654, 39, 3462, 12, 4793, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 666, 4109, 12, 203, 3639, 1758, 389, 2867, 16, 203, 3639, 533, 3778, 389, 19882, 3098, 16, 203, 3639, 533, 3778, 389, 27559, 1369, 3098, 203, 565, 262, 1071, 1338, 5541, 288, 203, 3639, 453, 59, 4109, 3778, 14978, 273, 453, 59, 4109, 12, 203, 5411, 389, 19882, 3098, 16, 203, 5411, 389, 27559, 1369, 3098, 16, 203, 3639, 11272, 203, 203, 3639, 10137, 18, 6206, 12, 3490, 376, 1769, 203, 3639, 10137, 2673, 63, 67, 2867, 65, 273, 1984, 1380, 31, 203, 3639, 1984, 1380, 9904, 31, 203, 203, 3639, 3626, 5420, 682, 329, 12, 3576, 18, 15330, 16, 389, 2867, 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 ]
./full_match/4/0x342d7feB4f753693CC83a5D73F5E73d643038bFa/sources/contracts/BondDepository.sol
to auto-stake payout
IStaking public staking;
648,685
[ 1, 869, 3656, 17, 334, 911, 293, 2012, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 467, 510, 6159, 1071, 384, 6159, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IAssetManager.sol"; // This contract is owned by Timelock. contract AssetManager is IAssetManager, Ownable { struct Asset { address token; address policy; uint8 category; // 0 - low, 1 - medium, 2 - high bool deprecated; } Asset[] public assets; // Every asset have a unique index. mapping(uint8 => uint256[]) private indexesByCategory; function setAsset(uint256 index_, address token_, address policy_, uint8 category_) external onlyOwner { if (index_ < assets.length) { assets[index_].token = token_; assets[index_].policy = policy_; assets[index_].category = category_; } else { Asset memory asset; asset.token = token_; asset.policy = policy_; asset.category = category_; assets.push(asset); } } function resetIndexesByCategory(uint8 category_) external { delete indexesByCategory[category_]; for (uint256 i = 0; i < assets.length; ++i) { if (assets[i].category == category_ && !assets[i].deprecated) { indexesByCategory[category_].push(i); } } } function getCategoryLength() external override view returns(uint8) { return 3; // May update in the future. } function getAssetLength() external override view returns(uint256) { return assets.length; } function getAssetToken(uint256 index_) external override view returns(address) { return assets[index_].token; } function getAssetPolicy(uint256 index_) external override view returns(address) { return assets[index_].policy; } function getAssetCategory(uint256 index_) external override view returns(uint8) { return assets[index_].category; } function getIndexesByCategory(uint8 category_, uint256 categoryIndex_) external override view returns(uint256) { return indexesByCategory[category_][categoryIndex_]; } function getIndexesByCategoryLength(uint8 category_) external override view returns(uint256) { return indexesByCategory[category_].length; } }
This contract is owned by Timelock.
contract AssetManager is IAssetManager, Ownable { pragma solidity 0.6.12; struct Asset { address token; address policy; bool deprecated; } mapping(uint8 => uint256[]) private indexesByCategory; function setAsset(uint256 index_, address token_, address policy_, uint8 category_) external onlyOwner { if (index_ < assets.length) { assets[index_].token = token_; assets[index_].policy = policy_; assets[index_].category = category_; Asset memory asset; asset.token = token_; asset.policy = policy_; asset.category = category_; assets.push(asset); } } function setAsset(uint256 index_, address token_, address policy_, uint8 category_) external onlyOwner { if (index_ < assets.length) { assets[index_].token = token_; assets[index_].policy = policy_; assets[index_].category = category_; Asset memory asset; asset.token = token_; asset.policy = policy_; asset.category = category_; assets.push(asset); } } } else { function resetIndexesByCategory(uint8 category_) external { delete indexesByCategory[category_]; for (uint256 i = 0; i < assets.length; ++i) { if (assets[i].category == category_ && !assets[i].deprecated) { indexesByCategory[category_].push(i); } } } function resetIndexesByCategory(uint8 category_) external { delete indexesByCategory[category_]; for (uint256 i = 0; i < assets.length; ++i) { if (assets[i].category == category_ && !assets[i].deprecated) { indexesByCategory[category_].push(i); } } } function resetIndexesByCategory(uint8 category_) external { delete indexesByCategory[category_]; for (uint256 i = 0; i < assets.length; ++i) { if (assets[i].category == category_ && !assets[i].deprecated) { indexesByCategory[category_].push(i); } } } function getCategoryLength() external override view returns(uint8) { } function getAssetLength() external override view returns(uint256) { return assets.length; } function getAssetToken(uint256 index_) external override view returns(address) { return assets[index_].token; } function getAssetPolicy(uint256 index_) external override view returns(address) { return assets[index_].policy; } function getAssetCategory(uint256 index_) external override view returns(uint8) { return assets[index_].category; } function getIndexesByCategory(uint8 category_, uint256 categoryIndex_) external override view returns(uint256) { return indexesByCategory[category_][categoryIndex_]; } function getIndexesByCategoryLength(uint8 category_) external override view returns(uint256) { return indexesByCategory[category_].length; } }
5,381,931
[ 1, 2503, 6835, 353, 16199, 635, 12652, 292, 975, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 10494, 1318, 353, 467, 6672, 1318, 16, 14223, 6914, 288, 203, 203, 683, 9454, 18035, 560, 374, 18, 26, 18, 2138, 31, 203, 565, 1958, 10494, 288, 203, 3639, 1758, 1147, 31, 203, 3639, 1758, 3329, 31, 203, 3639, 1426, 6849, 31, 203, 565, 289, 203, 203, 203, 565, 2874, 12, 11890, 28, 516, 2254, 5034, 63, 5717, 3238, 5596, 858, 4457, 31, 203, 203, 565, 445, 444, 6672, 12, 11890, 5034, 770, 67, 16, 1758, 1147, 67, 16, 1758, 3329, 67, 16, 2254, 28, 3150, 67, 13, 3903, 1338, 5541, 288, 203, 3639, 309, 261, 1615, 67, 411, 7176, 18, 2469, 13, 288, 203, 5411, 7176, 63, 1615, 67, 8009, 2316, 273, 1147, 67, 31, 203, 5411, 7176, 63, 1615, 67, 8009, 5086, 273, 3329, 67, 31, 203, 5411, 7176, 63, 1615, 67, 8009, 4743, 273, 3150, 67, 31, 203, 5411, 10494, 3778, 3310, 31, 203, 5411, 3310, 18, 2316, 273, 1147, 67, 31, 203, 5411, 3310, 18, 5086, 273, 3329, 67, 31, 203, 5411, 3310, 18, 4743, 273, 3150, 67, 31, 203, 5411, 7176, 18, 6206, 12, 9406, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 444, 6672, 12, 11890, 5034, 770, 67, 16, 1758, 1147, 67, 16, 1758, 3329, 67, 16, 2254, 28, 3150, 67, 13, 3903, 1338, 5541, 288, 203, 3639, 309, 261, 1615, 67, 411, 7176, 18, 2469, 13, 288, 203, 5411, 7176, 63, 1615, 67, 8009, 2316, 273, 1147, 67, 31, 203, 5411, 7176, 63, 1615, 67, 8009, 5086, 273, 3329, 67, 31, 203, 2 ]
pragma solidity 0.4.24; // // /// // // // // // // //company_2 // // // //demo //wallet2 //new ICO Sep28 //company_2 //DefaultOffer //DefaultOffer //new for company_2 //FOR PRODUCTION //New Offer /** * @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&#39;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. */ constructor(address _owner) public { owner = _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Whitelist is Ownable { mapping(address => bool) internal investorMap; /** * event for investor approval logging * @param investor approved investor */ event Approved(address indexed investor); /** * event for investor disapproval logging * @param investor disapproved investor */ event Disapproved(address indexed investor); constructor(address _owner) public Ownable(_owner) { } /** @param _investor the address of investor to be checked * @return true if investor is approved */ function isInvestorApproved(address _investor) external view returns (bool) { require(_investor != address(0)); return investorMap[_investor]; } /** @dev approve an investor * @param toApprove investor to be approved */ function approveInvestor(address toApprove) external onlyOwner { investorMap[toApprove] = true; emit Approved(toApprove); } /** @dev approve investors in bulk * @param toApprove array of investors to be approved */ function approveInvestorsInBulk(address[] toApprove) external onlyOwner { for (uint i = 0; i < toApprove.length; i++) { investorMap[toApprove[i]] = true; emit Approved(toApprove[i]); } } /** @dev disapprove an investor * @param toDisapprove investor to be disapproved */ function disapproveInvestor(address toDisapprove) external onlyOwner { delete investorMap[toDisapprove]; emit Disapproved(toDisapprove); } /** @dev disapprove investors in bulk * @param toDisapprove array of investors to be disapproved */ function disapproveInvestorsInBulk(address[] toDisapprove) external onlyOwner { for (uint i = 0; i < toDisapprove.length; i++) { delete investorMap[toDisapprove[i]]; emit Disapproved(toDisapprove[i]); } } } /** * @title Validator * @dev The Validator contract has a validator address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Validator { address public validator; /** * event for validator address update logging * @param previousOwner address of the old validator * @param newValidator address of the new validator */ event NewValidatorSet(address indexed previousOwner, address indexed newValidator); /** * @dev The Validator constructor sets the original `validator` of the contract to the sender * account. */ constructor() public { validator = msg.sender; } /** * @dev Throws if called by any account other than the validator. */ modifier onlyValidator() { require(msg.sender == validator); _; } /** * @dev Allows the current validator to transfer control of the contract to a newValidator. * @param newValidator The address to become next validator. */ function setNewValidator(address newValidator) public onlyValidator { require(newValidator != address(0)); emit NewValidatorSet(validator, newValidator); validator = newValidator; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @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); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } constructor(address _owner) public Ownable(_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) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract DetailedERC20 { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } /** @title Compliant Token */ contract CompliantToken is Validator, DetailedERC20, MintableToken { Whitelist public whiteListingContract; struct TransactionStruct { address from; address to; uint256 value; uint256 fee; address spender; } mapping (uint => TransactionStruct) public pendingTransactions; mapping (address => mapping (address => uint256)) public pendingApprovalAmount; uint256 public currentNonce = 0; uint256 public transferFee; address public feeRecipient; modifier checkIsInvestorApproved(address _account) { require(whiteListingContract.isInvestorApproved(_account)); _; } modifier checkIsAddressValid(address _account) { require(_account != address(0)); _; } modifier checkIsValueValid(uint256 _value) { require(_value > 0); _; } /** * event for rejected transfer logging * @param from address from which tokens have to be transferred * @param to address to tokens have to be transferred * @param value number of tokens * @param nonce request recorded at this particular nonce * @param reason reason for rejection */ event TransferRejected( address indexed from, address indexed to, uint256 value, uint256 indexed nonce, uint256 reason ); /** * event for transfer tokens logging * @param from address from which tokens have to be transferred * @param to address to tokens have to be transferred * @param value number of tokens * @param fee fee in tokens */ event TransferWithFee( address indexed from, address indexed to, uint256 value, uint256 fee ); /** * event for transfer/transferFrom request logging * @param from address from which tokens have to be transferred * @param to address to tokens have to be transferred * @param value number of tokens * @param fee fee in tokens * @param spender The address which will spend the tokens */ event RecordedPendingTransaction( address indexed from, address indexed to, uint256 value, uint256 fee, address indexed spender ); /** * event for whitelist contract update logging * @param _whiteListingContract address of the new whitelist contract */ event WhiteListingContractSet(address indexed _whiteListingContract); /** * event for fee update logging * @param previousFee previous fee * @param newFee new fee */ event FeeSet(uint256 indexed previousFee, uint256 indexed newFee); /** * event for fee recipient update logging * @param previousRecipient address of the old fee recipient * @param newRecipient address of the new fee recipient */ event FeeRecipientSet(address indexed previousRecipient, address indexed newRecipient); /** @dev Constructor * @param _owner Token contract owner * @param _name Token name * @param _symbol Token symbol * @param _decimals number of decimals in the token(usually 18) * @param whitelistAddress Ethereum address of the whitelist contract * @param recipient Ethereum address of the fee recipient * @param fee token fee for approving a transfer */ constructor( address _owner, string _name, string _symbol, uint8 _decimals, address whitelistAddress, address recipient, uint256 fee ) public MintableToken(_owner) DetailedERC20(_name, _symbol, _decimals) Validator() { setWhitelistContract(whitelistAddress); setFeeRecipient(recipient); setFee(fee); } /** @dev Updates whitelist contract address * @param whitelistAddress New whitelist contract address */ function setWhitelistContract(address whitelistAddress) public onlyValidator checkIsAddressValid(whitelistAddress) { whiteListingContract = Whitelist(whitelistAddress); emit WhiteListingContractSet(whiteListingContract); } /** @dev Updates token fee for approving a transfer * @param fee New token fee */ function setFee(uint256 fee) public onlyValidator { emit FeeSet(transferFee, fee); transferFee = fee; } /** @dev Updates fee recipient address * @param recipient New whitelist contract address */ function setFeeRecipient(address recipient) public onlyValidator checkIsAddressValid(recipient) { emit FeeRecipientSet(feeRecipient, recipient); feeRecipient = recipient; } /** @dev Updates token name * @param _name New token name */ function updateName(string _name) public onlyOwner { require(bytes(_name).length != 0); name = _name; } /** @dev Updates token symbol * @param _symbol New token name */ function updateSymbol(string _symbol) public onlyOwner { require(bytes(_symbol).length != 0); symbol = _symbol; } /** @dev transfer request * @param _to address to which the tokens have to be transferred * @param _value amount of tokens to be transferred */ function transfer(address _to, uint256 _value) public checkIsInvestorApproved(msg.sender) checkIsInvestorApproved(_to) checkIsValueValid(_value) returns (bool) { uint256 pendingAmount = pendingApprovalAmount[msg.sender][address(0)]; if (msg.sender == feeRecipient) { require(_value.add(pendingAmount) <= balances[msg.sender]); pendingApprovalAmount[msg.sender][address(0)] = pendingAmount.add(_value); } else { require(_value.add(pendingAmount).add(transferFee) <= balances[msg.sender]); pendingApprovalAmount[msg.sender][address(0)] = pendingAmount.add(_value).add(transferFee); } pendingTransactions[currentNonce] = TransactionStruct( msg.sender, _to, _value, transferFee, address(0) ); emit RecordedPendingTransaction(msg.sender, _to, _value, transferFee, address(0)); currentNonce++; return true; } /** @dev transferFrom request * @param _from address from which the tokens have to be transferred * @param _to address to which the tokens have to be transferred * @param _value amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public checkIsInvestorApproved(_from) checkIsInvestorApproved(_to) checkIsValueValid(_value) returns (bool) { uint256 allowedTransferAmount = allowed[_from][msg.sender]; uint256 pendingAmount = pendingApprovalAmount[_from][msg.sender]; if (_from == feeRecipient) { require(_value.add(pendingAmount) <= balances[_from]); require(_value.add(pendingAmount) <= allowedTransferAmount); pendingApprovalAmount[_from][msg.sender] = pendingAmount.add(_value); } else { require(_value.add(pendingAmount).add(transferFee) <= balances[_from]); require(_value.add(pendingAmount).add(transferFee) <= allowedTransferAmount); pendingApprovalAmount[_from][msg.sender] = pendingAmount.add(_value).add(transferFee); } pendingTransactions[currentNonce] = TransactionStruct( _from, _to, _value, transferFee, msg.sender ); emit RecordedPendingTransaction(_from, _to, _value, transferFee, msg.sender); currentNonce++; return true; } /** @dev approve transfer/transferFrom request * @param nonce request recorded at this particular nonce */ function approveTransfer(uint256 nonce) external onlyValidator checkIsInvestorApproved(pendingTransactions[nonce].from) checkIsInvestorApproved(pendingTransactions[nonce].to) checkIsValueValid(pendingTransactions[nonce].value) returns (bool) { address from = pendingTransactions[nonce].from; address spender = pendingTransactions[nonce].spender; address to = pendingTransactions[nonce].to; uint256 value = pendingTransactions[nonce].value; uint256 allowedTransferAmount = allowed[from][spender]; uint256 pendingAmount = pendingApprovalAmount[from][spender]; uint256 fee = pendingTransactions[nonce].fee; uint256 balanceFrom = balances[from]; uint256 balanceTo = balances[to]; delete pendingTransactions[nonce]; if (from == feeRecipient) { fee = 0; balanceFrom = balanceFrom.sub(value); balanceTo = balanceTo.add(value); if (spender != address(0)) { allowedTransferAmount = allowedTransferAmount.sub(value); } pendingAmount = pendingAmount.sub(value); } else { balanceFrom = balanceFrom.sub(value.add(fee)); balanceTo = balanceTo.add(value); balances[feeRecipient] = balances[feeRecipient].add(fee); if (spender != address(0)) { allowedTransferAmount = allowedTransferAmount.sub(value).sub(fee); } pendingAmount = pendingAmount.sub(value).sub(fee); } emit TransferWithFee( from, to, value, fee ); emit Transfer( from, to, value ); balances[from] = balanceFrom; balances[to] = balanceTo; allowed[from][spender] = allowedTransferAmount; pendingApprovalAmount[from][spender] = pendingAmount; return true; } /** @dev reject transfer/transferFrom request * @param nonce request recorded at this particular nonce * @param reason reason for rejection */ function rejectTransfer(uint256 nonce, uint256 reason) external onlyValidator checkIsAddressValid(pendingTransactions[nonce].from) { address from = pendingTransactions[nonce].from; address spender = pendingTransactions[nonce].spender; if (from == feeRecipient) { pendingApprovalAmount[from][spender] = pendingApprovalAmount[from][spender] .sub(pendingTransactions[nonce].value); } else { pendingApprovalAmount[from][spender] = pendingApprovalAmount[from][spender] .sub(pendingTransactions[nonce].value).sub(pendingTransactions[nonce].fee); } emit TransferRejected( from, pendingTransactions[nonce].to, pendingTransactions[nonce].value, nonce, reason ); delete pendingTransactions[nonce]; } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. The contract requires a MintableToken that will be * minted as contributions arrive, note that the crowdsale contract * must be owner of the token in order to be able to mint it. */ contract Crowdsale { using SafeMath for uint256; // The token being sold MintableToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); constructor(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, MintableToken _token) public { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; token = _token; } /** @dev fallback function redirects to buy tokens */ function () external payable { buyTokens(msg.sender); } /** @dev buy tokens * @param beneficiary the address to which the tokens have to be minted */ function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } /** @return true if crowdsale event has ended */ function hasEnded() public view returns (bool) { return now > endTime; } // Override this method to have a way to add business logic to your crowdsale when buying function getTokenAmount(uint256 weiAmount) internal view returns(uint256) { return weiAmount.mul(rate); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } } /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); constructor(address _owner) public Ownable(_owner) {} /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract&#39;s finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal {} } /** @title Compliant Crowdsale */ contract CompliantCrowdsale is Validator, FinalizableCrowdsale { Whitelist public whiteListingContract; struct MintStruct { address to; uint256 tokens; uint256 weiAmount; } mapping (uint => MintStruct) public pendingMints; uint256 public currentMintNonce; mapping (address => uint) public rejectedMintBalance; modifier checkIsInvestorApproved(address _account) { require(whiteListingContract.isInvestorApproved(_account)); _; } modifier checkIsAddressValid(address _account) { require(_account != address(0)); _; } /** * event for rejected mint logging * @param to address for which buy tokens got rejected * @param value number of tokens * @param amount number of ethers invested * @param nonce request recorded at this particular nonce * @param reason reason for rejection */ event MintRejected( address indexed to, uint256 value, uint256 amount, uint256 indexed nonce, uint256 reason ); /** * event for buy tokens request logging * @param beneficiary address for which buy tokens is requested * @param tokens number of tokens * @param weiAmount number of ethers invested * @param nonce request recorded at this particular nonce */ event ContributionRegistered( address beneficiary, uint256 tokens, uint256 weiAmount, uint256 nonce ); /** * event for whitelist contract update logging * @param _whiteListingContract address of the new whitelist contract */ event WhiteListingContractSet(address indexed _whiteListingContract); /** * event for claimed ether logging * @param account user claiming the ether * @param amount ether claimed */ event Claimed(address indexed account, uint256 amount); /** @dev Constructor * @param whitelistAddress Ethereum address of the whitelist contract * @param _startTime crowdsale start time * @param _endTime crowdsale end time * @param _rate number of tokens to be sold per ether * @param _wallet Ethereum address of the wallet * @param _token Ethereum address of the token contract * @param _owner Ethereum address of the owner */ constructor( address whitelistAddress, uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet, MintableToken _token, address _owner ) public FinalizableCrowdsale(_owner) Crowdsale(_startTime, _endTime, _rate, _wallet, _token) { setWhitelistContract(whitelistAddress); } /** @dev Updates whitelist contract address * @param whitelistAddress address of the new whitelist contract */ function setWhitelistContract(address whitelistAddress) public onlyValidator checkIsAddressValid(whitelistAddress) { whiteListingContract = Whitelist(whitelistAddress); emit WhiteListingContractSet(whiteListingContract); } /** @dev buy tokens request * @param beneficiary the address to which the tokens have to be minted */ function buyTokens(address beneficiary) public payable checkIsInvestorApproved(beneficiary) { require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.mul(rate); pendingMints[currentMintNonce] = MintStruct(beneficiary, tokens, weiAmount); emit ContributionRegistered(beneficiary, tokens, weiAmount, currentMintNonce); currentMintNonce++; } /** @dev approve buy tokens request * @param nonce request recorded at this particular nonce */ function approveMint(uint256 nonce) external onlyValidator checkIsInvestorApproved(pendingMints[nonce].to) returns (bool) { // update state weiRaised = weiRaised.add(pendingMints[nonce].weiAmount); //No need to use mint-approval on token side, since the minting is already approved in the crowdsale side token.mint(pendingMints[nonce].to, pendingMints[nonce].tokens); emit TokenPurchase( msg.sender, pendingMints[nonce].to, pendingMints[nonce].weiAmount, pendingMints[nonce].tokens ); forwardFunds(pendingMints[nonce].weiAmount); delete pendingMints[nonce]; return true; } /** @dev reject buy tokens request * @param nonce request recorded at this particular nonce * @param reason reason for rejection */ function rejectMint(uint256 nonce, uint256 reason) external onlyValidator checkIsAddressValid(pendingMints[nonce].to) { rejectedMintBalance[pendingMints[nonce].to] = rejectedMintBalance[pendingMints[nonce].to].add(pendingMints[nonce].weiAmount); emit MintRejected( pendingMints[nonce].to, pendingMints[nonce].tokens, pendingMints[nonce].weiAmount, nonce, reason ); delete pendingMints[nonce]; } /** @dev claim back ether if buy tokens request is rejected */ function claim() external { require(rejectedMintBalance[msg.sender] > 0); uint256 value = rejectedMintBalance[msg.sender]; rejectedMintBalance[msg.sender] = 0; msg.sender.transfer(value); emit Claimed(msg.sender, value); } function finalization() internal { token.finishMinting(); transferTokenOwnership(owner); super.finalization(); } /** @dev Updates token contract address * @param newToken New token contract address */ function setTokenContract(address newToken) external onlyOwner checkIsAddressValid(newToken) { token = CompliantToken(newToken); } /** @dev transfers ownership of the token contract * @param newOwner New owner of the token contract */ function transferTokenOwnership(address newOwner) public onlyOwner checkIsAddressValid(newOwner) { token.transferOwnership(newOwner); } function forwardFunds(uint256 amount) internal { wallet.transfer(amount); } }
* @title Compliant Token */
contract CompliantToken is Validator, DetailedERC20, MintableToken { Whitelist public whiteListingContract; struct TransactionStruct { address from; address to; uint256 value; uint256 fee; address spender; } mapping (uint => TransactionStruct) public pendingTransactions; mapping (address => mapping (address => uint256)) public pendingApprovalAmount; uint256 public currentNonce = 0; uint256 public transferFee; address public feeRecipient; modifier checkIsInvestorApproved(address _account) { require(whiteListingContract.isInvestorApproved(_account)); _; } modifier checkIsAddressValid(address _account) { require(_account != address(0)); _; } modifier checkIsValueValid(uint256 _value) { require(_value > 0); _; } address indexed from, address indexed to, uint256 value, uint256 indexed nonce, uint256 reason ); address indexed from, address indexed to, uint256 value, uint256 fee ); address indexed from, address indexed to, uint256 value, uint256 fee, address indexed spender ); address _owner, string _name, string _symbol, uint8 _decimals, address whitelistAddress, address recipient, uint256 fee ) public MintableToken(_owner) DetailedERC20(_name, _symbol, _decimals) Validator() event TransferRejected( event TransferWithFee( event RecordedPendingTransaction( event WhiteListingContractSet(address indexed _whiteListingContract); event FeeSet(uint256 indexed previousFee, uint256 indexed newFee); event FeeRecipientSet(address indexed previousRecipient, address indexed newRecipient); constructor( { setWhitelistContract(whitelistAddress); setFeeRecipient(recipient); setFee(fee); } function setWhitelistContract(address whitelistAddress) public onlyValidator checkIsAddressValid(whitelistAddress) { whiteListingContract = Whitelist(whitelistAddress); emit WhiteListingContractSet(whiteListingContract); } function setFee(uint256 fee) public onlyValidator { emit FeeSet(transferFee, fee); transferFee = fee; } function setFeeRecipient(address recipient) public onlyValidator checkIsAddressValid(recipient) { emit FeeRecipientSet(feeRecipient, recipient); feeRecipient = recipient; } function updateName(string _name) public onlyOwner { require(bytes(_name).length != 0); name = _name; } function updateSymbol(string _symbol) public onlyOwner { require(bytes(_symbol).length != 0); symbol = _symbol; } function transfer(address _to, uint256 _value) public checkIsInvestorApproved(msg.sender) checkIsInvestorApproved(_to) checkIsValueValid(_value) returns (bool) { uint256 pendingAmount = pendingApprovalAmount[msg.sender][address(0)]; if (msg.sender == feeRecipient) { require(_value.add(pendingAmount) <= balances[msg.sender]); pendingApprovalAmount[msg.sender][address(0)] = pendingAmount.add(_value); require(_value.add(pendingAmount).add(transferFee) <= balances[msg.sender]); pendingApprovalAmount[msg.sender][address(0)] = pendingAmount.add(_value).add(transferFee); } pendingTransactions[currentNonce] = TransactionStruct( msg.sender, _to, _value, transferFee, address(0) ); emit RecordedPendingTransaction(msg.sender, _to, _value, transferFee, address(0)); currentNonce++; return true; } function transfer(address _to, uint256 _value) public checkIsInvestorApproved(msg.sender) checkIsInvestorApproved(_to) checkIsValueValid(_value) returns (bool) { uint256 pendingAmount = pendingApprovalAmount[msg.sender][address(0)]; if (msg.sender == feeRecipient) { require(_value.add(pendingAmount) <= balances[msg.sender]); pendingApprovalAmount[msg.sender][address(0)] = pendingAmount.add(_value); require(_value.add(pendingAmount).add(transferFee) <= balances[msg.sender]); pendingApprovalAmount[msg.sender][address(0)] = pendingAmount.add(_value).add(transferFee); } pendingTransactions[currentNonce] = TransactionStruct( msg.sender, _to, _value, transferFee, address(0) ); emit RecordedPendingTransaction(msg.sender, _to, _value, transferFee, address(0)); currentNonce++; return true; } } else { function transferFrom(address _from, address _to, uint256 _value) public checkIsInvestorApproved(_from) checkIsInvestorApproved(_to) checkIsValueValid(_value) returns (bool) { uint256 allowedTransferAmount = allowed[_from][msg.sender]; uint256 pendingAmount = pendingApprovalAmount[_from][msg.sender]; if (_from == feeRecipient) { require(_value.add(pendingAmount) <= balances[_from]); require(_value.add(pendingAmount) <= allowedTransferAmount); pendingApprovalAmount[_from][msg.sender] = pendingAmount.add(_value); require(_value.add(pendingAmount).add(transferFee) <= balances[_from]); require(_value.add(pendingAmount).add(transferFee) <= allowedTransferAmount); pendingApprovalAmount[_from][msg.sender] = pendingAmount.add(_value).add(transferFee); } pendingTransactions[currentNonce] = TransactionStruct( _from, _to, _value, transferFee, msg.sender ); emit RecordedPendingTransaction(_from, _to, _value, transferFee, msg.sender); currentNonce++; return true; } function transferFrom(address _from, address _to, uint256 _value) public checkIsInvestorApproved(_from) checkIsInvestorApproved(_to) checkIsValueValid(_value) returns (bool) { uint256 allowedTransferAmount = allowed[_from][msg.sender]; uint256 pendingAmount = pendingApprovalAmount[_from][msg.sender]; if (_from == feeRecipient) { require(_value.add(pendingAmount) <= balances[_from]); require(_value.add(pendingAmount) <= allowedTransferAmount); pendingApprovalAmount[_from][msg.sender] = pendingAmount.add(_value); require(_value.add(pendingAmount).add(transferFee) <= balances[_from]); require(_value.add(pendingAmount).add(transferFee) <= allowedTransferAmount); pendingApprovalAmount[_from][msg.sender] = pendingAmount.add(_value).add(transferFee); } pendingTransactions[currentNonce] = TransactionStruct( _from, _to, _value, transferFee, msg.sender ); emit RecordedPendingTransaction(_from, _to, _value, transferFee, msg.sender); currentNonce++; return true; } } else { function approveTransfer(uint256 nonce) external onlyValidator checkIsInvestorApproved(pendingTransactions[nonce].from) checkIsInvestorApproved(pendingTransactions[nonce].to) checkIsValueValid(pendingTransactions[nonce].value) returns (bool) { address from = pendingTransactions[nonce].from; address spender = pendingTransactions[nonce].spender; address to = pendingTransactions[nonce].to; uint256 value = pendingTransactions[nonce].value; uint256 allowedTransferAmount = allowed[from][spender]; uint256 pendingAmount = pendingApprovalAmount[from][spender]; uint256 fee = pendingTransactions[nonce].fee; uint256 balanceFrom = balances[from]; uint256 balanceTo = balances[to]; delete pendingTransactions[nonce]; if (from == feeRecipient) { fee = 0; balanceFrom = balanceFrom.sub(value); balanceTo = balanceTo.add(value); if (spender != address(0)) { allowedTransferAmount = allowedTransferAmount.sub(value); } pendingAmount = pendingAmount.sub(value); balanceFrom = balanceFrom.sub(value.add(fee)); balanceTo = balanceTo.add(value); balances[feeRecipient] = balances[feeRecipient].add(fee); if (spender != address(0)) { allowedTransferAmount = allowedTransferAmount.sub(value).sub(fee); } pendingAmount = pendingAmount.sub(value).sub(fee); } emit TransferWithFee( from, to, value, fee ); emit Transfer( from, to, value ); balances[from] = balanceFrom; balances[to] = balanceTo; allowed[from][spender] = allowedTransferAmount; pendingApprovalAmount[from][spender] = pendingAmount; return true; } function approveTransfer(uint256 nonce) external onlyValidator checkIsInvestorApproved(pendingTransactions[nonce].from) checkIsInvestorApproved(pendingTransactions[nonce].to) checkIsValueValid(pendingTransactions[nonce].value) returns (bool) { address from = pendingTransactions[nonce].from; address spender = pendingTransactions[nonce].spender; address to = pendingTransactions[nonce].to; uint256 value = pendingTransactions[nonce].value; uint256 allowedTransferAmount = allowed[from][spender]; uint256 pendingAmount = pendingApprovalAmount[from][spender]; uint256 fee = pendingTransactions[nonce].fee; uint256 balanceFrom = balances[from]; uint256 balanceTo = balances[to]; delete pendingTransactions[nonce]; if (from == feeRecipient) { fee = 0; balanceFrom = balanceFrom.sub(value); balanceTo = balanceTo.add(value); if (spender != address(0)) { allowedTransferAmount = allowedTransferAmount.sub(value); } pendingAmount = pendingAmount.sub(value); balanceFrom = balanceFrom.sub(value.add(fee)); balanceTo = balanceTo.add(value); balances[feeRecipient] = balances[feeRecipient].add(fee); if (spender != address(0)) { allowedTransferAmount = allowedTransferAmount.sub(value).sub(fee); } pendingAmount = pendingAmount.sub(value).sub(fee); } emit TransferWithFee( from, to, value, fee ); emit Transfer( from, to, value ); balances[from] = balanceFrom; balances[to] = balanceTo; allowed[from][spender] = allowedTransferAmount; pendingApprovalAmount[from][spender] = pendingAmount; return true; } function approveTransfer(uint256 nonce) external onlyValidator checkIsInvestorApproved(pendingTransactions[nonce].from) checkIsInvestorApproved(pendingTransactions[nonce].to) checkIsValueValid(pendingTransactions[nonce].value) returns (bool) { address from = pendingTransactions[nonce].from; address spender = pendingTransactions[nonce].spender; address to = pendingTransactions[nonce].to; uint256 value = pendingTransactions[nonce].value; uint256 allowedTransferAmount = allowed[from][spender]; uint256 pendingAmount = pendingApprovalAmount[from][spender]; uint256 fee = pendingTransactions[nonce].fee; uint256 balanceFrom = balances[from]; uint256 balanceTo = balances[to]; delete pendingTransactions[nonce]; if (from == feeRecipient) { fee = 0; balanceFrom = balanceFrom.sub(value); balanceTo = balanceTo.add(value); if (spender != address(0)) { allowedTransferAmount = allowedTransferAmount.sub(value); } pendingAmount = pendingAmount.sub(value); balanceFrom = balanceFrom.sub(value.add(fee)); balanceTo = balanceTo.add(value); balances[feeRecipient] = balances[feeRecipient].add(fee); if (spender != address(0)) { allowedTransferAmount = allowedTransferAmount.sub(value).sub(fee); } pendingAmount = pendingAmount.sub(value).sub(fee); } emit TransferWithFee( from, to, value, fee ); emit Transfer( from, to, value ); balances[from] = balanceFrom; balances[to] = balanceTo; allowed[from][spender] = allowedTransferAmount; pendingApprovalAmount[from][spender] = pendingAmount; return true; } } else { function approveTransfer(uint256 nonce) external onlyValidator checkIsInvestorApproved(pendingTransactions[nonce].from) checkIsInvestorApproved(pendingTransactions[nonce].to) checkIsValueValid(pendingTransactions[nonce].value) returns (bool) { address from = pendingTransactions[nonce].from; address spender = pendingTransactions[nonce].spender; address to = pendingTransactions[nonce].to; uint256 value = pendingTransactions[nonce].value; uint256 allowedTransferAmount = allowed[from][spender]; uint256 pendingAmount = pendingApprovalAmount[from][spender]; uint256 fee = pendingTransactions[nonce].fee; uint256 balanceFrom = balances[from]; uint256 balanceTo = balances[to]; delete pendingTransactions[nonce]; if (from == feeRecipient) { fee = 0; balanceFrom = balanceFrom.sub(value); balanceTo = balanceTo.add(value); if (spender != address(0)) { allowedTransferAmount = allowedTransferAmount.sub(value); } pendingAmount = pendingAmount.sub(value); balanceFrom = balanceFrom.sub(value.add(fee)); balanceTo = balanceTo.add(value); balances[feeRecipient] = balances[feeRecipient].add(fee); if (spender != address(0)) { allowedTransferAmount = allowedTransferAmount.sub(value).sub(fee); } pendingAmount = pendingAmount.sub(value).sub(fee); } emit TransferWithFee( from, to, value, fee ); emit Transfer( from, to, value ); balances[from] = balanceFrom; balances[to] = balanceTo; allowed[from][spender] = allowedTransferAmount; pendingApprovalAmount[from][spender] = pendingAmount; return true; } function rejectTransfer(uint256 nonce, uint256 reason) external onlyValidator checkIsAddressValid(pendingTransactions[nonce].from) { address from = pendingTransactions[nonce].from; address spender = pendingTransactions[nonce].spender; if (from == feeRecipient) { pendingApprovalAmount[from][spender] = pendingApprovalAmount[from][spender] .sub(pendingTransactions[nonce].value); pendingApprovalAmount[from][spender] = pendingApprovalAmount[from][spender] .sub(pendingTransactions[nonce].value).sub(pendingTransactions[nonce].fee); } emit TransferRejected( from, pendingTransactions[nonce].to, pendingTransactions[nonce].value, nonce, reason ); delete pendingTransactions[nonce]; } function rejectTransfer(uint256 nonce, uint256 reason) external onlyValidator checkIsAddressValid(pendingTransactions[nonce].from) { address from = pendingTransactions[nonce].from; address spender = pendingTransactions[nonce].spender; if (from == feeRecipient) { pendingApprovalAmount[from][spender] = pendingApprovalAmount[from][spender] .sub(pendingTransactions[nonce].value); pendingApprovalAmount[from][spender] = pendingApprovalAmount[from][spender] .sub(pendingTransactions[nonce].value).sub(pendingTransactions[nonce].fee); } emit TransferRejected( from, pendingTransactions[nonce].to, pendingTransactions[nonce].value, nonce, reason ); delete pendingTransactions[nonce]; } } else { }
2,449,226
[ 1, 799, 18515, 3155, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1286, 18515, 1345, 353, 9150, 16, 463, 6372, 654, 39, 3462, 16, 490, 474, 429, 1345, 288, 203, 565, 3497, 7523, 1071, 9578, 19081, 8924, 31, 203, 203, 565, 1958, 5947, 3823, 288, 203, 3639, 1758, 628, 31, 203, 3639, 1758, 358, 31, 203, 3639, 2254, 5034, 460, 31, 203, 3639, 2254, 5034, 14036, 31, 203, 3639, 1758, 17571, 264, 31, 203, 565, 289, 203, 203, 565, 2874, 261, 11890, 516, 5947, 3823, 13, 1071, 4634, 14186, 31, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 1071, 4634, 23461, 6275, 31, 203, 565, 2254, 5034, 1071, 783, 13611, 273, 374, 31, 203, 565, 2254, 5034, 1071, 7412, 14667, 31, 203, 565, 1758, 1071, 14036, 18241, 31, 203, 203, 565, 9606, 866, 2520, 3605, 395, 280, 31639, 12, 2867, 389, 4631, 13, 288, 203, 3639, 2583, 12, 14739, 19081, 8924, 18, 291, 3605, 395, 280, 31639, 24899, 4631, 10019, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 866, 2520, 1887, 1556, 12, 2867, 389, 4631, 13, 288, 203, 3639, 2583, 24899, 4631, 480, 1758, 12, 20, 10019, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 866, 2520, 620, 1556, 12, 11890, 5034, 389, 1132, 13, 288, 203, 3639, 2583, 24899, 1132, 405, 374, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 3639, 1758, 8808, 628, 16, 203, 3639, 1758, 8808, 358, 16, 203, 3639, 2254, 5034, 460, 16, 203, 3639, 2254, 5034, 8808, 7448, 16, 203, 3639, 2254, 5034, 3971, 203, 2 ]
./partial_match/1/0xCF9A1A3A30d859aB8964E6dB596A8D2Edd449C0b/sources/TimeLockedController.sol
admin initiates a request that the insurance fee be changed
function requestChangeInsuranceFees(uint80 _transferFeeNumerator, uint80 _transferFeeDenominator, uint80 _mintFeeNumerator, uint80 _mintFeeDenominator, uint256 _mintFeeFlat, uint80 _burnFeeNumerator, uint80 _burnFeeDenominator, uint256 _burnFeeFlat) public onlyAdminOrOwner { uint deferBlock = computeDeferBlock(); changeInsuranceFeesOperation = ChangeInsuranceFeesOperation(_transferFeeNumerator, _transferFeeDenominator, _mintFeeNumerator, _mintFeeDenominator, _mintFeeFlat, _burnFeeNumerator, _burnFeeDenominator, _burnFeeFlat, admin, deferBlock); ChangeInsuranceFeesOperationEvent(_transferFeeNumerator, _transferFeeDenominator, _mintFeeNumerator, _mintFeeDenominator, _mintFeeFlat, _burnFeeNumerator, _burnFeeDenominator, _burnFeeFlat, deferBlock); }
15,462,942
[ 1, 3666, 1208, 16020, 279, 590, 716, 326, 2763, 295, 1359, 14036, 506, 3550, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 590, 3043, 5048, 295, 1359, 2954, 281, 12, 11890, 3672, 389, 13866, 14667, 2578, 7385, 16, 203, 4766, 3639, 2254, 3672, 389, 13866, 14667, 8517, 26721, 16, 203, 4766, 3639, 2254, 3672, 389, 81, 474, 14667, 2578, 7385, 16, 203, 4766, 3639, 2254, 3672, 389, 81, 474, 14667, 8517, 26721, 16, 203, 4766, 3639, 2254, 5034, 389, 81, 474, 14667, 16384, 16, 203, 4766, 3639, 2254, 3672, 389, 70, 321, 14667, 2578, 7385, 16, 203, 4766, 3639, 2254, 3672, 389, 70, 321, 14667, 8517, 26721, 16, 203, 4766, 3639, 2254, 5034, 389, 70, 321, 14667, 16384, 13, 1071, 1338, 4446, 1162, 5541, 288, 203, 3639, 2254, 2220, 1768, 273, 3671, 758, 586, 1768, 5621, 203, 3639, 2549, 5048, 295, 1359, 2954, 281, 2988, 273, 7576, 5048, 295, 1359, 2954, 281, 2988, 24899, 13866, 14667, 2578, 7385, 16, 203, 28524, 565, 389, 13866, 14667, 8517, 26721, 16, 203, 28524, 565, 389, 81, 474, 14667, 2578, 7385, 16, 203, 28524, 565, 389, 81, 474, 14667, 8517, 26721, 16, 203, 28524, 565, 389, 81, 474, 14667, 16384, 16, 203, 28524, 565, 389, 70, 321, 14667, 2578, 7385, 16, 203, 28524, 565, 389, 70, 321, 14667, 8517, 26721, 16, 203, 28524, 565, 389, 70, 321, 14667, 16384, 16, 203, 28524, 565, 3981, 16, 203, 28524, 565, 2220, 1768, 1769, 203, 3639, 7576, 5048, 295, 1359, 2954, 281, 2988, 1133, 24899, 13866, 14667, 2578, 7385, 16, 203, 4766, 1850, 389, 13866, 14667, 8517, 26721, 16, 203, 4766, 1850, 389, 81, 474, 14667, 2578, 7385, 16, 203, 4766, 2 ]
//SPDX-License-Identifier: MIT pragma solidity 0.6.9; pragma experimental ABIEncoderV2; import "./LimitOrderBook.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Initializable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import { Decimal } from "./utils/Decimal.sol"; import { SignedDecimal } from "./utils/SignedDecimal.sol"; import { DecimalERC20 } from "./utils/DecimalERC20.sol"; import { IAmm } from "./interface/IAmm.sol"; import { IClearingHouse } from "./interface/IClearingHouse.sol"; import { ISmartWallet } from "./interface/ISmartWallet.sol"; contract SmartWallet is DecimalERC20, Initializable, ISmartWallet, Pausable { // Store addresses of smart contracts that we will be interacting with LimitOrderBook public OrderBook; SmartWalletFactory public factory; /* The ClearingHouse deployed with the main PERP contracts */ address constant CLEARINGHOUSE = 0x124650FfF6cd6d3242Ef0296C2F2dAB8F8109878; // TODO Set this with a setter address private owner; using Decimal for Decimal.decimal; using SignedDecimal for SignedDecimal.signedDecimal; using Address for address; using SafeERC20 for IERC20; /* * @notice allows the owner of the smart wallet to execute any transaction * on an external smart contract. The external smart contract must be whitelisted * otherwise this function will revert * This utilises functions from OpenZeppelin's Address.sol * @param target the address of the smart contract to interact with (will revert * if this is not a valid smart contract) * @param callData the data bytes of the function and parameters to execute * Can use encodeFunctionData() from ethers.js * @param value the ether value to attach to the function call (can be 0) */ function executeCall( address target, bytes calldata callData, uint256 value ) external payable override onlyOwner() returns (bytes memory) { require(target.isContract(), 'call to non-contract'); require(factory.isWhitelisted(target), 'Invalid target contract'); return target.functionCallWithValue(callData, value); } function initialize(address _lob, address _trader) initializer external override{ OrderBook = LimitOrderBook(_lob); factory = SmartWalletFactory(msg.sender); owner = _trader; } function executeMarketOrder( IAmm _asset, SignedDecimal.signedDecimal memory _orderSize, Decimal.decimal memory _collateral, Decimal.decimal memory _leverage, Decimal.decimal memory _slippage ) external override onlyOwner() whenNotPaused() { _handleOpenPositionWithApproval(_asset, _orderSize, _collateral, _leverage, _slippage); } function executeClosePosition( IAmm _asset, Decimal.decimal memory _slippage ) external override onlyOwner() whenNotPaused() { _handleClosePositionWithApproval(_asset, _slippage); } function pauseWallet() external onlyOwner() { _pause(); } function unpauseWallet() external onlyOwner() { _unpause(); } /* * @notice Will execute an order from the limit order book. Note that the only * way to call this function is via the LimitOrderBook where you call execute(). * @param order_id is the ID of the order to execute */ function executeOrder( uint order_id ) external override whenNotPaused() { //Only the LimitOrderBook can call this function require(msg.sender == address(OrderBook), 'Only execute from the order book'); //Get some of the parameters (,address _trader, LimitOrderBook.OrderType _orderType, ,bool _stillValid, uint _expiry) = OrderBook.getLimitOrderParams(order_id); //Make sure that the order belongs to this smart wallet require(factory.getSmartWallet(_trader) == address(this), 'Incorrect smart wallet'); //Make sure that the order hasn't expired require(((_expiry == 0 ) || (block.timestamp<_expiry)), 'Order expired'); //Make sure the order is still valid require(_stillValid, 'Order no longer valid'); //Perform function depending on the type of order if(_orderType == LimitOrderBook.OrderType.LIMIT) { _executeLimitOrder(order_id); } else if(_orderType == LimitOrderBook.OrderType.STOPMARKET) { _executeStopOrder(order_id); } else if(_orderType == LimitOrderBook.OrderType.STOPLIMIT) { _executeStopLimitOrder(order_id); } else if (_orderType == LimitOrderBook.OrderType.TRAILINGSTOPMARKET) { _executeStopOrder(order_id); } else if (_orderType == LimitOrderBook.OrderType.TRAILINGSTOPLIMIT) { _executeStopLimitOrder(order_id); } } function minD(Decimal.decimal memory a, Decimal.decimal memory b) internal pure returns (Decimal.decimal memory){ return (a.cmp(b) >= 1) ? b : a; } function _handleOpenPositionWithApproval( IAmm _asset, SignedDecimal.signedDecimal memory _orderSize, Decimal.decimal memory _collateral, Decimal.decimal memory _leverage, Decimal.decimal memory _slippage ) internal { //Get cost of placing order (fees) (Decimal.decimal memory toll, Decimal.decimal memory spread) = _asset .calcFee(_collateral.mulD(_leverage)); Decimal.decimal memory totalCost = _collateral.addD(toll).addD(spread); IERC20 quoteAsset = _asset.quoteAsset(); _approve(quoteAsset, CLEARINGHOUSE, totalCost); //Establish how much leverage will be needed for that order based on the //amount of collateral and the maximum leverage the user was happy with. bool _isLong = _orderSize.isNegative() ? false : true; Decimal.decimal memory _size = _orderSize.abs(); Decimal.decimal memory _quote = (IAmm(_asset) .getOutputPrice(_isLong ? IAmm.Dir.REMOVE_FROM_AMM : IAmm.Dir.ADD_TO_AMM, _size)); Decimal.decimal memory _offset = Decimal.decimal(1); //Need to add one wei for rounding _leverage = minD(_quote.divD(_collateral).addD(_offset),_leverage); IClearingHouse(CLEARINGHOUSE).openPosition( _asset, _isLong ? IClearingHouse.Side.BUY : IClearingHouse.Side.SELL, _collateral, _leverage, _slippage ); } function _calcBaseAssetAmountLimit( Decimal.decimal memory _positionSize, bool _isLong, Decimal.decimal memory _slippage ) internal pure returns (Decimal.decimal memory){ Decimal.decimal memory factor; require(_slippage.cmp(Decimal.one()) == -1, 'Slippage must be %'); if (_isLong) { //base amount must be greater than base amount limit factor = Decimal.one().subD(_slippage); } else { //base amount must be less than base amount limit factor = Decimal.one().addD(_slippage); } return factor.mulD(_positionSize); } /* OPEN LONG BASE ASSET LIMIT = POSITION SIZE - SLIPPAGE OPEN SHORT BASE ASSET LIMIT = POSITION SIZE + SLIPPAGE CLOSE LONG QUOTE ASSET LIMIT = VALUE - SLIPPAGE CLOSE SHORT QUOTE ASSET LIMIT = VALUE + SLIPPAGE */ function _calcQuoteAssetAmountLimit( IAmm _asset, Decimal.decimal memory _targetPrice, bool _isLong, Decimal.decimal memory _slippage ) internal view returns (Decimal.decimal memory){ IClearingHouse.Position memory oldPosition = IClearingHouse(CLEARINGHOUSE) .getPosition(_asset, address(this)); SignedDecimal.signedDecimal memory oldPositionSize = oldPosition.size; Decimal.decimal memory value = oldPositionSize.abs().mulD(_targetPrice); Decimal.decimal memory factor; require(_slippage.cmp(Decimal.one()) == -1, 'Slippage must be %'); if (_isLong) { //quote amount must be less than quote amount limit factor = Decimal.one().subD(_slippage); } else { //quote amount must be greater than quote amount limit factor = Decimal.one().addD(_slippage); } return factor.mulD(value); } function _handleClosePositionWithApproval( IAmm _asset, Decimal.decimal memory _slippage ) internal { //Need to calculate trading fees to close position (no margin required) IClearingHouse.Position memory oldPosition = IClearingHouse(CLEARINGHOUSE) .getPosition(_asset, address(this)); SignedDecimal.signedDecimal memory oldPositionSize = oldPosition.size; Decimal.decimal memory _quoteAsset = _asset.getOutputPrice( oldPositionSize.toInt() > 0 ? IAmm.Dir.ADD_TO_AMM : IAmm.Dir.REMOVE_FROM_AMM, oldPositionSize.abs() ); (Decimal.decimal memory toll, Decimal.decimal memory spread) = _asset .calcFee(_quoteAsset); Decimal.decimal memory totalCost = toll.addD(spread); IERC20 quoteAsset = _asset.quoteAsset(); _approve(quoteAsset, CLEARINGHOUSE, totalCost); IClearingHouse(CLEARINGHOUSE).closePosition( _asset, _slippage ); } /* * @notice check what this order should do if it is reduceOnly * To clarify, only reduceOnly orders should call this function: * If it returns true, then the order should close the position rather than * opening one. * @param _asset the AMM for the asset * @param _orderSize the size of the order (note: negative are SELL/SHORt) */ function _shouldCloseReduceOnly( IAmm _asset, SignedDecimal.signedDecimal memory _orderSize ) internal view returns (bool) { //Get the size of the users current position IClearingHouse.Position memory _currentPosition = IClearingHouse(CLEARINGHOUSE) .getPosition(IAmm(_asset), address(this)); SignedDecimal.signedDecimal memory _currentSize = _currentPosition.size; //If the user has no position for this asset, then cannot execute a reduceOnly order require(_currentSize.abs().toUint() != 0, "#reduceOnly: current size is 0"); //If the direction of the order is opposite to the users current position if(_orderSize.isNegative() != _currentSize.isNegative()) { //User is long and wants to sell: if(_orderSize.isNegative()) { //The size of the order is large enough to open a reverse position, //therefore we should close it instead if(_orderSize.abs().cmp(_currentSize.abs()) == 1) { return true; } } else { //User is short and wants to buy: if(_currentSize.abs().cmp(_orderSize.abs()) == 1) { //The size of the order is large enough to open a reverse position, //therefore we should close it instead return true; } } } else { //User is trying to increase the size of their position revert('#reduceOnly: cannot increase size of position'); } } /* * @notice internal position to execute limit order - note that you need to * check that this is a limit order before calling this function */ function _executeLimitOrder( uint order_id ) internal { //Get information of limit order (,Decimal.decimal memory _limitPrice, SignedDecimal.signedDecimal memory _orderSize, Decimal.decimal memory _collateral, Decimal.decimal memory _leverage, Decimal.decimal memory _slippage,, address _asset, bool _reduceOnly) = OrderBook.getLimitOrderPrices(order_id); //Check whether we need to close position or open position bool closePosition = false; if(_reduceOnly) { closePosition = _shouldCloseReduceOnly(IAmm(_asset), _orderSize); } //Establish whether long or short bool isLong = _orderSize.isNegative() ? false : true; //Get the current spot price of the asset Decimal.decimal memory _markPrice = IAmm(_asset).getSpotPrice(); require(_markPrice.cmp(Decimal.zero()) >= 1, 'Error getting mark price'); //Check whether price conditions have been met: // LIMIT BUY: mark price < limit price // LIMIT SELL: mark price > limit price require((_limitPrice.cmp(_markPrice)) == (isLong ? int128(1) : -1), 'Invalid limit order condition'); if(closePosition) { Decimal.decimal memory quoteAssetLimit = _calcQuoteAssetAmountLimit(IAmm(_asset), _limitPrice, isLong, _slippage); _handleClosePositionWithApproval(IAmm(_asset), quoteAssetLimit); } else { //openPosition using the values calculated above Decimal.decimal memory baseAssetLimit = _calcBaseAssetAmountLimit(_orderSize.abs(), isLong, _slippage); _handleOpenPositionWithApproval(IAmm(_asset), _orderSize, _collateral, _leverage, baseAssetLimit); } } function _executeStopOrder( uint order_id ) internal { //Get information of stop order (Decimal.decimal memory _stopPrice,, SignedDecimal.signedDecimal memory _orderSize, Decimal.decimal memory _collateral, Decimal.decimal memory _leverage,,, address _asset, bool _reduceOnly) = OrderBook.getLimitOrderPrices(order_id); //Check whether we need to close position or open position bool closePosition = false; if(_reduceOnly) { closePosition = _shouldCloseReduceOnly(IAmm(_asset), _orderSize); } //Establish whether long or short bool isLong = _orderSize.isNegative() ? false : true; //Get the current spot price of the asset Decimal.decimal memory _markPrice = IAmm(_asset).getSpotPrice(); require(_markPrice.cmp(Decimal.zero()) >= 1, 'Error getting mark price'); //Check whether price conditions have been met: // STOP BUY: mark price > stop price // STOP SELL: mark price < stop price require((_markPrice.cmp(_stopPrice)) == (isLong ? int128(1) : -1), 'Invalid stop order conditions'); //Strictly speaking, stop orders cannot have slippage as by definition they //will get executed at the next available price. Restricting them with slippage //will turn them into stop limit orders. if(closePosition) { _handleClosePositionWithApproval(IAmm(_asset), Decimal.decimal(0)); } else { _handleOpenPositionWithApproval(IAmm(_asset), _orderSize, _collateral, _leverage, Decimal.decimal(0)); } } function _executeStopLimitOrder( uint order_id ) internal { //Get information of stop limit order (Decimal.decimal memory _stopPrice, Decimal.decimal memory _limitPrice, SignedDecimal.signedDecimal memory _orderSize, Decimal.decimal memory _collateral, Decimal.decimal memory _leverage, Decimal.decimal memory _slippage,, address _asset, bool _reduceOnly) = OrderBook.getLimitOrderPrices(order_id); //Check whether we need to close position or open position bool closePosition = false; if(_reduceOnly) { closePosition = _shouldCloseReduceOnly(IAmm(_asset), _orderSize); } //Establish whether long or short bool isLong = _orderSize.isNegative() ? false : true; //Get the current spot price of the asset Decimal.decimal memory _markPrice = IAmm(_asset).getSpotPrice(); require(_markPrice.cmp(Decimal.zero()) >= 1, 'Error getting mark price'); //Check whether price conditions have been met: // STOP LIMIT BUY: limit price > mark price > stop price // STOP LIMIT SELL: limit price < mark price < stop price require((_limitPrice.cmp(_markPrice)) == (isLong ? int128(1) : -1) && (_markPrice.cmp(_stopPrice)) == (isLong ? int128(1) : -1), 'Invalid stop-limit condition'); if(closePosition) { Decimal.decimal memory quoteAssetLimit = _calcQuoteAssetAmountLimit(IAmm(_asset), _limitPrice, isLong, _slippage); _handleClosePositionWithApproval(IAmm(_asset), quoteAssetLimit); } else { //openPosition using the values calculated above Decimal.decimal memory baseAssetLimit = _calcBaseAssetAmountLimit(_orderSize.abs(), isLong, _slippage); _handleOpenPositionWithApproval(IAmm(_asset), _orderSize, _collateral, _leverage, baseAssetLimit); } } modifier onlyOwner() { require(owner == msg.sender, "Ownable: caller is not the owner"); _; } } contract SmartWalletFactory is ISmartWalletFactory, Ownable{ event Created(address indexed owner, address indexed smartWallet); event AddedToWhitelist(address contractAddress); event DeletedFromWhitelist(address contractAddress); mapping (address => address) public override getSmartWallet; mapping (address => bool) public isWhitelisted; address public LimitOrderBook; constructor(address _addr) public { LimitOrderBook = _addr; } /* * @notice Create and deploy a smart wallet for the user and stores the address */ function spawn() external returns (address smartWallet) { require(getSmartWallet[msg.sender] == address(0), 'Already has smart wallet'); bytes memory bytecode = type(SmartWallet).creationCode; bytes32 salt = keccak256(abi.encodePacked(msg.sender)); assembly { smartWallet := create2(0, add(bytecode, 0x20), mload(bytecode), salt) } emit Created(msg.sender, smartWallet); ISmartWallet(smartWallet).initialize(LimitOrderBook, msg.sender); getSmartWallet[msg.sender] = smartWallet; } function addToWhitelist(address _contract) external onlyOwner{ require(!isWhitelisted[_contract], "already whitelisted"); isWhitelisted[_contract] = true; emit AddedToWhitelist(_contract); } function removeFromWhitelist(address _contract) external onlyOwner{ require(isWhitelisted[_contract], "not on whitelisted"); delete isWhitelisted[_contract]; emit DeletedFromWhitelist(_contract); } }
Get cost of placing order (fees)Establish how much leverage will be needed for that order based on theamount of collateral and the maximum leverage the user was happy with.
function _handleOpenPositionWithApproval( IAmm _asset, SignedDecimal.signedDecimal memory _orderSize, Decimal.decimal memory _collateral, Decimal.decimal memory _leverage, Decimal.decimal memory _slippage ) internal { (Decimal.decimal memory toll, Decimal.decimal memory spread) = _asset .calcFee(_collateral.mulD(_leverage)); Decimal.decimal memory totalCost = _collateral.addD(toll).addD(spread); IERC20 quoteAsset = _asset.quoteAsset(); _approve(quoteAsset, CLEARINGHOUSE, totalCost); bool _isLong = _orderSize.isNegative() ? false : true; Decimal.decimal memory _size = _orderSize.abs(); Decimal.decimal memory _quote = (IAmm(_asset) .getOutputPrice(_isLong ? IAmm.Dir.REMOVE_FROM_AMM : IAmm.Dir.ADD_TO_AMM, _size)); _leverage = minD(_quote.divD(_collateral).addD(_offset),_leverage); IClearingHouse(CLEARINGHOUSE).openPosition( _asset, _isLong ? IClearingHouse.Side.BUY : IClearingHouse.Side.SELL, _collateral, _leverage, _slippage ); }
12,909,905
[ 1, 967, 6991, 434, 886, 5330, 1353, 261, 3030, 281, 13, 9122, 23385, 3661, 9816, 884, 5682, 903, 506, 3577, 364, 716, 1353, 2511, 603, 326, 8949, 434, 4508, 2045, 287, 471, 326, 4207, 884, 5682, 326, 729, 1703, 5622, 2074, 598, 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, 225, 445, 389, 4110, 3678, 2555, 1190, 23461, 12, 203, 565, 467, 37, 7020, 389, 9406, 16, 203, 565, 16724, 5749, 18, 5679, 5749, 3778, 389, 1019, 1225, 16, 203, 565, 11322, 18, 12586, 3778, 389, 12910, 2045, 287, 16, 203, 565, 11322, 18, 12586, 3778, 389, 298, 5682, 16, 203, 565, 11322, 18, 12586, 3778, 389, 87, 3169, 2433, 203, 225, 262, 2713, 288, 203, 565, 261, 5749, 18, 12586, 3778, 6085, 80, 16, 11322, 18, 12586, 3778, 15103, 13, 273, 389, 9406, 203, 1377, 263, 12448, 14667, 24899, 12910, 2045, 287, 18, 16411, 40, 24899, 298, 5682, 10019, 203, 565, 11322, 18, 12586, 3778, 2078, 8018, 273, 389, 12910, 2045, 287, 18, 1289, 40, 12, 3490, 80, 2934, 1289, 40, 12, 26007, 1769, 203, 203, 565, 467, 654, 39, 3462, 3862, 6672, 273, 389, 9406, 18, 6889, 6672, 5621, 203, 565, 389, 12908, 537, 12, 6889, 6672, 16, 385, 900, 985, 1360, 7995, 8001, 16, 2078, 8018, 1769, 203, 203, 565, 1426, 389, 291, 3708, 273, 389, 1019, 1225, 18, 291, 14959, 1435, 692, 629, 294, 638, 31, 203, 203, 565, 11322, 18, 12586, 3778, 389, 1467, 273, 389, 1019, 1225, 18, 5113, 5621, 203, 565, 11322, 18, 12586, 3778, 389, 6889, 273, 261, 15188, 7020, 24899, 9406, 13, 203, 1377, 263, 588, 1447, 5147, 24899, 291, 3708, 692, 467, 37, 7020, 18, 1621, 18, 22122, 67, 11249, 67, 2192, 49, 294, 467, 37, 7020, 18, 1621, 18, 8355, 67, 4296, 67, 2192, 49, 16, 389, 1467, 10019, 203, 565, 389, 298, 2 ]
//Address: 0x74384b6355ad7892c7be6cb524d72768a3883f0c //Contract name: REDCrowdfund //Balance: 0 Ether //Verification Date: 1/9/2018 //Transacion Count: 263 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ 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 { 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); } contract REDToken is ERC20, Ownable { using SafeMath for uint; /*----------------- Token Information -----------------*/ string public constant name = "Red Community Token"; string public constant symbol = "RED"; uint8 public decimals = 18; // (ERC20 API) Decimal precision, factor is 1e18 mapping (address => uint256) angels; // Angels accounts table (during locking period only) mapping (address => uint256) accounts; // User's accounts table mapping (address => mapping (address => uint256)) allowed; // User's allowances table /*----------------- ICO Information -----------------*/ uint256 public angelSupply; // Angels sale supply uint256 public earlyBirdsSupply; // Early birds supply uint256 public publicSupply; // Open round supply uint256 public foundationSupply; // Red Foundation/Community supply uint256 public redTeamSupply; // Red team supply uint256 public marketingSupply; // Marketing & strategic supply uint256 public angelAmountRemaining; // Amount of private angels tokens remaining at a given time uint256 public icoStartsAt; // Crowdsale ending timestamp uint256 public icoEndsAt; // Crowdsale ending timestamp uint256 public redTeamLockingPeriod; // Locking period for Red team's supply uint256 public angelLockingPeriod; // Locking period for Angel's supply address public crowdfundAddress; // Crowdfunding contract address address public redTeamAddress; // Red team address address public foundationAddress; // Foundation address address public marketingAddress; // Private equity address bool public unlock20Done = false; // Allows the 20% unlocking for angels only once enum icoStages { Ready, // Initial state on contract's creation EarlyBirds, // Early birds state PublicSale, // Public crowdsale state Done // Ending state after ICO } icoStages stage; // Crowdfunding current state /*----------------- Events -----------------*/ event EarlyBirdsFinalized(uint tokensRemaining); // Event called when early birds round is done event CrowdfundFinalized(uint tokensRemaining); // Event called when crowdfund is done /*----------------- Modifiers -----------------*/ modifier nonZeroAddress(address _to) { // Ensures an address is provided require(_to != 0x0); _; } modifier nonZeroAmount(uint _amount) { // Ensures a non-zero amount require(_amount > 0); _; } modifier nonZeroValue() { // Ensures a non-zero value is passed require(msg.value > 0); _; } modifier onlyDuringCrowdfund(){ // Ensures actions can only happen after crowdfund ends require((now >= icoStartsAt) && (now < icoEndsAt)); _; } modifier notBeforeCrowdfundEnds(){ // Ensures actions can only happen after crowdfund ends require(now >= icoEndsAt); _; } modifier checkRedTeamLockingPeriod() { // Ensures locking period is over require(now >= redTeamLockingPeriod); _; } modifier checkAngelsLockingPeriod() { // Ensures locking period is over require(now >= angelLockingPeriod); _; } modifier onlyCrowdfund() { // Ensures only crowdfund can call the function require(msg.sender == crowdfundAddress); _; } /*----------------- ERC20 API -----------------*/ // ------------------------------------------------- // Transfers amount to address // ------------------------------------------------- function transfer(address _to, uint256 _amount) public notBeforeCrowdfundEnds returns (bool success) { require(accounts[msg.sender] >= _amount); // check amount of balance can be tranfered addToBalance(_to, _amount); decrementBalance(msg.sender, _amount); Transfer(msg.sender, _to, _amount); return true; } // ------------------------------------------------- // Transfers from one address to another (need allowance to be called first) // ------------------------------------------------- function transferFrom(address _from, address _to, uint256 _amount) public notBeforeCrowdfundEnds returns (bool success) { require(allowance(_from, msg.sender) >= _amount); decrementBalance(_from, _amount); addToBalance(_to, _amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); Transfer(_from, _to, _amount); return true; } // ------------------------------------------------- // Approves another address a certain amount of RED // ------------------------------------------------- function approve(address _spender, uint256 _value) public returns (bool success) { require((_value == 0) || (allowance(msg.sender, _spender) == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } // ------------------------------------------------- // Gets an address's RED allowance // ------------------------------------------------- function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // ------------------------------------------------- // Gets the RED balance of any address // ------------------------------------------------- function balanceOf(address _owner) public constant returns (uint256 balance) { return accounts[_owner] + angels[_owner]; } /*----------------- Token API -----------------*/ // ------------------------------------------------- // Contract's constructor // ------------------------------------------------- function REDToken() public { totalSupply = 200000000 * 1e18; // 100% - 200 million total RED with 18 decimals angelSupply = 20000000 * 1e18; // 10% - 20 million RED for private angels sale earlyBirdsSupply = 48000000 * 1e18; // 24% - 48 million RED for early-bird sale publicSupply = 12000000 * 1e18; // 6% - 12 million RED for the public crowdsale redTeamSupply = 30000000 * 1e18; // 15% - 30 million RED for Red team foundationSupply = 70000000 * 1e18; // 35% - 70 million RED for foundation/incentivising efforts marketingSupply = 20000000 * 1e18; // 10% - 20 million RED for covering marketing and strategic expenses angelAmountRemaining = angelSupply; // Decreased over the course of the private angel sale redTeamAddress = 0x31aa507c140E012d0DcAf041d482e04F36323B03; // Red Team address foundationAddress = 0x93e3AF42939C163Ee4146F63646Fb4C286CDbFeC; // Foundation/Community address marketingAddress = 0x0; // Marketing/Strategic address icoStartsAt = 1515398400; // Jan 8th 2018, 16:00, GMT+8 icoEndsAt = 1517385600; // Jan 31th 2018, 16:00, GMT+8 angelLockingPeriod = icoEndsAt.add(90 days); // 3 months locking period redTeamLockingPeriod = icoEndsAt.add(365 days); // 12 months locking period addToBalance(foundationAddress, foundationSupply); stage = icoStages.Ready; // Initializes state } // ------------------------------------------------- // Opens early birds sale // ------------------------------------------------- function startCrowdfund() external onlyCrowdfund onlyDuringCrowdfund returns(bool) { require(stage == icoStages.Ready); stage = icoStages.EarlyBirds; addToBalance(crowdfundAddress, earlyBirdsSupply); return true; } // ------------------------------------------------- // Returns TRUE if early birds round is currently going on // ------------------------------------------------- function isEarlyBirdsStage() external view returns(bool) { return (stage == icoStages.EarlyBirds); } // ------------------------------------------------- // Sets the crowdfund address, can only be done once // ------------------------------------------------- function setCrowdfundAddress(address _crowdfundAddress) external onlyOwner nonZeroAddress(_crowdfundAddress) { require(crowdfundAddress == 0x0); crowdfundAddress = _crowdfundAddress; } // ------------------------------------------------- // Function for the Crowdfund to transfer tokens // ------------------------------------------------- function transferFromCrowdfund(address _to, uint256 _amount) external onlyCrowdfund nonZeroAmount(_amount) nonZeroAddress(_to) returns (bool success) { require(balanceOf(crowdfundAddress) >= _amount); decrementBalance(crowdfundAddress, _amount); addToBalance(_to, _amount); Transfer(0x0, _to, _amount); return true; } // ------------------------------------------------- // Releases Red team supply after locking period is passed // ------------------------------------------------- function releaseRedTeamTokens() external checkRedTeamLockingPeriod onlyOwner returns(bool success) { require(redTeamSupply > 0); addToBalance(redTeamAddress, redTeamSupply); Transfer(0x0, redTeamAddress, redTeamSupply); redTeamSupply = 0; return true; } // ------------------------------------------------- // Releases Marketing & strategic supply // ------------------------------------------------- function releaseMarketingTokens() external onlyOwner returns(bool success) { require(marketingSupply > 0); addToBalance(marketingAddress, marketingSupply); Transfer(0x0, marketingAddress, marketingSupply); marketingSupply = 0; return true; } // ------------------------------------------------- // Finalizes early birds round. If some RED are left, let them overflow to the crowdfund // ------------------------------------------------- function finalizeEarlyBirds() external onlyOwner returns (bool success) { require(stage == icoStages.EarlyBirds); uint256 amount = balanceOf(crowdfundAddress); addToBalance(crowdfundAddress, publicSupply); stage = icoStages.PublicSale; EarlyBirdsFinalized(amount); // event log return true; } // ------------------------------------------------- // Finalizes crowdfund. If there are leftover RED, let them overflow to foundation // ------------------------------------------------- function finalizeCrowdfund() external onlyCrowdfund { require(stage == icoStages.PublicSale); uint256 amount = balanceOf(crowdfundAddress); if (amount > 0) { accounts[crowdfundAddress] = 0; addToBalance(foundationAddress, amount); Transfer(crowdfundAddress, foundationAddress, amount); } stage = icoStages.Done; CrowdfundFinalized(amount); // event log } // ------------------------------------------------- // Changes Red Team wallet // ------------------------------------------------- function changeRedTeamAddress(address _wallet) external onlyOwner { redTeamAddress = _wallet; } // ------------------------------------------------- // Changes Marketing&Strategic wallet // ------------------------------------------------- function changeMarketingAddress(address _wallet) external onlyOwner { marketingAddress = _wallet; } // ------------------------------------------------- // Function to unlock 20% RED to private angels investors // ------------------------------------------------- function partialUnlockAngelsAccounts(address[] _batchOfAddresses) external onlyOwner notBeforeCrowdfundEnds returns (bool success) { require(unlock20Done == false); uint256 amount; address holder; for (uint256 i = 0; i < _batchOfAddresses.length; i++) { holder = _batchOfAddresses[i]; amount = angels[holder].mul(20).div(100); angels[holder] = angels[holder].sub(amount); addToBalance(holder, amount); } unlock20Done = true; return true; } // ------------------------------------------------- // Function to unlock all remaining RED to private angels investors (after 3 months) // ------------------------------------------------- function fullUnlockAngelsAccounts(address[] _batchOfAddresses) external onlyOwner checkAngelsLockingPeriod returns (bool success) { uint256 amount; address holder; for (uint256 i = 0; i < _batchOfAddresses.length; i++) { holder = _batchOfAddresses[i]; amount = angels[holder]; angels[holder] = 0; addToBalance(holder, amount); } return true; } // ------------------------------------------------- // Function to reserve RED to private angels investors (initially locked) // the amount of RED is in Wei // ------------------------------------------------- function deliverAngelsREDAccounts(address[] _batchOfAddresses, uint[] _amountOfRED) external onlyOwner onlyDuringCrowdfund returns (bool success) { for (uint256 i = 0; i < _batchOfAddresses.length; i++) { deliverAngelsREDBalance(_batchOfAddresses[i], _amountOfRED[i]); } return true; } /*----------------- Helper functions -----------------*/ // ------------------------------------------------- // If one address has contributed more than once, // the contributions will be aggregated // ------------------------------------------------- function deliverAngelsREDBalance(address _accountHolder, uint _amountOfBoughtRED) internal onlyOwner { require(angelAmountRemaining > 0); angels[_accountHolder] = angels[_accountHolder].add(_amountOfBoughtRED); Transfer(0x0, _accountHolder, _amountOfBoughtRED); angelAmountRemaining = angelAmountRemaining.sub(_amountOfBoughtRED); } // ------------------------------------------------- // Adds to balance // ------------------------------------------------- function addToBalance(address _address, uint _amount) internal { accounts[_address] = accounts[_address].add(_amount); } // ------------------------------------------------- // Removes from balance // ------------------------------------------------- function decrementBalance(address _address, uint _amount) internal { accounts[_address] = accounts[_address].sub(_amount); } } contract REDCrowdfund is Ownable { using SafeMath for uint; mapping (address => bool) whiteList; // Buyers whitelisting mapping bool public isOpen = false; // Is the crowd fund open? address public tokenAddress; // Address of the deployed RED token contract address public wallet; // Address of secure wallet to receive crowdfund contributions uint256 public weiRaised = 0; uint256 public startsAt; // Crowdfund starting time (Epoch format) uint256 public endsAt; // Crowdfund ending time (Epoch format) REDToken public RED; // Instance of the RED token contract /*----------------- Events -----------------*/ event WalletAddressChanged(address _wallet); // Triggered upon owner changing the wallet address event AmountRaised(address beneficiary, uint amountRaised); // Triggered upon crowdfund being finalized event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount); // Triggered upon purchasing tokens /*----------------- Modifiers -----------------*/ modifier nonZeroAddress(address _to) { // Ensures an address is provided require(_to != 0x0); _; } modifier nonZeroValue() { // Ensures a non-zero value is passed require(msg.value > 0); _; } modifier crowdfundIsActive() { // Ensures the crowdfund is ongoing require(isOpen && now >= startsAt && now <= endsAt); _; } modifier notBeforeCrowdfundEnds(){ // Ensures actions can only happen after crowdfund ends require(now >= endsAt); _; } modifier onlyWhiteList() { // Ensures only whitelisted address can buy tokens require(whiteList[msg.sender]); _; } /*----------------- Crowdfunding API -----------------*/ // ------------------------------------------------- // Contract's constructor // ------------------------------------------------- function REDCrowdfund(address _tokenAddress) public { wallet = 0xc65f0d8a880f3145157117Af73fe2e6e8E60eF3c; // ICO wallet address startsAt = 1515398400; // Jan 8th 2018, 16:00, GMT+8 endsAt = 1517385600; // Jan 31th 2018, 16:00, GMT+8 tokenAddress = _tokenAddress; // RED token Address RED = REDToken(tokenAddress); } // ------------------------------------------------- // Changes main contribution wallet // ------------------------------------------------- function changeWalletAddress(address _wallet) external onlyOwner { wallet = _wallet; WalletAddressChanged(_wallet); } // ------------------------------------------------- // Opens the crowdfunding // ------------------------------------------------- function openCrowdfund() external onlyOwner returns (bool success) { require(isOpen == false); RED.startCrowdfund(); isOpen = true; return true; } // ------------------------------------------------- // Function to buy RED. One can also buy RED by calling this function directly and send // it to another destination. // ------------------------------------------------- function buyTokens(address _to) public crowdfundIsActive onlyWhiteList nonZeroAddress(_to) nonZeroValue payable { uint256 weiAmount = msg.value; uint256 tokens; uint price = 2500; if (RED.isEarlyBirdsStage()) {price = 2750;} // 10% discount for early birds tokens = weiAmount * price; weiRaised = weiRaised.add(weiAmount); wallet.transfer(weiAmount); if (!RED.transferFromCrowdfund(_to, tokens)) {revert();} TokenPurchase(_to, weiAmount, tokens); } // ------------------------------------------------- // Closes the crowdfunding. Any unsold RED will go back to the foundation. // ------------------------------------------------- function closeCrowdfund() external notBeforeCrowdfundEnds onlyOwner returns (bool success) { AmountRaised(wallet, weiRaised); RED.finalizeCrowdfund(); isOpen = false; return true; } // ------------------------------------------------- // Function to whitelist buyers // ------------------------------------------------- function whitelistAccounts(address[] _batchOfAddresses) external onlyOwner returns (bool success) { for (uint256 i = 0; i < _batchOfAddresses.length; i++) { whiteList[_batchOfAddresses[i]] = true; } return true; } /*----------------- Entry point -----------------*/ // ------------------------------------------------- // To contribute, send a value transaction to the crowdfund address. // Please include at least 100000 gas. // ------------------------------------------------- function () public payable { buyTokens(msg.sender); } }
------------------------------------------------- Function for the Crowdfund to transfer tokens -------------------------------------------------
function transferFromCrowdfund(address _to, uint256 _amount) external onlyCrowdfund nonZeroAmount(_amount) nonZeroAddress(_to) returns (bool success) { require(balanceOf(crowdfundAddress) >= _amount); decrementBalance(crowdfundAddress, _amount); addToBalance(_to, _amount); Transfer(0x0, _to, _amount); return true; }
5,346,909
[ 1, 9634, 17, 4284, 364, 326, 385, 492, 2180, 1074, 358, 7412, 2430, 13420, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 1265, 39, 492, 2180, 1074, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 3903, 1338, 39, 492, 2180, 1074, 1661, 7170, 6275, 24899, 8949, 13, 1661, 7170, 1887, 24899, 869, 13, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 2583, 12, 12296, 951, 12, 71, 492, 2180, 1074, 1887, 13, 1545, 389, 8949, 1769, 203, 3639, 15267, 13937, 12, 71, 492, 2180, 1074, 1887, 16, 389, 8949, 1769, 203, 3639, 9604, 13937, 24899, 869, 16, 389, 8949, 1769, 203, 3639, 12279, 12, 20, 92, 20, 16, 389, 869, 16, 389, 8949, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.7; // Allows anyone to claim a token if they exist in a merkle root abstract contract IMerkleDistributor { // Time from the moment this contract is deployed and until the owner can withdraw leftover tokens uint256 public constant timelapseUntilWithdrawWindow = 90 days; // Returns the address of the token distributed by this contract function token() virtual external view returns (address); // Returns the merkle root of the merkle tree containing account balances available to claim function merkleRoot() virtual external view returns (bytes32); // Returns the timestamp when this contract was deployed function deploymentTime() virtual external view returns (uint256); // Returns the address for the owner of this contract function owner() virtual external view returns (address); // Returns true if the index has been marked claimed function isClaimed(uint256 index) virtual external view returns (bool); // Send tokens to an address without that address claiming them function sendTokens(address dst, uint256 tokenAmount) virtual external; // Claim the given amount of the token to the given address. Reverts if the inputs are invalid function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) virtual external; // This event is triggered whenever an address is added to the set of authed addresses event AddAuthorization(address account); // This event is triggered whenever an address is removed from the set of authed addresses event RemoveAuthorization(address account); // This event is triggered whenever a call to #claim succeeds event Claimed(uint256 index, address account, uint256 amount); // This event is triggered whenever some tokens are sent to an address without that address claiming them event SendTokens(address dst, uint256 tokenAmount); } /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } /** * @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); } contract MerkleDistributor is IMerkleDistributor { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) virtual external isAuthorized { authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) virtual external isAuthorized { authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "MerkleDistributorFactory/account-not-authorized"); _; } /* * @notify Checks whether an address can send tokens out of this contract */ modifier canSendTokens { require( either(authorizedAccounts[msg.sender] == 1, both(owner == msg.sender, now >= addition(deploymentTime, timelapseUntilWithdrawWindow))), "MerkleDistributorFactory/cannot-send-tokens" ); _; } // The token being distributed address public immutable override token; // The owner of this contract address public immutable override owner; // The merkle root of all addresses that get a distribution bytes32 public immutable override merkleRoot; // Timestamp when this contract was deployed uint256 public immutable override deploymentTime; // This is a packed array of booleans mapping(uint256 => uint256) private claimedBitMap; constructor(address token_, bytes32 merkleRoot_) public { authorizedAccounts[msg.sender] = 1; owner = msg.sender; token = token_; merkleRoot = merkleRoot_; deploymentTime = now; emit AddAuthorization(msg.sender); } // --- Math --- function addition(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, "MerkleDistributorFactory/add-uint-uint-overflow"); } // --- Boolean Logic --- function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } // --- Administration --- /* * @notice Send tokens to an authorized address * @param dst The address to send tokens to * @param tokenAmount The amount of tokens to send */ function sendTokens(address dst, uint256 tokenAmount) external override canSendTokens { require(dst != address(0), "MerkleDistributorFactory/null-dst"); IERC20(token).transfer(dst, tokenAmount); emit SendTokens(dst, tokenAmount); } /* * @notice View function returning whether an address has already claimed their tokens * @param index The position of the address inside the merkle tree */ function isClaimed(uint256 index) public view override returns (bool) { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; uint256 claimedWord = claimedBitMap[claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } /* * @notice Mark an address as having claimed their distribution * @param index The position of the address inside the merkle tree */ function _setClaimed(uint256 index) private { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; claimedBitMap[claimedWordIndex] = claimedBitMap[claimedWordIndex] | (1 << claimedBitIndex); } /* * @notice Claim your distribution * @param index The position of the address inside the merkle tree * @param account The actual address from the tree * @param amount The amount being distributed * @param merkleProof The merkle path used to prove that the address is in the tree and can claim amount tokens */ function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external override { require(!isClaimed(index), 'MerkleDistributor/drop-already-claimed'); // Verify the merkle proof bytes32 node = keccak256(abi.encodePacked(index, account, amount)); require(MerkleProof.verify(merkleProof, merkleRoot, node), 'MerkleDistributor/invalid-proof'); // Mark it claimed and send the token _setClaimed(index); require(IERC20(token).transfer(account, amount), 'MerkleDistributor/transfer-failed'); emit Claimed(index, account, amount); } } contract MerkleDistributorFactory { // --- Auth --- mapping (address => uint) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) virtual external isAuthorized { authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) virtual external isAuthorized { authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "MerkleDistributorFactory/account-not-authorized"); _; } // --- Variables --- // Number of distributors created uint256 public nonce; // The token that's being distributed by every merkle distributor address public distributedToken; // Mapping of ID => distributor address mapping(uint256 => address) public distributors; // Tokens left to distribute to every distributor mapping(uint256 => uint256) public tokensToDistribute; // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event DeployDistributor(uint256 id, address distributor, uint256 tokenAmount); event SendTokensToDistributor(uint256 id); constructor(address distributedToken_) public { require(distributedToken_ != address(0), "MerkleDistributorFactory/null-distributed-token"); authorizedAccounts[msg.sender] = 1; distributedToken = distributedToken_; emit AddAuthorization(msg.sender); } // --- Math --- function addition(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, "MerkleDistributorFactory/add-uint-uint-overflow"); } // --- Core Logic --- /* * @notice Deploy a new merkle distributor * @param merkleRoot The merkle root used in the distributor */ function deployDistributor(bytes32 merkleRoot, uint256 tokenAmount) external isAuthorized { require(tokenAmount > 0, "MerkleDistributorFactory/null-token-amount"); nonce = addition(nonce, 1); address newDistributor = address(new MerkleDistributor(distributedToken, merkleRoot)); distributors[nonce] = newDistributor; tokensToDistribute[nonce] = tokenAmount; emit DeployDistributor(nonce, newDistributor, tokenAmount); } /* * @notice Send tokens to a distributor * @param nonce The nonce/id of the distributor to send tokens to */ function sendTokensToDistributor(uint256 id) external isAuthorized { require(tokensToDistribute[id] > 0, "MerkleDistributorFactory/nothing-to-send"); uint256 tokensToSend = tokensToDistribute[id]; tokensToDistribute[id] = 0; IERC20(distributedToken).transfer(distributors[id], tokensToSend); emit SendTokensToDistributor(id); } /* * @notice Sent distributedToken tokens out of this contract and to a custom destination * @param dst The address that will receive tokens * @param tokenAmount The token amount to send */ function sendTokensToCustom(address dst, uint256 tokenAmount) external isAuthorized { require(dst != address(0), "MerkleDistributorFactory/null-dst"); IERC20(distributedToken).transfer(dst, tokenAmount); } /* * @notice This contract gives up on being an authorized address inside a specific distributor contract */ function dropDistributorAuth(uint256 id) external isAuthorized { MerkleDistributor(distributors[id]).removeAuthorization(address(this)); } /* * @notice Send tokens from a distributor contract to this contract */ function getBackTokensFromDistributor(uint256 id, uint256 tokenAmount) external isAuthorized { MerkleDistributor(distributors[id]).sendTokens(address(this), tokenAmount); } }
Tokens left to distribute to every distributor
mapping(uint256 => uint256) public tokensToDistribute;
481,853
[ 1, 5157, 2002, 358, 25722, 358, 3614, 1015, 19293, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 1071, 2430, 774, 1669, 887, 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 ]
automat sg { #region MODIF_TYPE:ADV // ------------------------------------------------------ // наречия, которые могут модифицировать другие наречия, // выступая в роли предшествующих модификаторов. // ------------------------------------------------------ tag eng_adverb:straight{ MODIF_TYPE:ADV } // Go straight back tag eng_adverb:impressively{ MODIF_TYPE:ADV } // The students progressed impressively fast. tag eng_adverb:only{ MODIF_TYPE:ADV } // We perceived the change only dimly. tag eng_adverb:almost{ MODIF_TYPE:ADV } tag eng_adverb:at least{ MODIF_TYPE:ADV } tag eng_adverb:a little{ MODIF_TYPE:ADV } tag eng_adverb:a bit{ MODIF_TYPE:ADV } tag eng_adverb:a little bit{ MODIF_TYPE:ADV } tag eng_adverb:a little while{ MODIF_TYPE:ADV } tag eng_adverb:pretty{ MODIF_TYPE:ADV } tag eng_adverb:always{ MODIF_TYPE:ADV } tag eng_adverb:extremely{ MODIF_TYPE:ADV } tag eng_adverb:exceptionally{ MODIF_TYPE:ADV } tag eng_adverb:unbelievably{ MODIF_TYPE:ADV } tag eng_adverb:incurably{ MODIF_TYPE:ADV } tag eng_adverb:extraordinarily{ MODIF_TYPE:ADV } tag eng_adverb:jolly{ MODIF_TYPE:ADV } tag eng_adverb:mighty{ MODIF_TYPE:ADV } tag eng_adverb:damn{ MODIF_TYPE:ADV } tag eng_adverb:so{ MODIF_TYPE:ADV } tag eng_adverb:exceedingly{ MODIF_TYPE:ADV } tag eng_adverb:overly{ MODIF_TYPE:ADV } tag eng_adverb:downright{ MODIF_TYPE:ADV } tag eng_adverb:plumb{ MODIF_TYPE:ADV } tag eng_adverb:vitally{ MODIF_TYPE:ADV } tag eng_adverb:abundantly{ MODIF_TYPE:ADV } tag eng_adverb:chronically{ MODIF_TYPE:ADV } tag eng_adverb:frightfully{ MODIF_TYPE:ADV } tag eng_adverb:genuinely{ MODIF_TYPE:ADV } tag eng_adverb:humanly{ MODIF_TYPE:ADV } tag eng_adverb:patently{ MODIF_TYPE:ADV } tag eng_adverb:singularly{ MODIF_TYPE:ADV } tag eng_adverb:supremely{ MODIF_TYPE:ADV } tag eng_adverb:unbearably{ MODIF_TYPE:ADV } tag eng_adverb:unmistakably{ MODIF_TYPE:ADV } tag eng_adverb:unspeakably{ MODIF_TYPE:ADV } tag eng_adverb:awfully{ MODIF_TYPE:ADV } tag eng_adverb:decidedly{ MODIF_TYPE:ADV } tag eng_adverb:demonstrably{ MODIF_TYPE:ADV } tag eng_adverb:fashionably{ MODIF_TYPE:ADV } tag eng_adverb:frighteningly{ MODIF_TYPE:ADV } tag eng_adverb:horrifyingly{ MODIF_TYPE:ADV } tag eng_adverb:indescribably{ MODIF_TYPE:ADV } tag eng_adverb:intolerably{ MODIF_TYPE:ADV } tag eng_adverb:laughably{ MODIF_TYPE:ADV } tag eng_adverb:predominantly { MODIF_TYPE:ADV } tag eng_adverb:unalterably{ MODIF_TYPE:ADV } tag eng_adverb:undisputedly{ MODIF_TYPE:ADV } tag eng_adverb:unpardonably{ MODIF_TYPE:ADV } tag eng_adverb:unreasonably{ MODIF_TYPE:ADV } tag eng_adverb:unusually{ MODIF_TYPE:ADV } tag eng_adverb:hugely{ MODIF_TYPE:ADV } tag eng_adverb:infernally{ MODIF_TYPE:ADV } tag eng_adverb:notoriously{ MODIF_TYPE:ADV } tag eng_adverb:fabulously{ MODIF_TYPE:ADV } tag eng_adverb:incomparably{ MODIF_TYPE:ADV } tag eng_adverb:inherently{ MODIF_TYPE:ADV } tag eng_adverb:marginally{ MODIF_TYPE:ADV } tag eng_adverb:moderately { MODIF_TYPE:ADV } tag eng_adverb:relatively{ MODIF_TYPE:ADV } tag eng_adverb:ridiculously { MODIF_TYPE:ADV } tag eng_adverb:unacceptably{ MODIF_TYPE:ADV } tag eng_adverb:unarguably{ MODIF_TYPE:ADV } tag eng_adverb:undeniably{ MODIF_TYPE:ADV } tag eng_adverb:unimaginably{ MODIF_TYPE:ADV } tag eng_adverb:wide{ MODIF_TYPE:ADV } tag eng_adverb:very{ MODIF_TYPE:ADV } tag eng_adverb:way{ MODIF_TYPE:ADV } tag eng_adverb:real{ MODIF_TYPE:ADV } tag eng_adverb:quite{ MODIF_TYPE:ADV } tag eng_adverb:amazingly{ MODIF_TYPE:ADV } tag eng_adverb:strangely{ MODIF_TYPE:ADV } tag eng_adverb:incredibly{ MODIF_TYPE:ADV } tag eng_adverb:rather{ MODIF_TYPE:ADV } tag eng_adverb:particularly{ MODIF_TYPE:ADV } tag eng_adverb:notably{ MODIF_TYPE:ADV } tag eng_adverb:almost nearly{ MODIF_TYPE:ADV } tag eng_adverb:entirely{ MODIF_TYPE:ADV } tag eng_adverb:reasonably{ MODIF_TYPE:ADV } tag eng_adverb:highly{ MODIF_TYPE:ADV } tag eng_adverb:fairly{ MODIF_TYPE:ADV } tag eng_adverb:totally{ MODIF_TYPE:ADV } tag eng_adverb:completely{ MODIF_TYPE:ADV } tag eng_adverb:terribly{ MODIF_TYPE:ADV } tag eng_adverb:absolutely{ MODIF_TYPE:ADV } tag eng_adverb:altogether{ MODIF_TYPE:ADV } tag eng_adverb:equally{ MODIF_TYPE:ADV } tag eng_adverb:really{ MODIF_TYPE:ADV } tag eng_adverb:surprisingly{ MODIF_TYPE:ADV } tag eng_adverb:especially{ MODIF_TYPE:ADV } tag eng_adverb:virtually{ MODIF_TYPE:ADV } tag eng_adverb:too{ MODIF_TYPE:ADV } #endregion MODIF_TYPE:ADV #region MODIF_TYPE:COMPAR_ADV // --------------------------------------------------- // Модификаторы для наречий в сравнительной степени // --------------------------------------------------- tag eng_adverb:significantly{ MODIF_TYPE:COMPAR_ADV } tag eng_adverb:much{ MODIF_TYPE:COMPAR_ADV } tag eng_adverb:slightly{ MODIF_TYPE:COMPAR_ADV } tag eng_adverb:marginally{ MODIF_TYPE:COMPAR_ADV } // That one is marginally better tag eng_adverb:inherently{ MODIF_TYPE:COMPAR_ADV } // It's an inherently better method tag eng_adverb:fabulously{ MODIF_TYPE:COMPAR_ADV } tag eng_adverb:incomparably{ MODIF_TYPE:COMPAR_ADV } tag eng_adverb:moderately{ MODIF_TYPE:COMPAR_ADV } tag eng_adverb:relatively{ MODIF_TYPE:COMPAR_ADV } tag eng_adverb:ridiculously{ MODIF_TYPE:COMPAR_ADV } tag eng_adverb:unacceptably{ MODIF_TYPE:COMPAR_ADV } tag eng_adverb:unarguably{ MODIF_TYPE:COMPAR_ADV } tag eng_adverb:undeniably{ MODIF_TYPE:COMPAR_ADV } tag eng_adverb:unimaginably{ MODIF_TYPE:COMPAR_ADV } #endregion MODIF_TYPE:COMPAR_ADV #region MODIF_TYPE:ADJ // Наречия, которые могут модифицировать прилагательные в позиции слева. tag eng_adverb:generally{ MODIF_TYPE:ADJ } // Such hybrids are generally infertile. tag eng_adverb:overall{ MODIF_TYPE:ADJ } // The prognosis is overall poor. tag eng_adverb:whole{ MODIF_TYPE:ADJ } // I ate a fish whole! tag eng_adverb:also{ MODIF_TYPE:ADJ } // Dappled eyes are also possible. tag eng_adverb:increasingly{ MODIF_TYPE:ADJ } // It also became increasingly violent. tag eng_adverb:apparently{ MODIF_TYPE:ADJ } // An apparently arbitrary and reasonless change tag eng_adverb:Melodically{ MODIF_TYPE:ADJ } // Melodically interesting themes tag eng_adverb:Denominationally{ MODIF_TYPE:ADJ } // Denominationally diverse audiences tag eng_adverb:absurdly{ MODIF_TYPE:ADJ } // An absurdly rich young woman tag eng_adverb:Uncannily{ MODIF_TYPE:ADJ } // Uncannily human robots tag eng_adverb:vapidly{ MODIF_TYPE:ADJ } // A vapidly smiling salesman tag eng_adverb:unswervingly{ MODIF_TYPE:ADJ } // An unswervingly loyal man tag eng_adverb:Floridly{ MODIF_TYPE:ADJ } // Floridly figurative prose tag eng_adverb:Boringly{ MODIF_TYPE:ADJ } // Boringly slow work tag eng_adverb:Nocturnally{ MODIF_TYPE:ADJ } // Nocturnally active bird tag eng_adverb:actually{ MODIF_TYPE:ADJ } // The specimens are actually different from each other tag eng_adverb:simply{ MODIF_TYPE:ADJ } // We are simply broke. tag eng_adverb:obviously{ MODIF_TYPE:ADJ } // The answer is obviously wrong. tag eng_adverb:enviably{ MODIF_TYPE:ADJ } // She was enviably fluent in French. tag eng_adverb:crucially{ MODIF_TYPE:ADJ } // crucially important tag eng_adverb:dauntingly{ MODIF_TYPE:ADJ } // dauntingly difficult tag eng_adverb:cerebrally{ MODIF_TYPE:ADJ } // cerebrally active tag eng_adverb:territorially{ MODIF_TYPE:ADJ } // territorially important tag eng_adverb:scholastically{ MODIF_TYPE:ADJ } // scholastically apt tag eng_adverb:repellently{ MODIF_TYPE:ADJ } // repellently fat tag eng_adverb:screamingly{ MODIF_TYPE:ADJ } // screamingly funny tag eng_adverb:deucedly{ MODIF_TYPE:ADJ } // deucedly clever tag eng_adverb:deadly{ MODIF_TYPE:ADJ } // deadly dull tag eng_adverb:hellishly{ MODIF_TYPE:ADJ } // hellishly dangerous tag eng_adverb:chromatically{ MODIF_TYPE:ADJ } // chromatically pure tag eng_adverb:biradially{ MODIF_TYPE:ADJ } // biradially symmetrical tag eng_adverb:typically{ MODIF_TYPE:ADJ } // Tom was typically hostile. tag eng_adverb:relativistically{ MODIF_TYPE:ADJ } // This is relativistically impossible. tag eng_adverb:exultingly{ MODIF_TYPE:ADJ } // It was exultingly easy. tag eng_adverb:rollickingly{ MODIF_TYPE:ADJ } // She was rollickingly happy. tag eng_adverb:bewilderingly{ MODIF_TYPE:ADJ } // Her situation was bewilderingly unclear. tag eng_adverb:gratifyingly{ MODIF_TYPE:ADJ } // The performance was at a gratifyingly high level. tag eng_adverb:healthily{ MODIF_TYPE:ADJ } // The answers were healthily individual. tag eng_adverb:sufficiently{ MODIF_TYPE:ADJ } // She was sufficiently fluent in Mandarin. tag eng_adverb:surely{ MODIF_TYPE:ADJ } // The results are surely encouraging. tag eng_adverb:glaringly{ MODIF_TYPE:ADJ } // It was glaringly obvious. tag eng_adverb:uncharacteristically{ MODIF_TYPE:ADJ } // He was uncharacteristically cool. tag eng_adverb:discouragingly{ MODIF_TYPE:ADJ } // The failure rate on the bar exam is discouragingly high. tag eng_adverb:basically{ MODIF_TYPE:ADJ } // He is basically dishonest. tag eng_adverb:deliciously{ MODIF_TYPE:ADJ } // I bought some more of these deliciously sweet peaches. tag eng_adverb:bewitchingly{ MODIF_TYPE:ADJ } // She was bewitchingly beautiful. tag eng_adverb:captiously{ MODIF_TYPE:ADJ } // He was captiously pedantic. tag eng_adverb:potentially{ MODIF_TYPE:ADJ } // He is potentially dangerous. tag eng_adverb:contagiously{ MODIF_TYPE:ADJ } // She was contagiously bubbly. tag eng_adverb:goddamn{ MODIF_TYPE:ADJ } // You are goddamn right! tag eng_adverb:impracticably{ MODIF_TYPE:ADJ } // This is still impracticably high. tag eng_adverb:ravishingly{ MODIF_TYPE:ADJ } // She was ravishingly beautiful. tag eng_adverb:preternaturally{ MODIF_TYPE:ADJ } // She was preternaturally beautiful. tag eng_adverb:pleasingly{ MODIF_TYPE:ADJ } // The room was pleasingly large. tag eng_adverb:nowise{ MODIF_TYPE:ADJ } // They are nowise different. tag eng_adverb:mistily{ MODIF_TYPE:ADJ } // The summits of the mountains were mistily purple. tag eng_adverb:identifiably{ MODIF_TYPE:ADJ } // They were identifiably different. tag eng_adverb:so{ MODIF_TYPE:ADJ } // Are you so foolish? tag eng_adverb:unattainably{ MODIF_TYPE:ADJ } tag eng_adverb:tropically{ MODIF_TYPE:ADJ } // It was tropically hot in the greenhouse. tag eng_adverb:unwantedly{ MODIF_TYPE:ADJ } // He was unwantedly friendly. tag eng_adverb:demandingly{ MODIF_TYPE:ADJ } // He became demandingly dominant over the years. tag eng_adverb:greasily{ MODIF_TYPE:ADJ } // The food was greasily unappetizing. tag eng_adverb:often{ MODIF_TYPE:ADJ } // He was often friendly tag eng_adverb:vanishingly{ MODIF_TYPE:ADJ } // a vanishingly small dog tag eng_adverb:unbreathably{ MODIF_TYPE:ADJ } // It was unbreathably hot tag eng_adverb:unaccountably{ MODIF_TYPE:ADJ } // The jury was unaccountably slow tag eng_adverb:infinitely{ MODIF_TYPE:ADJ } // God is infinitely and unchangeably good tag eng_adverb:unexplainably{ MODIF_TYPE:ADJ } // His salary is unexplainably high tag eng_adverb:unnervingly{ MODIF_TYPE:ADJ } // Her companion was unnervingly quiet tag eng_adverb:unseasonally{ MODIF_TYPE:ADJ } // They had an unseasonally warm winter tag eng_adverb:a little{ MODIF_TYPE:ADJ } tag eng_adverb:slightly{ MODIF_TYPE:ADJ } tag eng_adverb:somewhat{ MODIF_TYPE:ADJ } tag eng_adverb:pretty{ MODIF_TYPE:ADJ } tag eng_adverb:extremely{ MODIF_TYPE:ADJ } tag eng_adverb:exceptionally{ MODIF_TYPE:ADJ } tag eng_adverb:unbelievably{ MODIF_TYPE:ADJ } tag eng_adverb:incurably{ MODIF_TYPE:ADJ } tag eng_adverb:extraordinarily{ MODIF_TYPE:ADJ } tag eng_adverb:jolly{ MODIF_TYPE:ADJ } tag eng_adverb:mighty{ MODIF_TYPE:ADJ } tag eng_adverb:damn{ MODIF_TYPE:ADJ } tag eng_adverb:exceedingly{ MODIF_TYPE:ADJ } tag eng_adverb:overly{ MODIF_TYPE:ADJ } tag eng_adverb:downright{ MODIF_TYPE:ADJ } tag eng_adverb:plumb{ MODIF_TYPE:ADJ } tag eng_adverb:vitally{ MODIF_TYPE:ADJ } tag eng_adverb:abundantly{ MODIF_TYPE:ADJ } tag eng_adverb:chronically{ MODIF_TYPE:ADJ } tag eng_adverb:frightfully{ MODIF_TYPE:ADJ } tag eng_adverb:genuinely{ MODIF_TYPE:ADJ } tag eng_adverb:humanly{ MODIF_TYPE:ADJ } tag eng_adverb:patently{ MODIF_TYPE:ADJ } tag eng_adverb:singularly{ MODIF_TYPE:ADJ } tag eng_adverb:supremely{ MODIF_TYPE:ADJ } tag eng_adverb:unbearably{ MODIF_TYPE:ADJ } tag eng_adverb:unmistakably{ MODIF_TYPE:ADJ } tag eng_adverb:unspeakably{ MODIF_TYPE:ADJ } tag eng_adverb:awfully{ MODIF_TYPE:ADJ } tag eng_adverb:decidedly{ MODIF_TYPE:ADJ } tag eng_adverb:demonstrably{ MODIF_TYPE:ADJ } tag eng_adverb:fashionably{ MODIF_TYPE:ADJ } tag eng_adverb:frighteningly{ MODIF_TYPE:ADJ } tag eng_adverb:horrifyingly{ MODIF_TYPE:ADJ } tag eng_adverb:indescribably{ MODIF_TYPE:ADJ } tag eng_adverb:intolerably{ MODIF_TYPE:ADJ } tag eng_adverb:laughably{ MODIF_TYPE:ADJ } tag eng_adverb:predominantly { MODIF_TYPE:ADJ } tag eng_adverb:unalterably{ MODIF_TYPE:ADJ } tag eng_adverb:undisputedly{ MODIF_TYPE:ADJ } tag eng_adverb:unpardonably{ MODIF_TYPE:ADJ } tag eng_adverb:unreasonably{ MODIF_TYPE:ADJ } tag eng_adverb:unusually{ MODIF_TYPE:ADJ } tag eng_adverb:usually{ MODIF_TYPE:ADJ } tag eng_adverb:hugely{ MODIF_TYPE:ADJ } tag eng_adverb:infernally{ MODIF_TYPE:ADJ } tag eng_adverb:notoriously{ MODIF_TYPE:ADJ } tag eng_adverb:fabulously{ MODIF_TYPE:ADJ } tag eng_adverb:incomparably{ MODIF_TYPE:ADJ } tag eng_adverb:inherently{ MODIF_TYPE:ADJ } tag eng_adverb:marginally{ MODIF_TYPE:ADJ } tag eng_adverb:moderately { MODIF_TYPE:ADJ } tag eng_adverb:relatively{ MODIF_TYPE:ADJ } tag eng_adverb:ridiculously { MODIF_TYPE:ADJ } tag eng_adverb:unacceptably{ MODIF_TYPE:ADJ } tag eng_adverb:unarguably{ MODIF_TYPE:ADJ } tag eng_adverb:undeniably{ MODIF_TYPE:ADJ } tag eng_adverb:unimaginably{ MODIF_TYPE:ADJ } tag eng_adverb:very{ MODIF_TYPE:ADJ } tag eng_adverb:way{ MODIF_TYPE:ADJ } tag eng_adverb:real{ MODIF_TYPE:ADJ } tag eng_adverb:quite{ MODIF_TYPE:ADJ } tag eng_adverb:amazingly{ MODIF_TYPE:ADJ } tag eng_adverb:strangely{ MODIF_TYPE:ADJ } tag eng_adverb:incredibly{ MODIF_TYPE:ADJ } tag eng_adverb:rather{ MODIF_TYPE:ADJ } tag eng_adverb:particularly{ MODIF_TYPE:ADJ } tag eng_adverb:notably{ MODIF_TYPE:ADJ } tag eng_adverb:almost nearly{ MODIF_TYPE:ADJ } tag eng_adverb:entirely{ MODIF_TYPE:ADJ } tag eng_adverb:reasonably{ MODIF_TYPE:ADJ } tag eng_adverb:highly{ MODIF_TYPE:ADJ } tag eng_adverb:fairly{ MODIF_TYPE:ADJ } tag eng_adverb:totally{ MODIF_TYPE:ADJ } // The car was totally destroyed in the crash tag eng_adverb:completely{ MODIF_TYPE:ADJ } tag eng_adverb:terribly{ MODIF_TYPE:ADJ } tag eng_adverb:absolutely{ MODIF_TYPE:ADJ } tag eng_adverb:altogether{ MODIF_TYPE:ADJ } tag eng_adverb:equally{ MODIF_TYPE:ADJ } tag eng_adverb:really{ MODIF_TYPE:ADJ } tag eng_adverb:surprisingly{ MODIF_TYPE:ADJ } tag eng_adverb:especially{ MODIF_TYPE:ADJ } tag eng_adverb:virtually{ MODIF_TYPE:ADJ } tag eng_adverb:wholly{ MODIF_TYPE:ADJ } // Bismuthides are not even wholly ionic; tag eng_adverb:fully{ MODIF_TYPE:ADJ } tag eng_adverb:critically{ MODIF_TYPE:ADJ } tag eng_adverb:greatly{ MODIF_TYPE:ADJ } tag eng_adverb:grossly{ MODIF_TYPE:ADJ } tag eng_adverb:duly{ MODIF_TYPE:ADJ } tag eng_adverb:unduly{ MODIF_TYPE:ADJ } tag eng_adverb:seemingly{ MODIF_TYPE:ADJ } tag eng_adverb:utterly{ MODIF_TYPE:ADJ } tag eng_adverb:barely{ MODIF_TYPE:ADJ } tag eng_adverb:scarcely{ MODIF_TYPE:ADJ } tag eng_adverb:hardly{ MODIF_TYPE:ADJ } tag eng_adverb:merely{ MODIF_TYPE:ADJ } tag eng_adverb:truly{ MODIF_TYPE:ADJ } tag eng_adverb:practically{ MODIF_TYPE:ADJ } tag eng_adverb:partly{ MODIF_TYPE:ADJ } tag eng_adverb:largely{ MODIF_TYPE:ADJ } tag eng_adverb:mostly{ MODIF_TYPE:ADJ } tag eng_adverb:chiefly{ MODIF_TYPE:ADJ } tag eng_adverb:purely{ MODIF_TYPE:ADJ } tag eng_adverb:solely{ MODIF_TYPE:ADJ } tag eng_adverb:academically{ MODIF_TYPE:ADJ } tag eng_adverb:actuarially{ MODIF_TYPE:ADJ } tag eng_adverb:administratively{ MODIF_TYPE:ADJ } tag eng_adverb:aesthetically{ MODIF_TYPE:ADJ } tag eng_adverb:agriculturally{ MODIF_TYPE:ADJ } tag eng_adverb:algebraically{ MODIF_TYPE:ADJ } tag eng_adverb:allegorically{ MODIF_TYPE:ADJ } tag eng_adverb:anatomically{ MODIF_TYPE:ADJ } tag eng_adverb:archeologically{ MODIF_TYPE:ADJ } tag eng_adverb:architecturally{ MODIF_TYPE:ADJ } tag eng_adverb:arithmetically{ MODIF_TYPE:ADJ } tag eng_adverb:artistically{ MODIF_TYPE:ADJ } tag eng_adverb:assumedly{ MODIF_TYPE:ADJ } tag eng_adverb:astronomically{ MODIF_TYPE:ADJ } tag eng_adverb:athletically{ MODIF_TYPE:ADJ } tag eng_adverb:atypically{ MODIF_TYPE:ADJ } tag eng_adverb:behaviorally{ MODIF_TYPE:ADJ } tag eng_adverb:biblically{ MODIF_TYPE:ADJ } tag eng_adverb:biochemically{ MODIF_TYPE:ADJ } tag eng_adverb:biologically{ MODIF_TYPE:ADJ } tag eng_adverb:biotically{ MODIF_TYPE:ADJ } tag eng_adverb:bipedally{ MODIF_TYPE:ADJ } tag eng_adverb:carnally{ MODIF_TYPE:ADJ } tag eng_adverb:chemically{ MODIF_TYPE:ADJ } tag eng_adverb:clandestinely{ MODIF_TYPE:ADJ } tag eng_adverb:climatically{ MODIF_TYPE:ADJ } tag eng_adverb:cognitively{ MODIF_TYPE:ADJ } tag eng_adverb:collegiately{ MODIF_TYPE:ADJ } tag eng_adverb:colonially{ MODIF_TYPE:ADJ } tag eng_adverb:computationally{ MODIF_TYPE:ADJ } tag eng_adverb:conceptually{ MODIF_TYPE:ADJ } tag eng_adverb:contractually{ MODIF_TYPE:ADJ } tag eng_adverb:cryogenically{ MODIF_TYPE:ADJ } tag eng_adverb:cryptographically{ MODIF_TYPE:ADJ } tag eng_adverb:ecclesiastically{ MODIF_TYPE:ADJ } tag eng_adverb:ecologically{ MODIF_TYPE:ADJ } tag eng_adverb:economically{ MODIF_TYPE:ADJ } tag eng_adverb:educationally{ MODIF_TYPE:ADJ } tag eng_adverb:electorally{ MODIF_TYPE:ADJ } tag eng_adverb:empirically{ MODIF_TYPE:ADJ } tag eng_adverb:environmentally{ MODIF_TYPE:ADJ } tag eng_adverb:equidistantly{ MODIF_TYPE:ADJ } tag eng_adverb:ethically{ MODIF_TYPE:ADJ } tag eng_adverb:ethnically{ MODIF_TYPE:ADJ } tag eng_adverb:factually{ MODIF_TYPE:ADJ } tag eng_adverb:federally{ MODIF_TYPE:ADJ } tag eng_adverb:financially{ MODIF_TYPE:ADJ } tag eng_adverb:finitely{ MODIF_TYPE:ADJ } tag eng_adverb:genealogically{ MODIF_TYPE:ADJ } tag eng_adverb:generically{ MODIF_TYPE:ADJ } tag eng_adverb:genetically{ MODIF_TYPE:ADJ } tag eng_adverb:geographically{ MODIF_TYPE:ADJ } tag eng_adverb:geologically{ MODIF_TYPE:ADJ } tag eng_adverb:geometrically{ MODIF_TYPE:ADJ } tag eng_adverb:governmentally{ MODIF_TYPE:ADJ } tag eng_adverb:grammatically{ MODIF_TYPE:ADJ } tag eng_adverb:gynaecologically{ MODIF_TYPE:ADJ } tag eng_adverb:harmonically{ MODIF_TYPE:ADJ } tag eng_adverb:heretofore{ MODIF_TYPE:ADJ } tag eng_adverb:histochemically{ MODIF_TYPE:ADJ } tag eng_adverb:historically{ MODIF_TYPE:ADJ } tag eng_adverb:hydraulically{ MODIF_TYPE:ADJ } tag eng_adverb:immunophenotypically{ MODIF_TYPE:ADJ } tag eng_adverb:infinitesimally{ MODIF_TYPE:ADJ } tag eng_adverb:institutionally{ MODIF_TYPE:ADJ } tag eng_adverb:journalistically{ MODIF_TYPE:ADJ } tag eng_adverb:judicially{ MODIF_TYPE:ADJ } tag eng_adverb:lastingly{ MODIF_TYPE:ADJ } tag eng_adverb:legendarily{ MODIF_TYPE:ADJ } tag eng_adverb:linguistically{ MODIF_TYPE:ADJ } tag eng_adverb:logically{ MODIF_TYPE:ADJ } tag eng_adverb:logistically{ MODIF_TYPE:ADJ } tag eng_adverb:maddeningly{ MODIF_TYPE:ADJ } tag eng_adverb:materially{ MODIF_TYPE:ADJ } tag eng_adverb:mathematically{ MODIF_TYPE:ADJ } tag eng_adverb:medically{ MODIF_TYPE:ADJ } tag eng_adverb:medicinally{ MODIF_TYPE:ADJ } tag eng_adverb:metaphysically{ MODIF_TYPE:ADJ } tag eng_adverb:meteorologically{ MODIF_TYPE:ADJ } tag eng_adverb:methodologically{ MODIF_TYPE:ADJ } tag eng_adverb:morally{ MODIF_TYPE:ADJ } tag eng_adverb:morbidly{ MODIF_TYPE:ADJ } tag eng_adverb:mystically{ MODIF_TYPE:ADJ } tag eng_adverb:nonspecifically{ MODIF_TYPE:ADJ } tag eng_adverb:nutritionally{ MODIF_TYPE:ADJ } tag eng_adverb:opportunistically{ MODIF_TYPE:ADJ } tag eng_adverb:optically{ MODIF_TYPE:ADJ } tag eng_adverb:organizationally{ MODIF_TYPE:ADJ } tag eng_adverb:perceptually{ MODIF_TYPE:ADJ } tag eng_adverb:perpendicularly{ MODIF_TYPE:ADJ } tag eng_adverb:pharmacologically{ MODIF_TYPE:ADJ } tag eng_adverb:phenomenologically{ MODIF_TYPE:ADJ } tag eng_adverb:philosophically{ MODIF_TYPE:ADJ } tag eng_adverb:phonetically{ MODIF_TYPE:ADJ } tag eng_adverb:phonologically{ MODIF_TYPE:ADJ } tag eng_adverb:photographically{ MODIF_TYPE:ADJ } tag eng_adverb:pictorially{ MODIF_TYPE:ADJ } tag eng_adverb:pinnately{ MODIF_TYPE:ADJ } tag eng_adverb:politically{ MODIF_TYPE:ADJ } tag eng_adverb:pragmatically{ MODIF_TYPE:ADJ } tag eng_adverb:princely{ MODIF_TYPE:ADJ } tag eng_adverb:probabilistically{ MODIF_TYPE:ADJ } tag eng_adverb:prognostically{ MODIF_TYPE:ADJ } tag eng_adverb:pseudonymously{ MODIF_TYPE:ADJ } tag eng_adverb:psychically{ MODIF_TYPE:ADJ } tag eng_adverb:psychologically{ MODIF_TYPE:ADJ } tag eng_adverb:publically{ MODIF_TYPE:ADJ } tag eng_adverb:putatively{ MODIF_TYPE:ADJ } tag eng_adverb:quadratically{ MODIF_TYPE:ADJ } tag eng_adverb:questionably{ MODIF_TYPE:ADJ } tag eng_adverb:racially{ MODIF_TYPE:ADJ } tag eng_adverb:recreationally{ MODIF_TYPE:ADJ } tag eng_adverb:recursively{ MODIF_TYPE:ADJ } tag eng_adverb:ritually{ MODIF_TYPE:ADJ } tag eng_adverb:scientifically{ MODIF_TYPE:ADJ } tag eng_adverb:semantically{ MODIF_TYPE:ADJ } tag eng_adverb:sexually{ MODIF_TYPE:ADJ } tag eng_adverb:socially{ MODIF_TYPE:ADJ } tag eng_adverb:societally{ MODIF_TYPE:ADJ } tag eng_adverb:sociologically{ MODIF_TYPE:ADJ } tag eng_adverb:sonically{ MODIF_TYPE:ADJ } tag eng_adverb:spatially{ MODIF_TYPE:ADJ } tag eng_adverb:spherically{ MODIF_TYPE:ADJ } tag eng_adverb:spirally{ MODIF_TYPE:ADJ } tag eng_adverb:statistically{ MODIF_TYPE:ADJ } tag eng_adverb:statutorily{ MODIF_TYPE:ADJ } tag eng_adverb:steganographically{ MODIF_TYPE:ADJ } tag eng_adverb:stereotypically{ MODIF_TYPE:ADJ } tag eng_adverb:structurally{ MODIF_TYPE:ADJ } tag eng_adverb:stylistically{ MODIF_TYPE:ADJ } tag eng_adverb:supernaturally{ MODIF_TYPE:ADJ } tag eng_adverb:syllabically{ MODIF_TYPE:ADJ } tag eng_adverb:synonymously{ MODIF_TYPE:ADJ } tag eng_adverb:synoptically{ MODIF_TYPE:ADJ } tag eng_adverb:syntactically{ MODIF_TYPE:ADJ } tag eng_adverb:tangentially{ MODIF_TYPE:ADJ } tag eng_adverb:taxonomically{ MODIF_TYPE:ADJ } tag eng_adverb:technologically{ MODIF_TYPE:ADJ } tag eng_adverb:telepathically{ MODIF_TYPE:ADJ } tag eng_adverb:terrestrially{ MODIF_TYPE:ADJ } tag eng_adverb:theologically{ MODIF_TYPE:ADJ } tag eng_adverb:theoretically{ MODIF_TYPE:ADJ } tag eng_adverb:therapeutically{ MODIF_TYPE:ADJ } tag eng_adverb:topographically{ MODIF_TYPE:ADJ } tag eng_adverb:wirelessly{ MODIF_TYPE:ADJ } tag eng_adverb:finely{ MODIF_TYPE:ADJ } tag eng_adverb:specially{ MODIF_TYPE:ADJ } tag eng_adverb:literally{ MODIF_TYPE:ADJ } tag eng_adverb:heavily{ MODIF_TYPE:ADJ } tag eng_adverb:alternately{ MODIF_TYPE:ADJ } tag eng_adverb:severely{ MODIF_TYPE:ADJ } tag eng_adverb:dearly{ MODIF_TYPE:ADJ } tag eng_adverb:voluntarily{ MODIF_TYPE:ADJ } tag eng_adverb:dramatically{ MODIF_TYPE:ADJ } tag eng_adverb:flatly{ MODIF_TYPE:ADJ } tag eng_adverb:purposely{ MODIF_TYPE:ADJ } tag eng_adverb:jointly{ MODIF_TYPE:ADJ } tag eng_adverb:narrowly{ MODIF_TYPE:ADJ } tag eng_adverb:universally{ MODIF_TYPE:ADJ } tag eng_adverb:thickly{ MODIF_TYPE:ADJ } tag eng_adverb:widely{ MODIF_TYPE:ADJ } tag eng_adverb:roughly{ MODIF_TYPE:ADJ } tag eng_adverb:approximately{ MODIF_TYPE:ADJ } tag eng_adverb:gradually{ MODIF_TYPE:ADJ } tag eng_adverb:sadly{ MODIF_TYPE:ADJ } tag eng_adverb:broadly{ MODIF_TYPE:ADJ } tag eng_adverb:clearly{ MODIF_TYPE:ADJ } tag eng_adverb:annually{ MODIF_TYPE:ADJ } tag eng_adverb:characteristically{ MODIF_TYPE:ADJ } tag eng_adverb:comparatively{ MODIF_TYPE:ADJ } tag eng_adverb:confidentially{ MODIF_TYPE:ADJ } tag eng_adverb:currently{ MODIF_TYPE:ADJ } tag eng_adverb:fundamentally{ MODIF_TYPE:ADJ } tag eng_adverb:hypothetically{ MODIF_TYPE:ADJ } tag eng_adverb:ironically{ MODIF_TYPE:ADJ } tag eng_adverb:justifiably{ MODIF_TYPE:ADJ } tag eng_adverb:momentarily{ MODIF_TYPE:ADJ } tag eng_adverb:mercifully{ MODIF_TYPE:ADJ } tag eng_adverb:nominally{ MODIF_TYPE:ADJ } tag eng_adverb:ominously{ MODIF_TYPE:ADJ } tag eng_adverb:periodically{ MODIF_TYPE:ADJ } tag eng_adverb:precisely{ MODIF_TYPE:ADJ } tag eng_adverb:realistically{ MODIF_TYPE:ADJ } tag eng_adverb:simultaneously{ MODIF_TYPE:ADJ } tag eng_adverb:subsequently{ MODIF_TYPE:ADJ } tag eng_adverb:superficially{ MODIF_TYPE:ADJ } tag eng_adverb:thankfully{ MODIF_TYPE:ADJ } tag eng_adverb:unofficially{ MODIF_TYPE:ADJ } tag eng_adverb:effectively{ MODIF_TYPE:ADJ } tag eng_adverb:traditionally{ MODIF_TYPE:ADJ } tag eng_adverb:briefly{ MODIF_TYPE:ADJ } tag eng_adverb:eventually{ MODIF_TYPE:ADJ } tag eng_adverb:ultimately{ MODIF_TYPE:ADJ } tag eng_adverb:mysteriously{ MODIF_TYPE:ADJ } tag eng_adverb:naturally{ MODIF_TYPE:ADJ } tag eng_adverb:oddly{ MODIF_TYPE:ADJ } tag eng_adverb:plainly{ MODIF_TYPE:ADJ } tag eng_adverb:truthfully{ MODIF_TYPE:ADJ } tag eng_adverb:appropriately{ MODIF_TYPE:ADJ } tag eng_adverb:abjectly{ MODIF_TYPE:ADJ } tag eng_adverb:ably{ MODIF_TYPE:ADJ } tag eng_adverb:abnormally{ MODIF_TYPE:ADJ } tag eng_adverb:abortively{ MODIF_TYPE:ADJ } tag eng_adverb:abruptly{ MODIF_TYPE:ADJ } tag eng_adverb:absently{ MODIF_TYPE:ADJ } tag eng_adverb:absent-mindedly{ MODIF_TYPE:ADJ } tag eng_adverb:abusively{ MODIF_TYPE:ADJ } tag eng_adverb:abysmally{ MODIF_TYPE:ADJ } tag eng_adverb:accidentally{ MODIF_TYPE:ADJ } tag eng_adverb:accordingly{ MODIF_TYPE:ADJ } tag eng_adverb:accurately{ MODIF_TYPE:ADJ } tag eng_adverb:accusingly{ MODIF_TYPE:ADJ } tag eng_adverb:actively{ MODIF_TYPE:ADJ } tag eng_adverb:acutely{ MODIF_TYPE:ADJ } tag eng_adverb:adamantly{ MODIF_TYPE:ADJ } tag eng_adverb:adequately{ MODIF_TYPE:ADJ } tag eng_adverb:admirably{ MODIF_TYPE:ADJ } tag eng_adverb:admiringly{ MODIF_TYPE:ADJ } tag eng_adverb:adoringly{ MODIF_TYPE:ADJ } tag eng_adverb:adroitly{ MODIF_TYPE:ADJ } tag eng_adverb:adversely{ MODIF_TYPE:ADJ } tag eng_adverb:advisedly{ MODIF_TYPE:ADJ } tag eng_adverb:affably{ MODIF_TYPE:ADJ } tag eng_adverb:affectionately{ MODIF_TYPE:ADJ } tag eng_adverb:afield{ MODIF_TYPE:ADJ } tag eng_adverb:aggressively{ MODIF_TYPE:ADJ } tag eng_adverb:agreeably{ MODIF_TYPE:ADJ } tag eng_adverb:aimlessly{ MODIF_TYPE:ADJ } tag eng_adverb:airily{ MODIF_TYPE:ADJ } tag eng_adverb:alarmingly{ MODIF_TYPE:ADJ } tag eng_adverb:allegretto{ MODIF_TYPE:ADJ } tag eng_adverb:alphabetically{ MODIF_TYPE:ADJ } tag eng_adverb:ambiguously{ MODIF_TYPE:ADJ } tag eng_adverb:ambitiously{ MODIF_TYPE:ADJ } tag eng_adverb:amiably{ MODIF_TYPE:ADJ } tag eng_adverb:amicably{ MODIF_TYPE:ADJ } tag eng_adverb:amidships{ MODIF_TYPE:ADJ } tag eng_adverb:amorously{ MODIF_TYPE:ADJ } tag eng_adverb:amply{ MODIF_TYPE:ADJ } tag eng_adverb:amusingly{ MODIF_TYPE:ADJ } tag eng_adverb:analogously{ MODIF_TYPE:ADJ } tag eng_adverb:analytically{ MODIF_TYPE:ADJ } tag eng_adverb:anciently{ MODIF_TYPE:ADJ } tag eng_adverb:andante{ MODIF_TYPE:ADJ } tag eng_adverb:angelically{ MODIF_TYPE:ADJ } tag eng_adverb:angrily{ MODIF_TYPE:ADJ } tag eng_adverb:anon{ MODIF_TYPE:ADJ } tag eng_adverb:anonymously{ MODIF_TYPE:ADJ } tag eng_adverb:anticlockwise{ MODIF_TYPE:ADJ } tag eng_adverb:anxiously{ MODIF_TYPE:ADJ } tag eng_adverb:anyplace{ MODIF_TYPE:ADJ } tag eng_adverb:apace{ MODIF_TYPE:ADJ } tag eng_adverb:apathetically{ MODIF_TYPE:ADJ } tag eng_adverb:apologetically{ MODIF_TYPE:ADJ } tag eng_adverb:appreciably{ MODIF_TYPE:ADJ } tag eng_adverb:appreciatively{ MODIF_TYPE:ADJ } tag eng_adverb:approvingly{ MODIF_TYPE:ADJ } tag eng_adverb:aptly{ MODIF_TYPE:ADJ } tag eng_adverb:arbitrarily{ MODIF_TYPE:ADJ } tag eng_adverb:archly{ MODIF_TYPE:ADJ } tag eng_adverb:ardently{ MODIF_TYPE:ADJ } tag eng_adverb:arduously{ MODIF_TYPE:ADJ } tag eng_adverb:arrogantly{ MODIF_TYPE:ADJ } tag eng_adverb:artfully{ MODIF_TYPE:ADJ } tag eng_adverb:articulately{ MODIF_TYPE:ADJ } tag eng_adverb:artificially{ MODIF_TYPE:ADJ } tag eng_adverb:asexually{ MODIF_TYPE:ADJ } tag eng_adverb:assertively{ MODIF_TYPE:ADJ } tag eng_adverb:assiduously{ MODIF_TYPE:ADJ } tag eng_adverb:astutely{ MODIF_TYPE:ADJ } tag eng_adverb:asymmetrically{ MODIF_TYPE:ADJ } tag eng_adverb:asymptotically{ MODIF_TYPE:ADJ } tag eng_adverb:atrociously{ MODIF_TYPE:ADJ } tag eng_adverb:attentively{ MODIF_TYPE:ADJ } tag eng_adverb:attractively{ MODIF_TYPE:ADJ } tag eng_adverb:attributively{ MODIF_TYPE:ADJ } tag eng_adverb:audaciously{ MODIF_TYPE:ADJ } tag eng_adverb:audibly{ MODIF_TYPE:ADJ } tag eng_adverb:auspiciously{ MODIF_TYPE:ADJ } tag eng_adverb:austerely{ MODIF_TYPE:ADJ } tag eng_adverb:authentically{ MODIF_TYPE:ADJ } tag eng_adverb:authoritatively{ MODIF_TYPE:ADJ } tag eng_adverb:autocratically{ MODIF_TYPE:ADJ } tag eng_adverb:automatically{ MODIF_TYPE:ADJ } tag eng_adverb:avariciously{ MODIF_TYPE:ADJ } tag eng_adverb:avidly{ MODIF_TYPE:ADJ } tag eng_adverb:awake{ MODIF_TYPE:ADJ } tag eng_adverb:awesomely{ MODIF_TYPE:ADJ } tag eng_adverb:awkwardly{ MODIF_TYPE:ADJ } tag eng_adverb:backstage{ MODIF_TYPE:ADJ } tag eng_adverb:badly{ MODIF_TYPE:ADJ } tag eng_adverb:baldly{ MODIF_TYPE:ADJ } tag eng_adverb:barbarously{ MODIF_TYPE:ADJ } tag eng_adverb:bareback{ MODIF_TYPE:ADJ } tag eng_adverb:barebacked{ MODIF_TYPE:ADJ } tag eng_adverb:barefacedly{ MODIF_TYPE:ADJ } tag eng_adverb:barefooted{ MODIF_TYPE:ADJ } tag eng_adverb:bashfully{ MODIF_TYPE:ADJ } tag eng_adverb:beautifully{ MODIF_TYPE:ADJ } tag eng_adverb:becomingly{ MODIF_TYPE:ADJ } tag eng_adverb:beforehand{ MODIF_TYPE:ADJ } tag eng_adverb:begrudgingly{ MODIF_TYPE:ADJ } tag eng_adverb:belatedly{ MODIF_TYPE:ADJ } tag eng_adverb:belligerently{ MODIF_TYPE:ADJ } tag eng_adverb:beneficially{ MODIF_TYPE:ADJ } tag eng_adverb:benevolently{ MODIF_TYPE:ADJ } tag eng_adverb:benignly{ MODIF_TYPE:ADJ } tag eng_adverb:biennially{ MODIF_TYPE:ADJ } tag eng_adverb:bilaterally{ MODIF_TYPE:ADJ } tag eng_adverb:bitterly{ MODIF_TYPE:ADJ } tag eng_adverb:blandly{ MODIF_TYPE:ADJ } tag eng_adverb:blankly{ MODIF_TYPE:ADJ } tag eng_adverb:blasphemously{ MODIF_TYPE:ADJ } tag eng_adverb:blatantly{ MODIF_TYPE:ADJ } tag eng_adverb:bleakly{ MODIF_TYPE:ADJ } tag eng_adverb:blindly{ MODIF_TYPE:ADJ } tag eng_adverb:blissfully{ MODIF_TYPE:ADJ } tag eng_adverb:blithely{ MODIF_TYPE:ADJ } tag eng_adverb:bloodily{ MODIF_TYPE:ADJ } tag eng_adverb:bluntly{ MODIF_TYPE:ADJ } tag eng_adverb:boastfully{ MODIF_TYPE:ADJ } tag eng_adverb:boisterously{ MODIF_TYPE:ADJ } tag eng_adverb:boldly{ MODIF_TYPE:ADJ } tag eng_adverb:bombastically{ MODIF_TYPE:ADJ } tag eng_adverb:boundlessly{ MODIF_TYPE:ADJ } tag eng_adverb:boyishly{ MODIF_TYPE:ADJ } tag eng_adverb:bravely{ MODIF_TYPE:ADJ } tag eng_adverb:brazenly{ MODIF_TYPE:ADJ } tag eng_adverb:breathlessly{ MODIF_TYPE:ADJ } tag eng_adverb:breezily{ MODIF_TYPE:ADJ } tag eng_adverb:bright{ MODIF_TYPE:ADJ } tag eng_adverb:brightly{ MODIF_TYPE:ADJ } tag eng_adverb:brilliantly{ MODIF_TYPE:ADJ } tag eng_adverb:briskly{ MODIF_TYPE:ADJ } tag eng_adverb:brusquely{ MODIF_TYPE:ADJ } tag eng_adverb:brutally{ MODIF_TYPE:ADJ } tag eng_adverb:buoyantly{ MODIF_TYPE:ADJ } tag eng_adverb:busily{ MODIF_TYPE:ADJ } tag eng_adverb:callously{ MODIF_TYPE:ADJ } tag eng_adverb:calmly{ MODIF_TYPE:ADJ } tag eng_adverb:candidly{ MODIF_TYPE:ADJ } tag eng_adverb:cantankerously{ MODIF_TYPE:ADJ } tag eng_adverb:capably{ MODIF_TYPE:ADJ } tag eng_adverb:capriciously{ MODIF_TYPE:ADJ } tag eng_adverb:carefully{ MODIF_TYPE:ADJ } tag eng_adverb:carelessly{ MODIF_TYPE:ADJ } tag eng_adverb:casually{ MODIF_TYPE:ADJ } tag eng_adverb:categorically{ MODIF_TYPE:ADJ } tag eng_adverb:causally{ MODIF_TYPE:ADJ } tag eng_adverb:caustically{ MODIF_TYPE:ADJ } tag eng_adverb:cautiously{ MODIF_TYPE:ADJ } tag eng_adverb:cavalierly{ MODIF_TYPE:ADJ } tag eng_adverb:ceaselessly{ MODIF_TYPE:ADJ } tag eng_adverb:centrally{ MODIF_TYPE:ADJ } tag eng_adverb:ceremonially{ MODIF_TYPE:ADJ } tag eng_adverb:ceremoniously{ MODIF_TYPE:ADJ } tag eng_adverb:chaotically{ MODIF_TYPE:ADJ } tag eng_adverb:charitably{ MODIF_TYPE:ADJ } tag eng_adverb:charmingly{ MODIF_TYPE:ADJ } tag eng_adverb:chattily{ MODIF_TYPE:ADJ } tag eng_adverb:cheaply{ MODIF_TYPE:ADJ } tag eng_adverb:cheekily{ MODIF_TYPE:ADJ } tag eng_adverb:cheerfully{ MODIF_TYPE:ADJ } tag eng_adverb:cheerily{ MODIF_TYPE:ADJ } tag eng_adverb:childishly{ MODIF_TYPE:ADJ } tag eng_adverb:chivalrously{ MODIF_TYPE:ADJ } tag eng_adverb:chronologically{ MODIF_TYPE:ADJ } tag eng_adverb:classically{ MODIF_TYPE:ADJ } tag eng_adverb:clean{ MODIF_TYPE:ADJ } tag eng_adverb:cleanly{ MODIF_TYPE:ADJ } tag eng_adverb:cleverly{ MODIF_TYPE:ADJ } tag eng_adverb:clinically{ MODIF_TYPE:ADJ } tag eng_adverb:clockwise{ MODIF_TYPE:ADJ } tag eng_adverb:closely{ MODIF_TYPE:ADJ } tag eng_adverb:clumsily{ MODIF_TYPE:ADJ } tag eng_adverb:coarsely{ MODIF_TYPE:ADJ } tag eng_adverb:coherently{ MODIF_TYPE:ADJ } tag eng_adverb:cohesively{ MODIF_TYPE:ADJ } tag eng_adverb:coldly{ MODIF_TYPE:ADJ } tag eng_adverb:collectively{ MODIF_TYPE:ADJ } tag eng_adverb:colloquially{ MODIF_TYPE:ADJ } tag eng_adverb:colorfully{ MODIF_TYPE:ADJ } tag eng_adverb:combatively{ MODIF_TYPE:ADJ } tag eng_adverb:comfortably{ MODIF_TYPE:ADJ } tag eng_adverb:comfortingly{ MODIF_TYPE:ADJ } tag eng_adverb:comically{ MODIF_TYPE:ADJ } tag eng_adverb:commercially{ MODIF_TYPE:ADJ } tag eng_adverb:communally{ MODIF_TYPE:ADJ } tag eng_adverb:comparably{ MODIF_TYPE:ADJ } tag eng_adverb:compassionately{ MODIF_TYPE:ADJ } tag eng_adverb:competently{ MODIF_TYPE:ADJ } tag eng_adverb:competitively{ MODIF_TYPE:ADJ } tag eng_adverb:complacently{ MODIF_TYPE:ADJ } tag eng_adverb:comprehensively{ MODIF_TYPE:ADJ } tag eng_adverb:compulsively{ MODIF_TYPE:ADJ } tag eng_adverb:conceitedly{ MODIF_TYPE:ADJ } tag eng_adverb:concernedly{ MODIF_TYPE:ADJ } tag eng_adverb:concisely{ MODIF_TYPE:ADJ } tag eng_adverb:conclusively{ MODIF_TYPE:ADJ } tag eng_adverb:concretely{ MODIF_TYPE:ADJ } tag eng_adverb:concurrently{ MODIF_TYPE:ADJ } tag eng_adverb:condescendingly{ MODIF_TYPE:ADJ } tag eng_adverb:conditionally{ MODIF_TYPE:ADJ } tag eng_adverb:confidently{ MODIF_TYPE:ADJ } tag eng_adverb:confidingly{ MODIF_TYPE:ADJ } tag eng_adverb:confusingly{ MODIF_TYPE:ADJ } tag eng_adverb:congenially{ MODIF_TYPE:ADJ } tag eng_adverb:conjugally{ MODIF_TYPE:ADJ } tag eng_adverb:conscientiously{ MODIF_TYPE:ADJ } tag eng_adverb:consciously{ MODIF_TYPE:ADJ } tag eng_adverb:consecutively{ MODIF_TYPE:ADJ } tag eng_adverb:conservatively{ MODIF_TYPE:ADJ } tag eng_adverb:considerably{ MODIF_TYPE:ADJ } tag eng_adverb:considerately{ MODIF_TYPE:ADJ } tag eng_adverb:consistently{ MODIF_TYPE:ADJ } tag eng_adverb:conspicuously{ MODIF_TYPE:ADJ } tag eng_adverb:constantly{ MODIF_TYPE:ADJ } tag eng_adverb:constitutionally{ MODIF_TYPE:ADJ } tag eng_adverb:constructively{ MODIF_TYPE:ADJ } tag eng_adverb:contemporaneously{ MODIF_TYPE:ADJ } tag eng_adverb:contemporarily{ MODIF_TYPE:ADJ } tag eng_adverb:contemptuously{ MODIF_TYPE:ADJ } tag eng_adverb:contentedly{ MODIF_TYPE:ADJ } tag eng_adverb:continually{ MODIF_TYPE:ADJ } tag eng_adverb:continuously{ MODIF_TYPE:ADJ } tag eng_adverb:contrariwise{ MODIF_TYPE:ADJ } tag eng_adverb:contritely{ MODIF_TYPE:ADJ } tag eng_adverb:controversially{ MODIF_TYPE:ADJ } tag eng_adverb:conventionally{ MODIF_TYPE:ADJ } tag eng_adverb:conversationally{ MODIF_TYPE:ADJ } tag eng_adverb:convincingly{ MODIF_TYPE:ADJ } tag eng_adverb:convulsively{ MODIF_TYPE:ADJ } tag eng_adverb:coolly{ MODIF_TYPE:ADJ } tag eng_adverb:cooperatively{ MODIF_TYPE:ADJ } tag eng_adverb:co-operatively{ MODIF_TYPE:ADJ } tag eng_adverb:copiously{ MODIF_TYPE:ADJ } tag eng_adverb:cordially{ MODIF_TYPE:ADJ } tag eng_adverb:correctly{ MODIF_TYPE:ADJ } tag eng_adverb:correspondingly{ MODIF_TYPE:ADJ } tag eng_adverb:corruptly{ MODIF_TYPE:ADJ } tag eng_adverb:courageously{ MODIF_TYPE:ADJ } tag eng_adverb:courteously{ MODIF_TYPE:ADJ } tag eng_adverb:covertly{ MODIF_TYPE:ADJ } tag eng_adverb:coyly{ MODIF_TYPE:ADJ } tag eng_adverb:craftily{ MODIF_TYPE:ADJ } tag eng_adverb:crassly{ MODIF_TYPE:ADJ } tag eng_adverb:crazily{ MODIF_TYPE:ADJ } tag eng_adverb:creatively{ MODIF_TYPE:ADJ } tag eng_adverb:credibly{ MODIF_TYPE:ADJ } tag eng_adverb:creditably{ MODIF_TYPE:ADJ } tag eng_adverb:credulously{ MODIF_TYPE:ADJ } tag eng_adverb:criminally{ MODIF_TYPE:ADJ } tag eng_adverb:crisply{ MODIF_TYPE:ADJ } tag eng_adverb:crookedly{ MODIF_TYPE:ADJ } tag eng_adverb:cross-legged{ MODIF_TYPE:ADJ } tag eng_adverb:crossly{ MODIF_TYPE:ADJ } tag eng_adverb:crudely{ MODIF_TYPE:ADJ } tag eng_adverb:cruelly{ MODIF_TYPE:ADJ } tag eng_adverb:cryptically{ MODIF_TYPE:ADJ } tag eng_adverb:culturally{ MODIF_TYPE:ADJ } tag eng_adverb:cumulatively{ MODIF_TYPE:ADJ } tag eng_adverb:cunningly{ MODIF_TYPE:ADJ } tag eng_adverb:cursorily{ MODIF_TYPE:ADJ } tag eng_adverb:curtly{ MODIF_TYPE:ADJ } tag eng_adverb:cynically{ MODIF_TYPE:ADJ } tag eng_adverb:daintily{ MODIF_TYPE:ADJ } tag eng_adverb:damnably{ MODIF_TYPE:ADJ } tag eng_adverb:dangerously{ MODIF_TYPE:ADJ } tag eng_adverb:daringly{ MODIF_TYPE:ADJ } tag eng_adverb:darkly{ MODIF_TYPE:ADJ } tag eng_adverb:dashingly{ MODIF_TYPE:ADJ } tag eng_adverb:deceitfully{ MODIF_TYPE:ADJ } tag eng_adverb:deceivingly{ MODIF_TYPE:ADJ } tag eng_adverb:decently{ MODIF_TYPE:ADJ } tag eng_adverb:deceptively{ MODIF_TYPE:ADJ } tag eng_adverb:decisively{ MODIF_TYPE:ADJ } tag eng_adverb:decorously{ MODIF_TYPE:ADJ } tag eng_adverb:deductively{ MODIF_TYPE:ADJ } tag eng_adverb:deeply{ MODIF_TYPE:ADJ } tag eng_adverb:defectively{ MODIF_TYPE:ADJ } tag eng_adverb:defensively{ MODIF_TYPE:ADJ } tag eng_adverb:deferentially{ MODIF_TYPE:ADJ } tag eng_adverb:defiantly{ MODIF_TYPE:ADJ } tag eng_adverb:deftly{ MODIF_TYPE:ADJ } tag eng_adverb:dejectedly{ MODIF_TYPE:ADJ } tag eng_adverb:deliberately{ MODIF_TYPE:ADJ } tag eng_adverb:delicately{ MODIF_TYPE:ADJ } tag eng_adverb:delightedly{ MODIF_TYPE:ADJ } tag eng_adverb:delightfully{ MODIF_TYPE:ADJ } tag eng_adverb:deliriously{ MODIF_TYPE:ADJ } tag eng_adverb:democratically{ MODIF_TYPE:ADJ } tag eng_adverb:demoniacally{ MODIF_TYPE:ADJ } tag eng_adverb:demonstratively{ MODIF_TYPE:ADJ } tag eng_adverb:demurely{ MODIF_TYPE:ADJ } tag eng_adverb:densely{ MODIF_TYPE:ADJ } tag eng_adverb:dentally{ MODIF_TYPE:ADJ } tag eng_adverb:dependably{ MODIF_TYPE:ADJ } tag eng_adverb:deplorably{ MODIF_TYPE:ADJ } tag eng_adverb:derisively{ MODIF_TYPE:ADJ } tag eng_adverb:descriptively{ MODIF_TYPE:ADJ } tag eng_adverb:deservedly{ MODIF_TYPE:ADJ } tag eng_adverb:despairingly{ MODIF_TYPE:ADJ } tag eng_adverb:desperately{ MODIF_TYPE:ADJ } tag eng_adverb:despicably{ MODIF_TYPE:ADJ } tag eng_adverb:despondently{ MODIF_TYPE:ADJ } tag eng_adverb:destructively{ MODIF_TYPE:ADJ } tag eng_adverb:detestably{ MODIF_TYPE:ADJ } tag eng_adverb:detrimentally{ MODIF_TYPE:ADJ } tag eng_adverb:devilishly{ MODIF_TYPE:ADJ } tag eng_adverb:deviously{ MODIF_TYPE:ADJ } tag eng_adverb:devotedly{ MODIF_TYPE:ADJ } tag eng_adverb:devoutly{ MODIF_TYPE:ADJ } tag eng_adverb:dexterously{ MODIF_TYPE:ADJ } tag eng_adverb:diabolically{ MODIF_TYPE:ADJ } tag eng_adverb:diagonally{ MODIF_TYPE:ADJ } tag eng_adverb:diametrically{ MODIF_TYPE:ADJ } tag eng_adverb:didactically{ MODIF_TYPE:ADJ } tag eng_adverb:differentially{ MODIF_TYPE:ADJ } tag eng_adverb:diffidently{ MODIF_TYPE:ADJ } tag eng_adverb:diffusely{ MODIF_TYPE:ADJ } tag eng_adverb:digitally{ MODIF_TYPE:ADJ } tag eng_adverb:diligently{ MODIF_TYPE:ADJ } tag eng_adverb:dimly{ MODIF_TYPE:ADJ } tag eng_adverb:diplomatically{ MODIF_TYPE:ADJ } tag eng_adverb:directly{ MODIF_TYPE:ADJ } tag eng_adverb:disagreeably{ MODIF_TYPE:ADJ } tag eng_adverb:disappointedly{ MODIF_TYPE:ADJ } tag eng_adverb:disapprovingly{ MODIF_TYPE:ADJ } tag eng_adverb:disastrously{ MODIF_TYPE:ADJ } tag eng_adverb:disconcertingly{ MODIF_TYPE:ADJ } tag eng_adverb:discourteously{ MODIF_TYPE:ADJ } tag eng_adverb:discreetly{ MODIF_TYPE:ADJ } tag eng_adverb:discretely{ MODIF_TYPE:ADJ } tag eng_adverb:discursively{ MODIF_TYPE:ADJ } tag eng_adverb:disdainfully{ MODIF_TYPE:ADJ } tag eng_adverb:disgracefully{ MODIF_TYPE:ADJ } tag eng_adverb:disgustedly{ MODIF_TYPE:ADJ } tag eng_adverb:disgustingly{ MODIF_TYPE:ADJ } tag eng_adverb:dishonestly{ MODIF_TYPE:ADJ } tag eng_adverb:dishonourably{ MODIF_TYPE:ADJ } tag eng_adverb:disingenuously{ MODIF_TYPE:ADJ } tag eng_adverb:dismally{ MODIF_TYPE:ADJ } tag eng_adverb:disobediently{ MODIF_TYPE:ADJ } tag eng_adverb:disparagingly{ MODIF_TYPE:ADJ } tag eng_adverb:dispassionately{ MODIF_TYPE:ADJ } tag eng_adverb:dispiritedly{ MODIF_TYPE:ADJ } tag eng_adverb:disproportionately{ MODIF_TYPE:ADJ } tag eng_adverb:disrespectfully{ MODIF_TYPE:ADJ } tag eng_adverb:distantly{ MODIF_TYPE:ADJ } tag eng_adverb:distinctively{ MODIF_TYPE:ADJ } tag eng_adverb:distinctly{ MODIF_TYPE:ADJ } tag eng_adverb:distractedly{ MODIF_TYPE:ADJ } tag eng_adverb:distressingly{ MODIF_TYPE:ADJ } tag eng_adverb:distrustfully{ MODIF_TYPE:ADJ } tag eng_adverb:disturbingly{ MODIF_TYPE:ADJ } tag eng_adverb:diversely{ MODIF_TYPE:ADJ } tag eng_adverb:divinely{ MODIF_TYPE:ADJ } tag eng_adverb:dizzily{ MODIF_TYPE:ADJ } tag eng_adverb:doggedly{ MODIF_TYPE:ADJ } tag eng_adverb:dogmatically{ MODIF_TYPE:ADJ } tag eng_adverb:dolefully{ MODIF_TYPE:ADJ } tag eng_adverb:domestically{ MODIF_TYPE:ADJ } tag eng_adverb:doubly{ MODIF_TYPE:ADJ } tag eng_adverb:doubtfully{ MODIF_TYPE:ADJ } tag eng_adverb:dourly{ MODIF_TYPE:ADJ } tag eng_adverb:drably{ MODIF_TYPE:ADJ } tag eng_adverb:drastically{ MODIF_TYPE:ADJ } tag eng_adverb:dreadfully{ MODIF_TYPE:ADJ } tag eng_adverb:dreamily{ MODIF_TYPE:ADJ } tag eng_adverb:drearily{ MODIF_TYPE:ADJ } tag eng_adverb:drily{ MODIF_TYPE:ADJ } tag eng_adverb:drowsily{ MODIF_TYPE:ADJ } tag eng_adverb:drunkenly{ MODIF_TYPE:ADJ } tag eng_adverb:dryly{ MODIF_TYPE:ADJ } tag eng_adverb:dubiously{ MODIF_TYPE:ADJ } tag eng_adverb:dumbly{ MODIF_TYPE:ADJ } tag eng_adverb:dutifully{ MODIF_TYPE:ADJ } tag eng_adverb:dynamically{ MODIF_TYPE:ADJ } tag eng_adverb:eagarly{ MODIF_TYPE:ADJ } tag eng_adverb:eagerly{ MODIF_TYPE:ADJ } tag eng_adverb:earnestly{ MODIF_TYPE:ADJ } tag eng_adverb:easily{ MODIF_TYPE:ADJ } tag eng_adverb:eastwards{ MODIF_TYPE:ADJ } tag eng_adverb:ebulliently{ MODIF_TYPE:ADJ } tag eng_adverb:ecstatically{ MODIF_TYPE:ADJ } tag eng_adverb:edgewise{ MODIF_TYPE:ADJ } tag eng_adverb:eerily{ MODIF_TYPE:ADJ } tag eng_adverb:efficaciously{ MODIF_TYPE:ADJ } tag eng_adverb:efficiently{ MODIF_TYPE:ADJ } tag eng_adverb:effortlessly{ MODIF_TYPE:ADJ } tag eng_adverb:effusively{ MODIF_TYPE:ADJ } tag eng_adverb:egotistically{ MODIF_TYPE:ADJ } tag eng_adverb:elaborately{ MODIF_TYPE:ADJ } tag eng_adverb:electrically{ MODIF_TYPE:ADJ } tag eng_adverb:electronically{ MODIF_TYPE:ADJ } tag eng_adverb:elegantly{ MODIF_TYPE:ADJ } tag eng_adverb:eloquently{ MODIF_TYPE:ADJ } tag eng_adverb:embarrassingly{ MODIF_TYPE:ADJ } tag eng_adverb:eminently{ MODIF_TYPE:ADJ } tag eng_adverb:emotionally{ MODIF_TYPE:ADJ } tag eng_adverb:emphatically{ MODIF_TYPE:ADJ } tag eng_adverb:encouragingly{ MODIF_TYPE:ADJ } tag eng_adverb:endearingly{ MODIF_TYPE:ADJ } tag eng_adverb:endlessly{ MODIF_TYPE:ADJ } tag eng_adverb:energetically{ MODIF_TYPE:ADJ } tag eng_adverb:engagingly{ MODIF_TYPE:ADJ } tag eng_adverb:enigmatically{ MODIF_TYPE:ADJ } tag eng_adverb:enormously{ MODIF_TYPE:ADJ } tag eng_adverb:enquiringly{ MODIF_TYPE:ADJ } tag eng_adverb:enterprisingly{ MODIF_TYPE:ADJ } tag eng_adverb:entertainingly{ MODIF_TYPE:ADJ } tag eng_adverb:enthusiastically{ MODIF_TYPE:ADJ } tag eng_adverb:enviously{ MODIF_TYPE:ADJ } tag eng_adverb:epidurally{ MODIF_TYPE:ADJ } tag eng_adverb:eponymously{ MODIF_TYPE:ADJ } tag eng_adverb:equably{ MODIF_TYPE:ADJ } tag eng_adverb:equitably{ MODIF_TYPE:ADJ } tag eng_adverb:erratically{ MODIF_TYPE:ADJ } tag eng_adverb:erroneously{ MODIF_TYPE:ADJ } tag eng_adverb:eruditely{ MODIF_TYPE:ADJ } tag eng_adverb:eternally{ MODIF_TYPE:ADJ } tag eng_adverb:euphemistically{ MODIF_TYPE:ADJ } tag eng_adverb:evasively{ MODIF_TYPE:ADJ } tag eng_adverb:evenly{ MODIF_TYPE:ADJ } tag eng_adverb:evermore{ MODIF_TYPE:ADJ } tag eng_adverb:excellently{ MODIF_TYPE:ADJ } tag eng_adverb:excessively{ MODIF_TYPE:ADJ } tag eng_adverb:excitedly{ MODIF_TYPE:ADJ } tag eng_adverb:excitingly{ MODIF_TYPE:ADJ } tag eng_adverb:exclusively{ MODIF_TYPE:ADJ } tag eng_adverb:excruciatingly{ MODIF_TYPE:ADJ } tag eng_adverb:exhaustively{ MODIF_TYPE:ADJ } tag eng_adverb:exorbitantly{ MODIF_TYPE:ADJ } tag eng_adverb:expansively{ MODIF_TYPE:ADJ } tag eng_adverb:expectantly{ MODIF_TYPE:ADJ } tag eng_adverb:experimentally{ MODIF_TYPE:ADJ } tag eng_adverb:expertly{ MODIF_TYPE:ADJ } tag eng_adverb:explicitly{ MODIF_TYPE:ADJ } tag eng_adverb:explosively{ MODIF_TYPE:ADJ } tag eng_adverb:exponentially{ MODIF_TYPE:ADJ } tag eng_adverb:expressively{ MODIF_TYPE:ADJ } tag eng_adverb:expressly{ MODIF_TYPE:ADJ } tag eng_adverb:exquisitely{ MODIF_TYPE:ADJ } tag eng_adverb:extemporaneously{ MODIF_TYPE:ADJ } tag eng_adverb:extensively{ MODIF_TYPE:ADJ } tag eng_adverb:externally{ MODIF_TYPE:ADJ } tag eng_adverb:extravagantly{ MODIF_TYPE:ADJ } tag eng_adverb:exuberantly{ MODIF_TYPE:ADJ } tag eng_adverb:exultantly{ MODIF_TYPE:ADJ } tag eng_adverb:facetiously{ MODIF_TYPE:ADJ } tag eng_adverb:facially{ MODIF_TYPE:ADJ } tag eng_adverb:faintly{ MODIF_TYPE:ADJ } tag eng_adverb:faithfully{ MODIF_TYPE:ADJ } tag eng_adverb:falsely{ MODIF_TYPE:ADJ } tag eng_adverb:famously{ MODIF_TYPE:ADJ } tag eng_adverb:fanatically{ MODIF_TYPE:ADJ } tag eng_adverb:fantastically{ MODIF_TYPE:ADJ } //tag eng_adverb:fast{ MODIF_TYPE:ADJ } tag eng_adverb:fastidiously{ MODIF_TYPE:ADJ } tag eng_adverb:fatally{ MODIF_TYPE:ADJ } tag eng_adverb:fatuously{ MODIF_TYPE:ADJ } tag eng_adverb:faultlessly{ MODIF_TYPE:ADJ } tag eng_adverb:favorably{ MODIF_TYPE:ADJ } tag eng_adverb:favourably{ MODIF_TYPE:ADJ } tag eng_adverb:fearfully{ MODIF_TYPE:ADJ } tag eng_adverb:fearlessly{ MODIF_TYPE:ADJ } tag eng_adverb:feebly{ MODIF_TYPE:ADJ } tag eng_adverb:ferociously{ MODIF_TYPE:ADJ } tag eng_adverb:fervently{ MODIF_TYPE:ADJ } tag eng_adverb:fervidly{ MODIF_TYPE:ADJ } tag eng_adverb:feverishly{ MODIF_TYPE:ADJ } tag eng_adverb:fiendishly{ MODIF_TYPE:ADJ } tag eng_adverb:fiercely{ MODIF_TYPE:ADJ } tag eng_adverb:figuratively{ MODIF_TYPE:ADJ } tag eng_adverb:firmly{ MODIF_TYPE:ADJ } tag eng_adverb:first-class{ MODIF_TYPE:ADJ } tag eng_adverb:first-hand{ MODIF_TYPE:ADJ } tag eng_adverb:fiscally{ MODIF_TYPE:ADJ } tag eng_adverb:fitfully{ MODIF_TYPE:ADJ } tag eng_adverb:fittingly{ MODIF_TYPE:ADJ } tag eng_adverb:flagrantly{ MODIF_TYPE:ADJ } tag eng_adverb:flamboyantly{ MODIF_TYPE:ADJ } tag eng_adverb:flashily{ MODIF_TYPE:ADJ } tag eng_adverb:flawlessly{ MODIF_TYPE:ADJ } tag eng_adverb:flexibly{ MODIF_TYPE:ADJ } tag eng_adverb:flippantly{ MODIF_TYPE:ADJ } tag eng_adverb:flirtatiously{ MODIF_TYPE:ADJ } tag eng_adverb:fluently{ MODIF_TYPE:ADJ } tag eng_adverb:fondly{ MODIF_TYPE:ADJ } tag eng_adverb:foolishly{ MODIF_TYPE:ADJ } tag eng_adverb:forbiddingly{ MODIF_TYPE:ADJ } tag eng_adverb:forcefully{ MODIF_TYPE:ADJ } tag eng_adverb:forcibly{ MODIF_TYPE:ADJ } tag eng_adverb:forgivingly{ MODIF_TYPE:ADJ } tag eng_adverb:forlornly{ MODIF_TYPE:ADJ } tag eng_adverb:formally{ MODIF_TYPE:ADJ } tag eng_adverb:formidably{ MODIF_TYPE:ADJ } tag eng_adverb:forthwith{ MODIF_TYPE:ADJ } tag eng_adverb:fortissimo{ MODIF_TYPE:ADJ } tag eng_adverb:fortnightly{ MODIF_TYPE:ADJ } tag eng_adverb:fortuitously{ MODIF_TYPE:ADJ } tag eng_adverb:frankly{ MODIF_TYPE:ADJ } tag eng_adverb:frantically{ MODIF_TYPE:ADJ } tag eng_adverb:fraternally{ MODIF_TYPE:ADJ } tag eng_adverb:fraudulently{ MODIF_TYPE:ADJ } tag eng_adverb:freakishly{ MODIF_TYPE:ADJ } tag eng_adverb:freely{ MODIF_TYPE:ADJ } tag eng_adverb:frequently{ MODIF_TYPE:ADJ } tag eng_adverb:freshly{ MODIF_TYPE:ADJ } tag eng_adverb:fretfully{ MODIF_TYPE:ADJ } tag eng_adverb:frigidly{ MODIF_TYPE:ADJ } tag eng_adverb:friskily{ MODIF_TYPE:ADJ } tag eng_adverb:frivolously{ MODIF_TYPE:ADJ } tag eng_adverb:frostily{ MODIF_TYPE:ADJ } tag eng_adverb:frugally{ MODIF_TYPE:ADJ } tag eng_adverb:fruitfully{ MODIF_TYPE:ADJ } tag eng_adverb:fruitlessly{ MODIF_TYPE:ADJ } tag eng_adverb:full-time{ MODIF_TYPE:ADJ } tag eng_adverb:functionally{ MODIF_TYPE:ADJ } tag eng_adverb:funnily{ MODIF_TYPE:ADJ } tag eng_adverb:furiously{ MODIF_TYPE:ADJ } tag eng_adverb:furtively{ MODIF_TYPE:ADJ } tag eng_adverb:fussily{ MODIF_TYPE:ADJ } tag eng_adverb:gaily{ MODIF_TYPE:ADJ } tag eng_adverb:gainfully{ MODIF_TYPE:ADJ } tag eng_adverb:gallantly{ MODIF_TYPE:ADJ } tag eng_adverb:galore{ MODIF_TYPE:ADJ } tag eng_adverb:gamely{ MODIF_TYPE:ADJ } tag eng_adverb:garishly{ MODIF_TYPE:ADJ } tag eng_adverb:gaudily{ MODIF_TYPE:ADJ } tag eng_adverb:generously{ MODIF_TYPE:ADJ } tag eng_adverb:genially{ MODIF_TYPE:ADJ } tag eng_adverb:genteelly{ MODIF_TYPE:ADJ } tag eng_adverb:gently{ MODIF_TYPE:ADJ } tag eng_adverb:giddily{ MODIF_TYPE:ADJ } tag eng_adverb:girlishly{ MODIF_TYPE:ADJ } tag eng_adverb:gladly{ MODIF_TYPE:ADJ } tag eng_adverb:gleefully{ MODIF_TYPE:ADJ } tag eng_adverb:glibly{ MODIF_TYPE:ADJ } tag eng_adverb:gloatingly{ MODIF_TYPE:ADJ } tag eng_adverb:globally{ MODIF_TYPE:ADJ } tag eng_adverb:gloomily{ MODIF_TYPE:ADJ } tag eng_adverb:gloriously{ MODIF_TYPE:ADJ } tag eng_adverb:glowingly{ MODIF_TYPE:ADJ } tag eng_adverb:glumly{ MODIF_TYPE:ADJ } tag eng_adverb:gorgeously{ MODIF_TYPE:ADJ } tag eng_adverb:gracefully{ MODIF_TYPE:ADJ } tag eng_adverb:graciously{ MODIF_TYPE:ADJ } tag eng_adverb:grandly{ MODIF_TYPE:ADJ } tag eng_adverb:graphically{ MODIF_TYPE:ADJ } tag eng_adverb:gratefully{ MODIF_TYPE:ADJ } tag eng_adverb:gratis{ MODIF_TYPE:ADJ } tag eng_adverb:gratuitously{ MODIF_TYPE:ADJ } tag eng_adverb:gravely{ MODIF_TYPE:ADJ } tag eng_adverb:greedily{ MODIF_TYPE:ADJ } tag eng_adverb:gregariously{ MODIF_TYPE:ADJ } tag eng_adverb:grievously{ MODIF_TYPE:ADJ } tag eng_adverb:grimly{ MODIF_TYPE:ADJ } tag eng_adverb:grotesquely{ MODIF_TYPE:ADJ } tag eng_adverb:grudgingly{ MODIF_TYPE:ADJ } tag eng_adverb:gruffly{ MODIF_TYPE:ADJ } tag eng_adverb:grumpily{ MODIF_TYPE:ADJ } tag eng_adverb:guardedly{ MODIF_TYPE:ADJ } tag eng_adverb:guiltily{ MODIF_TYPE:ADJ } tag eng_adverb:gushingly{ MODIF_TYPE:ADJ } tag eng_adverb:habitually{ MODIF_TYPE:ADJ } tag eng_adverb:half-heartedly{ MODIF_TYPE:ADJ } tag eng_adverb:halfway{ MODIF_TYPE:ADJ } tag eng_adverb:haltingly{ MODIF_TYPE:ADJ } tag eng_adverb:handily{ MODIF_TYPE:ADJ } tag eng_adverb:handsomely{ MODIF_TYPE:ADJ } tag eng_adverb:haphazardly{ MODIF_TYPE:ADJ } tag eng_adverb:happily{ MODIF_TYPE:ADJ } tag eng_adverb:harmoniously{ MODIF_TYPE:ADJ } tag eng_adverb:harshly{ MODIF_TYPE:ADJ } tag eng_adverb:hastily{ MODIF_TYPE:ADJ } tag eng_adverb:hatefully{ MODIF_TYPE:ADJ } tag eng_adverb:haughtily{ MODIF_TYPE:ADJ } tag eng_adverb:headlong{ MODIF_TYPE:ADJ } tag eng_adverb:head-on{ MODIF_TYPE:ADJ } tag eng_adverb:heartily{ MODIF_TYPE:ADJ } tag eng_adverb:heartlessly{ MODIF_TYPE:ADJ } tag eng_adverb:heatedly{ MODIF_TYPE:ADJ } tag eng_adverb:helpfully{ MODIF_TYPE:ADJ } tag eng_adverb:helplessly{ MODIF_TYPE:ADJ } tag eng_adverb:helter-skelter{ MODIF_TYPE:ADJ } tag eng_adverb:henceforth{ MODIF_TYPE:ADJ } tag eng_adverb:hereabouts{ MODIF_TYPE:ADJ } tag eng_adverb:hereafter{ MODIF_TYPE:ADJ } tag eng_adverb:hermetically{ MODIF_TYPE:ADJ } tag eng_adverb:heroically{ MODIF_TYPE:ADJ } tag eng_adverb:hesitantly{ MODIF_TYPE:ADJ } tag eng_adverb:hesitatingly{ MODIF_TYPE:ADJ } tag eng_adverb:hideously{ MODIF_TYPE:ADJ } tag eng_adverb:higgledy-piggledy{ MODIF_TYPE:ADJ } tag eng_adverb:high-handedly{ MODIF_TYPE:ADJ } tag eng_adverb:hilariously{ MODIF_TYPE:ADJ } tag eng_adverb:hither{ MODIF_TYPE:ADJ } tag eng_adverb:hitherto{ MODIF_TYPE:ADJ } tag eng_adverb:hoarsely{ MODIF_TYPE:ADJ } tag eng_adverb:homeward{ MODIF_TYPE:ADJ } tag eng_adverb:homewards{ MODIF_TYPE:ADJ } tag eng_adverb:honestly{ MODIF_TYPE:ADJ } tag eng_adverb:honorably{ MODIF_TYPE:ADJ } tag eng_adverb:honourably{ MODIF_TYPE:ADJ } tag eng_adverb:hopelessly{ MODIF_TYPE:ADJ } tag eng_adverb:horizontally{ MODIF_TYPE:ADJ } tag eng_adverb:horribly{ MODIF_TYPE:ADJ } tag eng_adverb:horrifically{ MODIF_TYPE:ADJ } tag eng_adverb:hospitably{ MODIF_TYPE:ADJ } tag eng_adverb:hotly{ MODIF_TYPE:ADJ } tag eng_adverb:huffily{ MODIF_TYPE:ADJ } tag eng_adverb:humanely{ MODIF_TYPE:ADJ } tag eng_adverb:humbly{ MODIF_TYPE:ADJ } tag eng_adverb:humorously{ MODIF_TYPE:ADJ } tag eng_adverb:hungrily{ MODIF_TYPE:ADJ } tag eng_adverb:hurriedly{ MODIF_TYPE:ADJ } tag eng_adverb:huskily{ MODIF_TYPE:ADJ } tag eng_adverb:hypocritically{ MODIF_TYPE:ADJ } tag eng_adverb:hysterically{ MODIF_TYPE:ADJ } tag eng_adverb:icily{ MODIF_TYPE:ADJ } tag eng_adverb:identically{ MODIF_TYPE:ADJ } tag eng_adverb:ideologically{ MODIF_TYPE:ADJ } tag eng_adverb:idiomatically{ MODIF_TYPE:ADJ } tag eng_adverb:idly{ MODIF_TYPE:ADJ } tag eng_adverb:illegally{ MODIF_TYPE:ADJ } tag eng_adverb:illegibly{ MODIF_TYPE:ADJ } tag eng_adverb:illegitimately{ MODIF_TYPE:ADJ } tag eng_adverb:illicitly{ MODIF_TYPE:ADJ } tag eng_adverb:illustriously{ MODIF_TYPE:ADJ } tag eng_adverb:imaginatively{ MODIF_TYPE:ADJ } tag eng_adverb:immaculately{ MODIF_TYPE:ADJ } tag eng_adverb:immeasurably{ MODIF_TYPE:ADJ } tag eng_adverb:immensely{ MODIF_TYPE:ADJ } tag eng_adverb:imminently{ MODIF_TYPE:ADJ } tag eng_adverb:immodestly{ MODIF_TYPE:ADJ } tag eng_adverb:immorally{ MODIF_TYPE:ADJ } tag eng_adverb:impartially{ MODIF_TYPE:ADJ } tag eng_adverb:impassively{ MODIF_TYPE:ADJ } tag eng_adverb:impatiently{ MODIF_TYPE:ADJ } tag eng_adverb:impeccably{ MODIF_TYPE:ADJ } tag eng_adverb:imperceptibly{ MODIF_TYPE:ADJ } tag eng_adverb:imperfectly{ MODIF_TYPE:ADJ } tag eng_adverb:imperially{ MODIF_TYPE:ADJ } tag eng_adverb:imperiously{ MODIF_TYPE:ADJ } tag eng_adverb:impertinently{ MODIF_TYPE:ADJ } tag eng_adverb:impetuously{ MODIF_TYPE:ADJ } tag eng_adverb:impishly{ MODIF_TYPE:ADJ } tag eng_adverb:implausibly{ MODIF_TYPE:ADJ } tag eng_adverb:implicitly{ MODIF_TYPE:ADJ } tag eng_adverb:imploringly{ MODIF_TYPE:ADJ } tag eng_adverb:impolitely{ MODIF_TYPE:ADJ } tag eng_adverb:imposingly{ MODIF_TYPE:ADJ } tag eng_adverb:impossibly{ MODIF_TYPE:ADJ } tag eng_adverb:impractically{ MODIF_TYPE:ADJ } tag eng_adverb:imprecisely{ MODIF_TYPE:ADJ } tag eng_adverb:impressively{ MODIF_TYPE:ADJ } tag eng_adverb:improperly{ MODIF_TYPE:ADJ } tag eng_adverb:imprudently{ MODIF_TYPE:ADJ } tag eng_adverb:impudently{ MODIF_TYPE:ADJ } tag eng_adverb:impulsively{ MODIF_TYPE:ADJ } tag eng_adverb:inaccurately{ MODIF_TYPE:ADJ } tag eng_adverb:inadequately{ MODIF_TYPE:ADJ } tag eng_adverb:inadvertantly{ MODIF_TYPE:ADJ } tag eng_adverb:inadvertently{ MODIF_TYPE:ADJ } tag eng_adverb:inanely{ MODIF_TYPE:ADJ } tag eng_adverb:inappropriately{ MODIF_TYPE:ADJ } tag eng_adverb:inarticulately{ MODIF_TYPE:ADJ } tag eng_adverb:incessantly{ MODIF_TYPE:ADJ } tag eng_adverb:incisively{ MODIF_TYPE:ADJ } tag eng_adverb:inclusively{ MODIF_TYPE:ADJ } tag eng_adverb:incognito{ MODIF_TYPE:ADJ } tag eng_adverb:incoherently{ MODIF_TYPE:ADJ } tag eng_adverb:incompetently{ MODIF_TYPE:ADJ } tag eng_adverb:incompletely{ MODIF_TYPE:ADJ } tag eng_adverb:inconclusively{ MODIF_TYPE:ADJ } tag eng_adverb:incongruously{ MODIF_TYPE:ADJ } tag eng_adverb:inconsiderately{ MODIF_TYPE:ADJ } tag eng_adverb:inconsistently{ MODIF_TYPE:ADJ } tag eng_adverb:inconspicuously{ MODIF_TYPE:ADJ } tag eng_adverb:inconveniently{ MODIF_TYPE:ADJ } tag eng_adverb:incorrectly{ MODIF_TYPE:ADJ } tag eng_adverb:incredulously{ MODIF_TYPE:ADJ } tag eng_adverb:indecently{ MODIF_TYPE:ADJ } tag eng_adverb:indecisively{ MODIF_TYPE:ADJ } tag eng_adverb:indefinitely{ MODIF_TYPE:ADJ } tag eng_adverb:indelibly{ MODIF_TYPE:ADJ } tag eng_adverb:indifferently{ MODIF_TYPE:ADJ } tag eng_adverb:indignantly{ MODIF_TYPE:ADJ } tag eng_adverb:indirectly{ MODIF_TYPE:ADJ } tag eng_adverb:indiscreetly{ MODIF_TYPE:ADJ } tag eng_adverb:indiscriminately{ MODIF_TYPE:ADJ } tag eng_adverb:individually{ MODIF_TYPE:ADJ } tag eng_adverb:indolently{ MODIF_TYPE:ADJ } tag eng_adverb:industriously{ MODIF_TYPE:ADJ } tag eng_adverb:ineffably{ MODIF_TYPE:ADJ } tag eng_adverb:ineffectively{ MODIF_TYPE:ADJ } tag eng_adverb:ineffectually{ MODIF_TYPE:ADJ } tag eng_adverb:inefficiently{ MODIF_TYPE:ADJ } tag eng_adverb:inelegantly{ MODIF_TYPE:ADJ } tag eng_adverb:ineptly{ MODIF_TYPE:ADJ } tag eng_adverb:inescapably{ MODIF_TYPE:ADJ } tag eng_adverb:inexorably{ MODIF_TYPE:ADJ } tag eng_adverb:inexpensively{ MODIF_TYPE:ADJ } tag eng_adverb:inexplicably{ MODIF_TYPE:ADJ } tag eng_adverb:inextricably{ MODIF_TYPE:ADJ } tag eng_adverb:infamously{ MODIF_TYPE:ADJ } tag eng_adverb:inflexibly{ MODIF_TYPE:ADJ } tag eng_adverb:informally{ MODIF_TYPE:ADJ } tag eng_adverb:informatively{ MODIF_TYPE:ADJ } tag eng_adverb:infrequently{ MODIF_TYPE:ADJ } tag eng_adverb:ingeniously{ MODIF_TYPE:ADJ } tag eng_adverb:ingratiatingly{ MODIF_TYPE:ADJ } tag eng_adverb:inhumanely{ MODIF_TYPE:ADJ } tag eng_adverb:inimitably{ MODIF_TYPE:ADJ } tag eng_adverb:innately{ MODIF_TYPE:ADJ } tag eng_adverb:innocently{ MODIF_TYPE:ADJ } tag eng_adverb:inoffensively{ MODIF_TYPE:ADJ } tag eng_adverb:inordinately{ MODIF_TYPE:ADJ } tag eng_adverb:inorganically{ MODIF_TYPE:ADJ } tag eng_adverb:inquiringly{ MODIF_TYPE:ADJ } tag eng_adverb:inquisitively{ MODIF_TYPE:ADJ } tag eng_adverb:insanely{ MODIF_TYPE:ADJ } tag eng_adverb:insatiably{ MODIF_TYPE:ADJ } tag eng_adverb:insecurely{ MODIF_TYPE:ADJ } tag eng_adverb:insensitively{ MODIF_TYPE:ADJ } tag eng_adverb:insidiously{ MODIF_TYPE:ADJ } tag eng_adverb:insightfully{ MODIF_TYPE:ADJ } tag eng_adverb:insinuatingly{ MODIF_TYPE:ADJ } tag eng_adverb:insipidly{ MODIF_TYPE:ADJ } tag eng_adverb:insistently{ MODIF_TYPE:ADJ } tag eng_adverb:insolently{ MODIF_TYPE:ADJ } tag eng_adverb:instantaneously{ MODIF_TYPE:ADJ } tag eng_adverb:instantly{ MODIF_TYPE:ADJ } tag eng_adverb:instinctively{ MODIF_TYPE:ADJ } tag eng_adverb:insufferably{ MODIF_TYPE:ADJ } tag eng_adverb:insufficiently{ MODIF_TYPE:ADJ } tag eng_adverb:insultingly{ MODIF_TYPE:ADJ } tag eng_adverb:insuperably{ MODIF_TYPE:ADJ } tag eng_adverb:integrally{ MODIF_TYPE:ADJ } tag eng_adverb:intellectually{ MODIF_TYPE:ADJ } tag eng_adverb:intelligently{ MODIF_TYPE:ADJ } tag eng_adverb:intelligibly{ MODIF_TYPE:ADJ } tag eng_adverb:intensely{ MODIF_TYPE:ADJ } tag eng_adverb:intensively{ MODIF_TYPE:ADJ } tag eng_adverb:intentionally{ MODIF_TYPE:ADJ } tag eng_adverb:intently{ MODIF_TYPE:ADJ } tag eng_adverb:interchangeably{ MODIF_TYPE:ADJ } tag eng_adverb:interminably{ MODIF_TYPE:ADJ } tag eng_adverb:intermittently{ MODIF_TYPE:ADJ } tag eng_adverb:internally{ MODIF_TYPE:ADJ } // an internally controlled environment tag eng_adverb:internationally{ MODIF_TYPE:ADJ } tag eng_adverb:interrogatively{ MODIF_TYPE:ADJ } tag eng_adverb:intimately{ MODIF_TYPE:ADJ } tag eng_adverb:intransitively{ MODIF_TYPE:ADJ } tag eng_adverb:intravenously{ MODIF_TYPE:ADJ } tag eng_adverb:intrepidly{ MODIF_TYPE:ADJ } tag eng_adverb:intricately{ MODIF_TYPE:ADJ } tag eng_adverb:intrinsically{ MODIF_TYPE:ADJ } // There are also intrinsically multidimensional FFT algorithms. tag eng_adverb:intuitively{ MODIF_TYPE:ADJ } tag eng_adverb:inventively{ MODIF_TYPE:ADJ } tag eng_adverb:inversely{ MODIF_TYPE:ADJ } tag eng_adverb:invisibly{ MODIF_TYPE:ADJ } tag eng_adverb:invitingly{ MODIF_TYPE:ADJ } tag eng_adverb:involuntarily{ MODIF_TYPE:ADJ } tag eng_adverb:inwardly{ MODIF_TYPE:ADJ } tag eng_adverb:irately{ MODIF_TYPE:ADJ } tag eng_adverb:irmly{ MODIF_TYPE:ADJ } tag eng_adverb:irrationally{ MODIF_TYPE:ADJ } tag eng_adverb:irregularly{ MODIF_TYPE:ADJ } tag eng_adverb:irrelevantly{ MODIF_TYPE:ADJ } tag eng_adverb:irreparably{ MODIF_TYPE:ADJ } tag eng_adverb:irresistibly{ MODIF_TYPE:ADJ } tag eng_adverb:irresponsibly{ MODIF_TYPE:ADJ } tag eng_adverb:irretrievably{ MODIF_TYPE:ADJ } tag eng_adverb:irreverently{ MODIF_TYPE:ADJ } tag eng_adverb:irreversibly{ MODIF_TYPE:ADJ } tag eng_adverb:irritably{ MODIF_TYPE:ADJ } tag eng_adverb:jarringly{ MODIF_TYPE:ADJ } tag eng_adverb:jauntily{ MODIF_TYPE:ADJ } tag eng_adverb:jealously{ MODIF_TYPE:ADJ } tag eng_adverb:jerkily{ MODIF_TYPE:ADJ } tag eng_adverb:jestingly{ MODIF_TYPE:ADJ } tag eng_adverb:jocosely{ MODIF_TYPE:ADJ } tag eng_adverb:jocularly{ MODIF_TYPE:ADJ } tag eng_adverb:jokingly{ MODIF_TYPE:ADJ } tag eng_adverb:jovially{ MODIF_TYPE:ADJ } tag eng_adverb:joyfully{ MODIF_TYPE:ADJ } tag eng_adverb:joyously{ MODIF_TYPE:ADJ } tag eng_adverb:jubilantly{ MODIF_TYPE:ADJ } tag eng_adverb:judiciously{ MODIF_TYPE:ADJ } tag eng_adverb:justly{ MODIF_TYPE:ADJ } tag eng_adverb:keenly{ MODIF_TYPE:ADJ } tag eng_adverb:knowingly{ MODIF_TYPE:ADJ } tag eng_adverb:laboriously{ MODIF_TYPE:ADJ } tag eng_adverb:lackadaisically{ MODIF_TYPE:ADJ } tag eng_adverb:laconically{ MODIF_TYPE:ADJ } tag eng_adverb:lamely{ MODIF_TYPE:ADJ } tag eng_adverb:landward{ MODIF_TYPE:ADJ } tag eng_adverb:languidly{ MODIF_TYPE:ADJ } tag eng_adverb:languorously{ MODIF_TYPE:ADJ } tag eng_adverb:lasciviously{ MODIF_TYPE:ADJ } tag eng_adverb:laterally{ MODIF_TYPE:ADJ } tag eng_adverb:latterly{ MODIF_TYPE:ADJ } tag eng_adverb:laudably{ MODIF_TYPE:ADJ } tag eng_adverb:laughingly{ MODIF_TYPE:ADJ } tag eng_adverb:lavishly{ MODIF_TYPE:ADJ } tag eng_adverb:lawfully{ MODIF_TYPE:ADJ } tag eng_adverb:lazily{ MODIF_TYPE:ADJ } tag eng_adverb:learnedly{ MODIF_TYPE:ADJ } tag eng_adverb:legally{ MODIF_TYPE:ADJ } tag eng_adverb:legibly{ MODIF_TYPE:ADJ } tag eng_adverb:legislatively{ MODIF_TYPE:ADJ } tag eng_adverb:legitimately{ MODIF_TYPE:ADJ } tag eng_adverb:lengthily{ MODIF_TYPE:ADJ } tag eng_adverb:lengthways{ MODIF_TYPE:ADJ } tag eng_adverb:leniently{ MODIF_TYPE:ADJ } tag eng_adverb:lento{ MODIF_TYPE:ADJ } tag eng_adverb:lethargically{ MODIF_TYPE:ADJ } tag eng_adverb:lewdly{ MODIF_TYPE:ADJ } tag eng_adverb:lexically{ MODIF_TYPE:ADJ } tag eng_adverb:liberally{ MODIF_TYPE:ADJ } tag eng_adverb:licentiously{ MODIF_TYPE:ADJ } tag eng_adverb:lifelessly{ MODIF_TYPE:ADJ } tag eng_adverb:light-headedly{ MODIF_TYPE:ADJ } tag eng_adverb:light-heartedly{ MODIF_TYPE:ADJ } tag eng_adverb:lightheartedly{ MODIF_TYPE:ADJ } tag eng_adverb:lightly{ MODIF_TYPE:ADJ } tag eng_adverb:limply{ MODIF_TYPE:ADJ } tag eng_adverb:linearly{ MODIF_TYPE:ADJ } tag eng_adverb:listlessly{ MODIF_TYPE:ADJ } tag eng_adverb:locally{ MODIF_TYPE:ADJ } tag eng_adverb:loftily{ MODIF_TYPE:ADJ } tag eng_adverb:logarithmically{ MODIF_TYPE:ADJ } tag eng_adverb:longingly{ MODIF_TYPE:ADJ } tag eng_adverb:longitudinally{ MODIF_TYPE:ADJ } tag eng_adverb:longways{ MODIF_TYPE:ADJ } tag eng_adverb:loosely{ MODIF_TYPE:ADJ } tag eng_adverb:loquaciously{ MODIF_TYPE:ADJ } tag eng_adverb:loudly{ MODIF_TYPE:ADJ } tag eng_adverb:lovingly{ MODIF_TYPE:ADJ } tag eng_adverb:loyally{ MODIF_TYPE:ADJ } tag eng_adverb:lucidly{ MODIF_TYPE:ADJ } tag eng_adverb:ludicrously{ MODIF_TYPE:ADJ } tag eng_adverb:lugubriously{ MODIF_TYPE:ADJ } tag eng_adverb:lukewarmly{ MODIF_TYPE:ADJ } tag eng_adverb:luridly{ MODIF_TYPE:ADJ } tag eng_adverb:lustfully{ MODIF_TYPE:ADJ } tag eng_adverb:lustily{ MODIF_TYPE:ADJ } tag eng_adverb:luxuriantly{ MODIF_TYPE:ADJ } tag eng_adverb:luxuriously{ MODIF_TYPE:ADJ } tag eng_adverb:lyrically{ MODIF_TYPE:ADJ } tag eng_adverb:magically{ MODIF_TYPE:ADJ } tag eng_adverb:magisterially{ MODIF_TYPE:ADJ } tag eng_adverb:magnanimously{ MODIF_TYPE:ADJ } tag eng_adverb:magnetically{ MODIF_TYPE:ADJ } tag eng_adverb:magnificently{ MODIF_TYPE:ADJ } tag eng_adverb:majestically{ MODIF_TYPE:ADJ } tag eng_adverb:malevolently{ MODIF_TYPE:ADJ } tag eng_adverb:maliciously{ MODIF_TYPE:ADJ } tag eng_adverb:malignantly{ MODIF_TYPE:ADJ } tag eng_adverb:manageably{ MODIF_TYPE:ADJ } tag eng_adverb:manfully{ MODIF_TYPE:ADJ } tag eng_adverb:manifestly{ MODIF_TYPE:ADJ } tag eng_adverb:manually{ MODIF_TYPE:ADJ } tag eng_adverb:markedly{ MODIF_TYPE:ADJ } tag eng_adverb:marvellously{ MODIF_TYPE:ADJ } tag eng_adverb:marvelously{ MODIF_TYPE:ADJ } tag eng_adverb:massively{ MODIF_TYPE:ADJ } tag eng_adverb:masterfully{ MODIF_TYPE:ADJ } tag eng_adverb:maternally{ MODIF_TYPE:ADJ } tag eng_adverb:maturely{ MODIF_TYPE:ADJ } tag eng_adverb:maximally{ MODIF_TYPE:ADJ } tag eng_adverb:meagrely{ MODIF_TYPE:ADJ } tag eng_adverb:meaningfully{ MODIF_TYPE:ADJ } tag eng_adverb:meanly{ MODIF_TYPE:ADJ } tag eng_adverb:measurably{ MODIF_TYPE:ADJ } tag eng_adverb:mechanically{ MODIF_TYPE:ADJ } tag eng_adverb:mechanistically{ MODIF_TYPE:ADJ } tag eng_adverb:meditatively{ MODIF_TYPE:ADJ } tag eng_adverb:meekly{ MODIF_TYPE:ADJ } tag eng_adverb:melodiously{ MODIF_TYPE:ADJ } tag eng_adverb:melodramatically{ MODIF_TYPE:ADJ } tag eng_adverb:memorably{ MODIF_TYPE:ADJ } tag eng_adverb:menacingly{ MODIF_TYPE:ADJ } tag eng_adverb:menially{ MODIF_TYPE:ADJ } tag eng_adverb:mentally{ MODIF_TYPE:ADJ } tag eng_adverb:mercilessly{ MODIF_TYPE:ADJ } tag eng_adverb:merrily{ MODIF_TYPE:ADJ } tag eng_adverb:metaphorically{ MODIF_TYPE:ADJ } tag eng_adverb:methodically{ MODIF_TYPE:ADJ } tag eng_adverb:meticulously{ MODIF_TYPE:ADJ } tag eng_adverb:metrically{ MODIF_TYPE:ADJ } tag eng_adverb:microscopically{ MODIF_TYPE:ADJ } tag eng_adverb:mightily{ MODIF_TYPE:ADJ } tag eng_adverb:mildly{ MODIF_TYPE:ADJ } tag eng_adverb:militarily{ MODIF_TYPE:ADJ } tag eng_adverb:mindlessly{ MODIF_TYPE:ADJ } tag eng_adverb:minimally{ MODIF_TYPE:ADJ } tag eng_adverb:ministerially{ MODIF_TYPE:ADJ } tag eng_adverb:minorly{ MODIF_TYPE:ADJ } tag eng_adverb:minutely{ MODIF_TYPE:ADJ } tag eng_adverb:mirthfully{ MODIF_TYPE:ADJ } tag eng_adverb:mischievously{ MODIF_TYPE:ADJ } tag eng_adverb:miserably{ MODIF_TYPE:ADJ } tag eng_adverb:mistakenly{ MODIF_TYPE:ADJ } tag eng_adverb:mistrustfully{ MODIF_TYPE:ADJ } tag eng_adverb:mockingly{ MODIF_TYPE:ADJ } tag eng_adverb:modestly{ MODIF_TYPE:ADJ } tag eng_adverb:momentously{ MODIF_TYPE:ADJ } tag eng_adverb:monetarily{ MODIF_TYPE:ADJ } tag eng_adverb:monotonously{ MODIF_TYPE:ADJ } tag eng_adverb:monstrously{ MODIF_TYPE:ADJ } tag eng_adverb:moodily{ MODIF_TYPE:ADJ } tag eng_adverb:morosely{ MODIF_TYPE:ADJ } tag eng_adverb:mortally{ MODIF_TYPE:ADJ } tag eng_adverb:mournfully{ MODIF_TYPE:ADJ } tag eng_adverb:municipally{ MODIF_TYPE:ADJ } tag eng_adverb:musically{ MODIF_TYPE:ADJ } tag eng_adverb:musingly{ MODIF_TYPE:ADJ } tag eng_adverb:mutely{ MODIF_TYPE:ADJ } tag eng_adverb:mutually{ MODIF_TYPE:ADJ } tag eng_adverb:naively{ MODIF_TYPE:ADJ } tag eng_adverb:narrow-mindedly{ MODIF_TYPE:ADJ } tag eng_adverb:nasally{ MODIF_TYPE:ADJ } tag eng_adverb:nastily{ MODIF_TYPE:ADJ } tag eng_adverb:nationally{ MODIF_TYPE:ADJ } tag eng_adverb:neatly{ MODIF_TYPE:ADJ } tag eng_adverb:needlessly{ MODIF_TYPE:ADJ } tag eng_adverb:nefariously{ MODIF_TYPE:ADJ } tag eng_adverb:negatively{ MODIF_TYPE:ADJ } tag eng_adverb:negligently{ MODIF_TYPE:ADJ } tag eng_adverb:nervously{ MODIF_TYPE:ADJ } tag eng_adverb:neurotically{ MODIF_TYPE:ADJ } tag eng_adverb:nicely{ MODIF_TYPE:ADJ } tag eng_adverb:nimbly{ MODIF_TYPE:ADJ } tag eng_adverb:nobly{ MODIF_TYPE:ADJ } tag eng_adverb:noisily{ MODIF_TYPE:ADJ } tag eng_adverb:nonchalantly{ MODIF_TYPE:ADJ } tag eng_adverb:nonstop{ MODIF_TYPE:ADJ } tag eng_adverb:normally{ MODIF_TYPE:ADJ } tag eng_adverb:northwards{ MODIF_TYPE:ADJ } tag eng_adverb:nostalgically{ MODIF_TYPE:ADJ } tag eng_adverb:noticeably{ MODIF_TYPE:ADJ } tag eng_adverb:numbly{ MODIF_TYPE:ADJ } tag eng_adverb:numerically{ MODIF_TYPE:ADJ } tag eng_adverb:obdurately{ MODIF_TYPE:ADJ } tag eng_adverb:obediently{ MODIF_TYPE:ADJ } tag eng_adverb:objectionably{ MODIF_TYPE:ADJ } tag eng_adverb:objectively{ MODIF_TYPE:ADJ } tag eng_adverb:obligingly{ MODIF_TYPE:ADJ } tag eng_adverb:obliquely{ MODIF_TYPE:ADJ } tag eng_adverb:obnoxiously{ MODIF_TYPE:ADJ } tag eng_adverb:obscenely{ MODIF_TYPE:ADJ } tag eng_adverb:obscurely{ MODIF_TYPE:ADJ } tag eng_adverb:obsequiously{ MODIF_TYPE:ADJ } tag eng_adverb:observantly{ MODIF_TYPE:ADJ } tag eng_adverb:obsessively{ MODIF_TYPE:ADJ } tag eng_adverb:obstinately{ MODIF_TYPE:ADJ } tag eng_adverb:obstreperously{ MODIF_TYPE:ADJ } tag eng_adverb:obstructively{ MODIF_TYPE:ADJ } tag eng_adverb:obtrusively{ MODIF_TYPE:ADJ } tag eng_adverb:obtusely{ MODIF_TYPE:ADJ } tag eng_adverb:odiously{ MODIF_TYPE:ADJ } tag eng_adverb:offensively{ MODIF_TYPE:ADJ } tag eng_adverb:offhand{ MODIF_TYPE:ADJ } tag eng_adverb:offhandedly{ MODIF_TYPE:ADJ } tag eng_adverb:officially{ MODIF_TYPE:ADJ } tag eng_adverb:officiously{ MODIF_TYPE:ADJ } tag eng_adverb:offstage{ MODIF_TYPE:ADJ } tag eng_adverb:onerously{ MODIF_TYPE:ADJ } tag eng_adverb:onshore{ MODIF_TYPE:ADJ } tag eng_adverb:onward{ MODIF_TYPE:ADJ } tag eng_adverb:onwards{ MODIF_TYPE:ADJ } tag eng_adverb:opaquely{ MODIF_TYPE:ADJ } tag eng_adverb:openly{ MODIF_TYPE:ADJ } tag eng_adverb:oppressively{ MODIF_TYPE:ADJ } tag eng_adverb:optimally{ MODIF_TYPE:ADJ } tag eng_adverb:optimistically{ MODIF_TYPE:ADJ } tag eng_adverb:optionally{ MODIF_TYPE:ADJ } tag eng_adverb:opulently{ MODIF_TYPE:ADJ } tag eng_adverb:orally{ MODIF_TYPE:ADJ } tag eng_adverb:organically{ MODIF_TYPE:ADJ } tag eng_adverb:ornately{ MODIF_TYPE:ADJ } tag eng_adverb:orthogonally{ MODIF_TYPE:ADJ } tag eng_adverb:ostentatiously{ MODIF_TYPE:ADJ } tag eng_adverb:outrageously{ MODIF_TYPE:ADJ } tag eng_adverb:outspokenly{ MODIF_TYPE:ADJ } tag eng_adverb:outstandingly{ MODIF_TYPE:ADJ } tag eng_adverb:outwardly{ MODIF_TYPE:ADJ } tag eng_adverb:overbearingly{ MODIF_TYPE:ADJ } tag eng_adverb:overboard{ MODIF_TYPE:ADJ } tag eng_adverb:overtly{ MODIF_TYPE:ADJ } tag eng_adverb:overwhelmingly{ MODIF_TYPE:ADJ } tag eng_adverb:painfully{ MODIF_TYPE:ADJ } tag eng_adverb:painlessly{ MODIF_TYPE:ADJ } tag eng_adverb:painstakingly{ MODIF_TYPE:ADJ } tag eng_adverb:palatably{ MODIF_TYPE:ADJ } tag eng_adverb:palmately{ MODIF_TYPE:ADJ } tag eng_adverb:palpably{ MODIF_TYPE:ADJ } tag eng_adverb:parentally{ MODIF_TYPE:ADJ } tag eng_adverb:parenthetically{ MODIF_TYPE:ADJ } tag eng_adverb:parochially{ MODIF_TYPE:ADJ } tag eng_adverb:part-time{ MODIF_TYPE:ADJ } tag eng_adverb:passably{ MODIF_TYPE:ADJ } tag eng_adverb:passim{ MODIF_TYPE:ADJ } tag eng_adverb:passionately{ MODIF_TYPE:ADJ } tag eng_adverb:passively{ MODIF_TYPE:ADJ } tag eng_adverb:paternally{ MODIF_TYPE:ADJ } tag eng_adverb:pathetically{ MODIF_TYPE:ADJ } tag eng_adverb:pathologically{ MODIF_TYPE:ADJ } tag eng_adverb:patiently{ MODIF_TYPE:ADJ } tag eng_adverb:patriotically{ MODIF_TYPE:ADJ } tag eng_adverb:patronizingly{ MODIF_TYPE:ADJ } tag eng_adverb:peaceably{ MODIF_TYPE:ADJ } tag eng_adverb:peacefully{ MODIF_TYPE:ADJ } tag eng_adverb:peculiarly{ MODIF_TYPE:ADJ } tag eng_adverb:pedantically{ MODIF_TYPE:ADJ } tag eng_adverb:peevishly{ MODIF_TYPE:ADJ } tag eng_adverb:pejoratively{ MODIF_TYPE:ADJ } tag eng_adverb:pell-mell{ MODIF_TYPE:ADJ } tag eng_adverb:penetratingly{ MODIF_TYPE:ADJ } tag eng_adverb:pensively{ MODIF_TYPE:ADJ } tag eng_adverb:perceptibly{ MODIF_TYPE:ADJ } tag eng_adverb:perceptively{ MODIF_TYPE:ADJ } tag eng_adverb:perchance{ MODIF_TYPE:ADJ } tag eng_adverb:peremptorily{ MODIF_TYPE:ADJ } tag eng_adverb:perenially{ MODIF_TYPE:ADJ } tag eng_adverb:perennially{ MODIF_TYPE:ADJ } tag eng_adverb:perfectly{ MODIF_TYPE:ADJ } tag eng_adverb:perfunctorily{ MODIF_TYPE:ADJ } tag eng_adverb:perilously{ MODIF_TYPE:ADJ } tag eng_adverb:permanently{ MODIF_TYPE:ADJ } tag eng_adverb:perniciously{ MODIF_TYPE:ADJ } tag eng_adverb:perpetually{ MODIF_TYPE:ADJ } tag eng_adverb:persistently{ MODIF_TYPE:ADJ } tag eng_adverb:personally{ MODIF_TYPE:ADJ } tag eng_adverb:persuasively{ MODIF_TYPE:ADJ } tag eng_adverb:pervasively{ MODIF_TYPE:ADJ } tag eng_adverb:perversely{ MODIF_TYPE:ADJ } tag eng_adverb:pessimistically{ MODIF_TYPE:ADJ } tag eng_adverb:petulantly{ MODIF_TYPE:ADJ } tag eng_adverb:phenomenally{ MODIF_TYPE:ADJ } tag eng_adverb:physically{ MODIF_TYPE:ADJ } tag eng_adverb:pianissimo{ MODIF_TYPE:ADJ } tag eng_adverb:picturesquely{ MODIF_TYPE:ADJ } tag eng_adverb:piercingly{ MODIF_TYPE:ADJ } tag eng_adverb:pig-headedly{ MODIF_TYPE:ADJ } tag eng_adverb:piously{ MODIF_TYPE:ADJ } tag eng_adverb:pithily{ MODIF_TYPE:ADJ } tag eng_adverb:pitifully{ MODIF_TYPE:ADJ } tag eng_adverb:pizzicato{ MODIF_TYPE:ADJ } tag eng_adverb:placidly{ MODIF_TYPE:ADJ } tag eng_adverb:plaintively{ MODIF_TYPE:ADJ } tag eng_adverb:plausibly{ MODIF_TYPE:ADJ } tag eng_adverb:playfully{ MODIF_TYPE:ADJ } tag eng_adverb:pleadingly{ MODIF_TYPE:ADJ } tag eng_adverb:pleasantly{ MODIF_TYPE:ADJ } tag eng_adverb:ploddingly{ MODIF_TYPE:ADJ } tag eng_adverb:pneumatically{ MODIF_TYPE:ADJ } tag eng_adverb:poetically{ MODIF_TYPE:ADJ } tag eng_adverb:poignantly{ MODIF_TYPE:ADJ } tag eng_adverb:point-blank{ MODIF_TYPE:ADJ } tag eng_adverb:pointedly{ MODIF_TYPE:ADJ } tag eng_adverb:polemically{ MODIF_TYPE:ADJ } tag eng_adverb:politely{ MODIF_TYPE:ADJ } tag eng_adverb:pompously{ MODIF_TYPE:ADJ } tag eng_adverb:ponderously{ MODIF_TYPE:ADJ } tag eng_adverb:poorly{ MODIF_TYPE:ADJ } tag eng_adverb:popularly{ MODIF_TYPE:ADJ } tag eng_adverb:portentously{ MODIF_TYPE:ADJ } tag eng_adverb:positively{ MODIF_TYPE:ADJ } tag eng_adverb:possessively{ MODIF_TYPE:ADJ } tag eng_adverb:posthumously{ MODIF_TYPE:ADJ } tag eng_adverb:potently{ MODIF_TYPE:ADJ } tag eng_adverb:powerfully{ MODIF_TYPE:ADJ } tag eng_adverb:precariously{ MODIF_TYPE:ADJ } tag eng_adverb:precipitously{ MODIF_TYPE:ADJ } tag eng_adverb:pre-eminently{ MODIF_TYPE:ADJ } tag eng_adverb:prematurely{ MODIF_TYPE:ADJ } tag eng_adverb:presently{ MODIF_TYPE:ADJ } tag eng_adverb:prestissimo{ MODIF_TYPE:ADJ } tag eng_adverb:presumptuously{ MODIF_TYPE:ADJ } tag eng_adverb:pretentiously{ MODIF_TYPE:ADJ } tag eng_adverb:previously{ MODIF_TYPE:ADJ } tag eng_adverb:primitively{ MODIF_TYPE:ADJ } tag eng_adverb:primly{ MODIF_TYPE:ADJ } tag eng_adverb:privately{ MODIF_TYPE:ADJ } tag eng_adverb:proactively{ MODIF_TYPE:ADJ } tag eng_adverb:prodigiously{ MODIF_TYPE:ADJ } tag eng_adverb:productively{ MODIF_TYPE:ADJ } tag eng_adverb:profanely{ MODIF_TYPE:ADJ } tag eng_adverb:professionally{ MODIF_TYPE:ADJ } tag eng_adverb:proficiently{ MODIF_TYPE:ADJ } tag eng_adverb:profitably{ MODIF_TYPE:ADJ } tag eng_adverb:profoundly{ MODIF_TYPE:ADJ } tag eng_adverb:profusely{ MODIF_TYPE:ADJ } tag eng_adverb:programmatically{ MODIF_TYPE:ADJ } tag eng_adverb:progressively{ MODIF_TYPE:ADJ } tag eng_adverb:prohibitively{ MODIF_TYPE:ADJ } tag eng_adverb:prolifically{ MODIF_TYPE:ADJ } tag eng_adverb:prominently{ MODIF_TYPE:ADJ } tag eng_adverb:promiscuously{ MODIF_TYPE:ADJ } tag eng_adverb:promptly{ MODIF_TYPE:ADJ } tag eng_adverb:prophetically{ MODIF_TYPE:ADJ } tag eng_adverb:proportionally{ MODIF_TYPE:ADJ } tag eng_adverb:proportionately{ MODIF_TYPE:ADJ } tag eng_adverb:prosaically{ MODIF_TYPE:ADJ } tag eng_adverb:protectively{ MODIF_TYPE:ADJ } tag eng_adverb:proudly{ MODIF_TYPE:ADJ } tag eng_adverb:providently{ MODIF_TYPE:ADJ } tag eng_adverb:provincially{ MODIF_TYPE:ADJ } tag eng_adverb:provisionally{ MODIF_TYPE:ADJ } tag eng_adverb:provocatively{ MODIF_TYPE:ADJ } tag eng_adverb:prudently{ MODIF_TYPE:ADJ } tag eng_adverb:prudishly{ MODIF_TYPE:ADJ } tag eng_adverb:publicly{ MODIF_TYPE:ADJ } tag eng_adverb:punctually{ MODIF_TYPE:ADJ } tag eng_adverb:puritanically{ MODIF_TYPE:ADJ } tag eng_adverb:purportedly{ MODIF_TYPE:ADJ } tag eng_adverb:purposefully{ MODIF_TYPE:ADJ } tag eng_adverb:quaintly{ MODIF_TYPE:ADJ } tag eng_adverb:qualitatively{ MODIF_TYPE:ADJ } tag eng_adverb:quantitatively{ MODIF_TYPE:ADJ } tag eng_adverb:quick{ MODIF_TYPE:ADJ } tag eng_adverb:quickly{ MODIF_TYPE:ADJ } tag eng_adverb:quiescently{ MODIF_TYPE:ADJ } tag eng_adverb:quietly{ MODIF_TYPE:ADJ } tag eng_adverb:quixotically{ MODIF_TYPE:ADJ } tag eng_adverb:quizzically{ MODIF_TYPE:ADJ } tag eng_adverb:radially{ MODIF_TYPE:ADJ } tag eng_adverb:radiantly{ MODIF_TYPE:ADJ } tag eng_adverb:radically{ MODIF_TYPE:ADJ } tag eng_adverb:rampantly{ MODIF_TYPE:ADJ } tag eng_adverb:randomly{ MODIF_TYPE:ADJ } tag eng_adverb:rapidly{ MODIF_TYPE:ADJ } tag eng_adverb:rapturously{ MODIF_TYPE:ADJ } tag eng_adverb:rarely{ MODIF_TYPE:ADJ } tag eng_adverb:rashly{ MODIF_TYPE:ADJ } tag eng_adverb:rationally{ MODIF_TYPE:ADJ } tag eng_adverb:raucously{ MODIF_TYPE:ADJ } tag eng_adverb:ravenously{ MODIF_TYPE:ADJ } tag eng_adverb:readily{ MODIF_TYPE:ADJ } tag eng_adverb:reassuringly{ MODIF_TYPE:ADJ } tag eng_adverb:recklessly{ MODIF_TYPE:ADJ } tag eng_adverb:recognizably{ MODIF_TYPE:ADJ } tag eng_adverb:redundantly{ MODIF_TYPE:ADJ } tag eng_adverb:reflectively{ MODIF_TYPE:ADJ } tag eng_adverb:refreshingly{ MODIF_TYPE:ADJ } tag eng_adverb:regally{ MODIF_TYPE:ADJ } tag eng_adverb:regionally{ MODIF_TYPE:ADJ } tag eng_adverb:regretfully{ MODIF_TYPE:ADJ } tag eng_adverb:regularly{ MODIF_TYPE:ADJ } tag eng_adverb:relentlessly{ MODIF_TYPE:ADJ } tag eng_adverb:reliably{ MODIF_TYPE:ADJ } tag eng_adverb:religiously{ MODIF_TYPE:ADJ } tag eng_adverb:reluctantly{ MODIF_TYPE:ADJ } tag eng_adverb:remorsefully{ MODIF_TYPE:ADJ } tag eng_adverb:remorselessly{ MODIF_TYPE:ADJ } tag eng_adverb:remotely{ MODIF_TYPE:ADJ } tag eng_adverb:repeatably{ MODIF_TYPE:ADJ } tag eng_adverb:repeatedly{ MODIF_TYPE:ADJ } tag eng_adverb:repentantly{ MODIF_TYPE:ADJ } tag eng_adverb:repetitively{ MODIF_TYPE:ADJ } tag eng_adverb:reproachfully{ MODIF_TYPE:ADJ } tag eng_adverb:reprovingly{ MODIF_TYPE:ADJ } tag eng_adverb:resentfully{ MODIF_TYPE:ADJ } tag eng_adverb:resignedly{ MODIF_TYPE:ADJ } tag eng_adverb:resolutely{ MODIF_TYPE:ADJ } tag eng_adverb:resoundingly{ MODIF_TYPE:ADJ } tag eng_adverb:resourcefully{ MODIF_TYPE:ADJ } tag eng_adverb:respectfully{ MODIF_TYPE:ADJ } tag eng_adverb:responsibly{ MODIF_TYPE:ADJ } tag eng_adverb:restively{ MODIF_TYPE:ADJ } tag eng_adverb:restlessly{ MODIF_TYPE:ADJ } tag eng_adverb:reticently{ MODIF_TYPE:ADJ } tag eng_adverb:retroactively{ MODIF_TYPE:ADJ } tag eng_adverb:retrospectively{ MODIF_TYPE:ADJ } tag eng_adverb:reverentially{ MODIF_TYPE:ADJ } tag eng_adverb:reverently{ MODIF_TYPE:ADJ } tag eng_adverb:rhetorically{ MODIF_TYPE:ADJ } tag eng_adverb:richly{ MODIF_TYPE:ADJ } tag eng_adverb:righteously{ MODIF_TYPE:ADJ } tag eng_adverb:rightfully{ MODIF_TYPE:ADJ } tag eng_adverb:rigidly{ MODIF_TYPE:ADJ } tag eng_adverb:rigorously{ MODIF_TYPE:ADJ } tag eng_adverb:riotously{ MODIF_TYPE:ADJ } tag eng_adverb:robustly{ MODIF_TYPE:ADJ } tag eng_adverb:romantically{ MODIF_TYPE:ADJ } tag eng_adverb:roundly{ MODIF_TYPE:ADJ } tag eng_adverb:routinely{ MODIF_TYPE:ADJ } tag eng_adverb:rowdily{ MODIF_TYPE:ADJ } tag eng_adverb:royally{ MODIF_TYPE:ADJ } tag eng_adverb:rudely{ MODIF_TYPE:ADJ } tag eng_adverb:ruefully{ MODIF_TYPE:ADJ } tag eng_adverb:ruggedly{ MODIF_TYPE:ADJ } tag eng_adverb:ruthlessly{ MODIF_TYPE:ADJ } tag eng_adverb:sadistically{ MODIF_TYPE:ADJ } tag eng_adverb:safely{ MODIF_TYPE:ADJ } tag eng_adverb:sanctimoniously{ MODIF_TYPE:ADJ } tag eng_adverb:sarcastically{ MODIF_TYPE:ADJ } tag eng_adverb:sardonically{ MODIF_TYPE:ADJ } tag eng_adverb:satirically{ MODIF_TYPE:ADJ } tag eng_adverb:satisfactorily{ MODIF_TYPE:ADJ } tag eng_adverb:savagely{ MODIF_TYPE:ADJ } tag eng_adverb:scantily{ MODIF_TYPE:ADJ } tag eng_adverb:scathingly{ MODIF_TYPE:ADJ } tag eng_adverb:sceptically{ MODIF_TYPE:ADJ } tag eng_adverb:schematically{ MODIF_TYPE:ADJ } tag eng_adverb:scornfully{ MODIF_TYPE:ADJ } tag eng_adverb:scot-free{ MODIF_TYPE:ADJ } tag eng_adverb:scrupulously{ MODIF_TYPE:ADJ } tag eng_adverb:seamlessly{ MODIF_TYPE:ADJ } tag eng_adverb:seasonally{ MODIF_TYPE:ADJ } tag eng_adverb:seawards{ MODIF_TYPE:ADJ } tag eng_adverb:secretively{ MODIF_TYPE:ADJ } tag eng_adverb:secretly{ MODIF_TYPE:ADJ } tag eng_adverb:securely{ MODIF_TYPE:ADJ } tag eng_adverb:sedately{ MODIF_TYPE:ADJ } tag eng_adverb:seductively{ MODIF_TYPE:ADJ } tag eng_adverb:selectively{ MODIF_TYPE:ADJ } tag eng_adverb:selfconsciously{ MODIF_TYPE:ADJ } tag eng_adverb:self-consciously{ MODIF_TYPE:ADJ } tag eng_adverb:selfishly{ MODIF_TYPE:ADJ } tag eng_adverb:selflessly{ MODIF_TYPE:ADJ } tag eng_adverb:sensationally{ MODIF_TYPE:ADJ } tag eng_adverb:senselessly{ MODIF_TYPE:ADJ } tag eng_adverb:sensibly{ MODIF_TYPE:ADJ } tag eng_adverb:sensitively{ MODIF_TYPE:ADJ } tag eng_adverb:sensuously{ MODIF_TYPE:ADJ } tag eng_adverb:sentimentally{ MODIF_TYPE:ADJ } tag eng_adverb:separately{ MODIF_TYPE:ADJ } tag eng_adverb:sequentially{ MODIF_TYPE:ADJ } tag eng_adverb:serenely{ MODIF_TYPE:ADJ } tag eng_adverb:serially{ MODIF_TYPE:ADJ } tag eng_adverb:seriatim{ MODIF_TYPE:ADJ } tag eng_adverb:seriously{ MODIF_TYPE:ADJ } tag eng_adverb:severally{ MODIF_TYPE:ADJ } tag eng_adverb:shabbily{ MODIF_TYPE:ADJ } tag eng_adverb:shamefully{ MODIF_TYPE:ADJ } tag eng_adverb:shamelessly{ MODIF_TYPE:ADJ } tag eng_adverb:sharply{ MODIF_TYPE:ADJ } tag eng_adverb:sheepishly{ MODIF_TYPE:ADJ } tag eng_adverb:shockingly{ MODIF_TYPE:ADJ } tag eng_adverb:shrewdly{ MODIF_TYPE:ADJ } tag eng_adverb:shrilly{ MODIF_TYPE:ADJ } tag eng_adverb:shyly{ MODIF_TYPE:ADJ } tag eng_adverb:side-saddle{ MODIF_TYPE:ADJ } tag eng_adverb:silently{ MODIF_TYPE:ADJ } tag eng_adverb:simple-mindedly{ MODIF_TYPE:ADJ } tag eng_adverb:sincerely{ MODIF_TYPE:ADJ } tag eng_adverb:single-handed{ MODIF_TYPE:ADJ } tag eng_adverb:singlehandedly{ MODIF_TYPE:ADJ } tag eng_adverb:singly{ MODIF_TYPE:ADJ } tag eng_adverb:skeptically{ MODIF_TYPE:ADJ } tag eng_adverb:skilfully{ MODIF_TYPE:ADJ } tag eng_adverb:skillfully{ MODIF_TYPE:ADJ } tag eng_adverb:sky-high{ MODIF_TYPE:ADJ } tag eng_adverb:skyward{ MODIF_TYPE:ADJ } tag eng_adverb:skywards{ MODIF_TYPE:ADJ } tag eng_adverb:slavishly{ MODIF_TYPE:ADJ } tag eng_adverb:sleepily{ MODIF_TYPE:ADJ } tag eng_adverb:slickly{ MODIF_TYPE:ADJ } tag eng_adverb:sloppily{ MODIF_TYPE:ADJ } tag eng_adverb:sluggishly{ MODIF_TYPE:ADJ } tag eng_adverb:slyly{ MODIF_TYPE:ADJ } tag eng_adverb:smartly{ MODIF_TYPE:ADJ } tag eng_adverb:smilingly{ MODIF_TYPE:ADJ } tag eng_adverb:smoothly{ MODIF_TYPE:ADJ } tag eng_adverb:smugly{ MODIF_TYPE:ADJ } tag eng_adverb:sneeringly{ MODIF_TYPE:ADJ } tag eng_adverb:snobbishly{ MODIF_TYPE:ADJ } tag eng_adverb:snootily{ MODIF_TYPE:ADJ } tag eng_adverb:snugly{ MODIF_TYPE:ADJ } tag eng_adverb:soberly{ MODIF_TYPE:ADJ } tag eng_adverb:sociably{ MODIF_TYPE:ADJ } tag eng_adverb:softly{ MODIF_TYPE:ADJ } tag eng_adverb:solemnly{ MODIF_TYPE:ADJ } tag eng_adverb:solidly{ MODIF_TYPE:ADJ } tag eng_adverb:somberly{ MODIF_TYPE:ADJ } tag eng_adverb:sombrely{ MODIF_TYPE:ADJ } tag eng_adverb:sonorously{ MODIF_TYPE:ADJ } tag eng_adverb:soothingly{ MODIF_TYPE:ADJ } tag eng_adverb:sorely{ MODIF_TYPE:ADJ } tag eng_adverb:sorrowfully{ MODIF_TYPE:ADJ } tag eng_adverb:soundly{ MODIF_TYPE:ADJ } tag eng_adverb:sourly{ MODIF_TYPE:ADJ } tag eng_adverb:southwards{ MODIF_TYPE:ADJ } tag eng_adverb:spaciously{ MODIF_TYPE:ADJ } tag eng_adverb:sparingly{ MODIF_TYPE:ADJ } tag eng_adverb:sparsely{ MODIF_TYPE:ADJ } tag eng_adverb:spasmodically{ MODIF_TYPE:ADJ } tag eng_adverb:speciously{ MODIF_TYPE:ADJ } tag eng_adverb:spectacularly{ MODIF_TYPE:ADJ } tag eng_adverb:speedily{ MODIF_TYPE:ADJ } tag eng_adverb:spiritually{ MODIF_TYPE:ADJ } tag eng_adverb:spitefully{ MODIF_TYPE:ADJ } tag eng_adverb:splendidly{ MODIF_TYPE:ADJ } tag eng_adverb:spontaneously{ MODIF_TYPE:ADJ } tag eng_adverb:sporadically{ MODIF_TYPE:ADJ } tag eng_adverb:spotlessly{ MODIF_TYPE:ADJ } tag eng_adverb:spuriously{ MODIF_TYPE:ADJ } tag eng_adverb:squarely{ MODIF_TYPE:ADJ } tag eng_adverb:staggeringly{ MODIF_TYPE:ADJ } tag eng_adverb:staidly{ MODIF_TYPE:ADJ } tag eng_adverb:starkly{ MODIF_TYPE:ADJ } tag eng_adverb:statically{ MODIF_TYPE:ADJ } tag eng_adverb:staunchly{ MODIF_TYPE:ADJ } tag eng_adverb:steadfastly{ MODIF_TYPE:ADJ } tag eng_adverb:steadily{ MODIF_TYPE:ADJ } tag eng_adverb:stealthily{ MODIF_TYPE:ADJ } tag eng_adverb:steeply{ MODIF_TYPE:ADJ } tag eng_adverb:sternly{ MODIF_TYPE:ADJ } tag eng_adverb:stiffly{ MODIF_TYPE:ADJ } tag eng_adverb:stirringly{ MODIF_TYPE:ADJ } tag eng_adverb:stochastically{ MODIF_TYPE:ADJ } tag eng_adverb:stoically{ MODIF_TYPE:ADJ } tag eng_adverb:stonily{ MODIF_TYPE:ADJ } tag eng_adverb:stoutly{ MODIF_TYPE:ADJ } tag eng_adverb:straightforwardly{ MODIF_TYPE:ADJ } tag eng_adverb:strategically{ MODIF_TYPE:ADJ } tag eng_adverb:strenuously{ MODIF_TYPE:ADJ } tag eng_adverb:stridently{ MODIF_TYPE:ADJ } tag eng_adverb:strikingly{ MODIF_TYPE:ADJ } tag eng_adverb:stringently{ MODIF_TYPE:ADJ } tag eng_adverb:strong{ MODIF_TYPE:ADJ } tag eng_adverb:strongly{ MODIF_TYPE:ADJ } tag eng_adverb:stubbornly{ MODIF_TYPE:ADJ } tag eng_adverb:studiously{ MODIF_TYPE:ADJ } tag eng_adverb:stuffily{ MODIF_TYPE:ADJ } tag eng_adverb:stunningly{ MODIF_TYPE:ADJ } tag eng_adverb:stupendously{ MODIF_TYPE:ADJ } tag eng_adverb:stupidly{ MODIF_TYPE:ADJ } tag eng_adverb:sturdily{ MODIF_TYPE:ADJ } tag eng_adverb:stylishly{ MODIF_TYPE:ADJ } tag eng_adverb:suavely{ MODIF_TYPE:ADJ } tag eng_adverb:subconsciously{ MODIF_TYPE:ADJ } tag eng_adverb:subjectively{ MODIF_TYPE:ADJ } tag eng_adverb:sublimely{ MODIF_TYPE:ADJ } tag eng_adverb:subserviently{ MODIF_TYPE:ADJ } tag eng_adverb:subtly{ MODIF_TYPE:ADJ } tag eng_adverb:successfully{ MODIF_TYPE:ADJ } tag eng_adverb:successively{ MODIF_TYPE:ADJ } tag eng_adverb:succinctly{ MODIF_TYPE:ADJ } tag eng_adverb:suddenly{ MODIF_TYPE:ADJ } tag eng_adverb:suggestively{ MODIF_TYPE:ADJ } tag eng_adverb:suitably{ MODIF_TYPE:ADJ } tag eng_adverb:sullenly{ MODIF_TYPE:ADJ } tag eng_adverb:summarily{ MODIF_TYPE:ADJ } tag eng_adverb:sumptuously{ MODIF_TYPE:ADJ } tag eng_adverb:superbly{ MODIF_TYPE:ADJ } tag eng_adverb:superciliously{ MODIF_TYPE:ADJ } tag eng_adverb:superfluously{ MODIF_TYPE:ADJ } tag eng_adverb:surgically{ MODIF_TYPE:ADJ } tag eng_adverb:surpassingly{ MODIF_TYPE:ADJ } tag eng_adverb:surreptitiously{ MODIF_TYPE:ADJ } tag eng_adverb:suspiciously{ MODIF_TYPE:ADJ } tag eng_adverb:sustainably{ MODIF_TYPE:ADJ } tag eng_adverb:sweetly{ MODIF_TYPE:ADJ } tag eng_adverb:swiftly{ MODIF_TYPE:ADJ } tag eng_adverb:symbolically{ MODIF_TYPE:ADJ } tag eng_adverb:symmetrically{ MODIF_TYPE:ADJ } tag eng_adverb:sympathetically{ MODIF_TYPE:ADJ } tag eng_adverb:synthetically{ MODIF_TYPE:ADJ } tag eng_adverb:systematically{ MODIF_TYPE:ADJ } tag eng_adverb:tacitly{ MODIF_TYPE:ADJ } tag eng_adverb:tactfully{ MODIF_TYPE:ADJ } tag eng_adverb:tactically{ MODIF_TYPE:ADJ } tag eng_adverb:tactlessly{ MODIF_TYPE:ADJ } tag eng_adverb:tangibly{ MODIF_TYPE:ADJ } tag eng_adverb:tartly{ MODIF_TYPE:ADJ } tag eng_adverb:tastefully{ MODIF_TYPE:ADJ } tag eng_adverb:tastelessly{ MODIF_TYPE:ADJ } tag eng_adverb:tauntingly{ MODIF_TYPE:ADJ } tag eng_adverb:tearfully{ MODIF_TYPE:ADJ } tag eng_adverb:technically{ MODIF_TYPE:ADJ } tag eng_adverb:tediously{ MODIF_TYPE:ADJ } tag eng_adverb:tellingly{ MODIF_TYPE:ADJ } tag eng_adverb:temperamentally{ MODIF_TYPE:ADJ } tag eng_adverb:temporarily{ MODIF_TYPE:ADJ } tag eng_adverb:tenaciously{ MODIF_TYPE:ADJ } tag eng_adverb:tenderly{ MODIF_TYPE:ADJ } tag eng_adverb:tensely{ MODIF_TYPE:ADJ } tag eng_adverb:tentatively{ MODIF_TYPE:ADJ } tag eng_adverb:tenuously{ MODIF_TYPE:ADJ } tag eng_adverb:terminally{ MODIF_TYPE:ADJ } tag eng_adverb:terrifically{ MODIF_TYPE:ADJ } tag eng_adverb:tersely{ MODIF_TYPE:ADJ } tag eng_adverb:testily{ MODIF_TYPE:ADJ } tag eng_adverb:theatrically{ MODIF_TYPE:ADJ } tag eng_adverb:thermally{ MODIF_TYPE:ADJ } tag eng_adverb:thinly{ MODIF_TYPE:ADJ } tag eng_adverb:thoroughly{ MODIF_TYPE:ADJ } tag eng_adverb:thoughtfully{ MODIF_TYPE:ADJ } tag eng_adverb:thoughtlessly{ MODIF_TYPE:ADJ } tag eng_adverb:threateningly{ MODIF_TYPE:ADJ } tag eng_adverb:tightly{ MODIF_TYPE:ADJ } tag eng_adverb:timidly{ MODIF_TYPE:ADJ } tag eng_adverb:tirelessly{ MODIF_TYPE:ADJ } tag eng_adverb:tolerably{ MODIF_TYPE:ADJ } tag eng_adverb:tolerantly{ MODIF_TYPE:ADJ } tag eng_adverb:topically{ MODIF_TYPE:ADJ } tag eng_adverb:transitively{ MODIF_TYPE:ADJ } tag eng_adverb:transparently{ MODIF_TYPE:ADJ } tag eng_adverb:treacherously{ MODIF_TYPE:ADJ } tag eng_adverb:tremendously{ MODIF_TYPE:ADJ } tag eng_adverb:trenchantly{ MODIF_TYPE:ADJ } tag eng_adverb:tritely{ MODIF_TYPE:ADJ } tag eng_adverb:triumphantly{ MODIF_TYPE:ADJ } tag eng_adverb:trivially{ MODIF_TYPE:ADJ } tag eng_adverb:truculently{ MODIF_TYPE:ADJ } tag eng_adverb:trustfully{ MODIF_TYPE:ADJ } tag eng_adverb:typographically{ MODIF_TYPE:ADJ } tag eng_adverb:unabashedly{ MODIF_TYPE:ADJ } tag eng_adverb:unambiguously{ MODIF_TYPE:ADJ } tag eng_adverb:unanimously{ MODIF_TYPE:ADJ } tag eng_adverb:unashamedly{ MODIF_TYPE:ADJ } tag eng_adverb:unassumingly{ MODIF_TYPE:ADJ } tag eng_adverb:unawares{ MODIF_TYPE:ADJ } tag eng_adverb:unceasingly{ MODIF_TYPE:ADJ } tag eng_adverb:unceremoniously{ MODIF_TYPE:ADJ } tag eng_adverb:uncomfortably{ MODIF_TYPE:ADJ } tag eng_adverb:uncommonly{ MODIF_TYPE:ADJ } tag eng_adverb:uncomplainingly{ MODIF_TYPE:ADJ } tag eng_adverb:unconditionally{ MODIF_TYPE:ADJ } tag eng_adverb:unconsciously{ MODIF_TYPE:ADJ } tag eng_adverb:uncontrollably{ MODIF_TYPE:ADJ } tag eng_adverb:unconventionally{ MODIF_TYPE:ADJ } tag eng_adverb:unconvincingly{ MODIF_TYPE:ADJ } tag eng_adverb:uncritically{ MODIF_TYPE:ADJ } tag eng_adverb:underarm{ MODIF_TYPE:ADJ } tag eng_adverb:underhand{ MODIF_TYPE:ADJ } tag eng_adverb:undiplomatically{ MODIF_TYPE:ADJ } tag eng_adverb:uneasily{ MODIF_TYPE:ADJ } tag eng_adverb:unemotionally{ MODIF_TYPE:ADJ } tag eng_adverb:unenthusiastically{ MODIF_TYPE:ADJ } tag eng_adverb:unequally{ MODIF_TYPE:ADJ } tag eng_adverb:unequivocably{ MODIF_TYPE:ADJ } tag eng_adverb:unequivocally{ MODIF_TYPE:ADJ } tag eng_adverb:unerringly{ MODIF_TYPE:ADJ } tag eng_adverb:unethically{ MODIF_TYPE:ADJ } tag eng_adverb:unevenly{ MODIF_TYPE:ADJ } tag eng_adverb:uneventfully{ MODIF_TYPE:ADJ } tag eng_adverb:unexpectedly{ MODIF_TYPE:ADJ } tag eng_adverb:unfailingly{ MODIF_TYPE:ADJ } tag eng_adverb:unfairly{ MODIF_TYPE:ADJ } tag eng_adverb:unfaithfully{ MODIF_TYPE:ADJ } tag eng_adverb:unfalteringly{ MODIF_TYPE:ADJ } tag eng_adverb:unfavorably{ MODIF_TYPE:ADJ } tag eng_adverb:unfavourably{ MODIF_TYPE:ADJ } tag eng_adverb:unfeelingly{ MODIF_TYPE:ADJ } tag eng_adverb:unflinchingly{ MODIF_TYPE:ADJ } tag eng_adverb:unforgivably{ MODIF_TYPE:ADJ } tag eng_adverb:ungraciously{ MODIF_TYPE:ADJ } tag eng_adverb:ungrammatically{ MODIF_TYPE:ADJ } tag eng_adverb:ungratefully{ MODIF_TYPE:ADJ } tag eng_adverb:ungrudgingly{ MODIF_TYPE:ADJ } tag eng_adverb:unhappily{ MODIF_TYPE:ADJ } tag eng_adverb:unhelpfully{ MODIF_TYPE:ADJ } tag eng_adverb:unhesitatingly{ MODIF_TYPE:ADJ } tag eng_adverb:unhurriedly{ MODIF_TYPE:ADJ } tag eng_adverb:uniformly{ MODIF_TYPE:ADJ } tag eng_adverb:unilaterally{ MODIF_TYPE:ADJ } tag eng_adverb:unimaginatively{ MODIF_TYPE:ADJ } tag eng_adverb:unimpressively{ MODIF_TYPE:ADJ } tag eng_adverb:unintelligibly{ MODIF_TYPE:ADJ } tag eng_adverb:unintentionally{ MODIF_TYPE:ADJ } tag eng_adverb:uninterruptedly{ MODIF_TYPE:ADJ } tag eng_adverb:uniquely{ MODIF_TYPE:ADJ } tag eng_adverb:unjustifiably{ MODIF_TYPE:ADJ } tag eng_adverb:unjustly{ MODIF_TYPE:ADJ } tag eng_adverb:unknowingly{ MODIF_TYPE:ADJ } tag eng_adverb:unlawfully{ MODIF_TYPE:ADJ } tag eng_adverb:unmusically{ MODIF_TYPE:ADJ } tag eng_adverb:unnecessarily{ MODIF_TYPE:ADJ } tag eng_adverb:unobtrusively{ MODIF_TYPE:ADJ } tag eng_adverb:unpleasantly{ MODIF_TYPE:ADJ } tag eng_adverb:unreliably{ MODIF_TYPE:ADJ } tag eng_adverb:unreservedly{ MODIF_TYPE:ADJ } tag eng_adverb:unsatisfactorily{ MODIF_TYPE:ADJ } tag eng_adverb:unscientifically{ MODIF_TYPE:ADJ } tag eng_adverb:unscrupulously{ MODIF_TYPE:ADJ } tag eng_adverb:unseasonably{ MODIF_TYPE:ADJ } tag eng_adverb:seasonably{ MODIF_TYPE:ADJ } tag eng_adverb:unselfconsciously{ MODIF_TYPE:ADJ } tag eng_adverb:unselfishly{ MODIF_TYPE:ADJ } tag eng_adverb:unsparingly{ MODIF_TYPE:ADJ } tag eng_adverb:unsuccessfully{ MODIF_TYPE:ADJ } tag eng_adverb:unsurprisingly{ MODIF_TYPE:ADJ } tag eng_adverb:unsuspectingly{ MODIF_TYPE:ADJ } tag eng_adverb:unthinkingly{ MODIF_TYPE:ADJ } tag eng_adverb:untruthfully{ MODIF_TYPE:ADJ } tag eng_adverb:unwaveringly{ MODIF_TYPE:ADJ } tag eng_adverb:unwillingly{ MODIF_TYPE:ADJ } tag eng_adverb:unwisely{ MODIF_TYPE:ADJ } tag eng_adverb:unwittingly{ MODIF_TYPE:ADJ } tag eng_adverb:uphill{ MODIF_TYPE:ADJ } tag eng_adverb:upright{ MODIF_TYPE:ADJ } tag eng_adverb:uproariously{ MODIF_TYPE:ADJ } tag eng_adverb:upstage{ MODIF_TYPE:ADJ } tag eng_adverb:upwardly{ MODIF_TYPE:ADJ } tag eng_adverb:urbanely{ MODIF_TYPE:ADJ } tag eng_adverb:urgently{ MODIF_TYPE:ADJ } tag eng_adverb:vacantly{ MODIF_TYPE:ADJ } tag eng_adverb:vaguely{ MODIF_TYPE:ADJ } tag eng_adverb:vainly{ MODIF_TYPE:ADJ } tag eng_adverb:valiantly{ MODIF_TYPE:ADJ } tag eng_adverb:variously{ MODIF_TYPE:ADJ } tag eng_adverb:varyingly{ MODIF_TYPE:ADJ } tag eng_adverb:vastly{ MODIF_TYPE:ADJ } tag eng_adverb:vehemently{ MODIF_TYPE:ADJ } tag eng_adverb:venomously{ MODIF_TYPE:ADJ } tag eng_adverb:verbally{ MODIF_TYPE:ADJ } tag eng_adverb:verbosely{ MODIF_TYPE:ADJ } tag eng_adverb:vertically{ MODIF_TYPE:ADJ } tag eng_adverb:vibrantly{ MODIF_TYPE:ADJ } tag eng_adverb:vicariously{ MODIF_TYPE:ADJ } tag eng_adverb:viciously{ MODIF_TYPE:ADJ } tag eng_adverb:victoriously{ MODIF_TYPE:ADJ } tag eng_adverb:vigilantly{ MODIF_TYPE:ADJ } tag eng_adverb:vigorously{ MODIF_TYPE:ADJ } tag eng_adverb:vindictively{ MODIF_TYPE:ADJ } tag eng_adverb:violently{ MODIF_TYPE:ADJ } tag eng_adverb:virtuously{ MODIF_TYPE:ADJ } tag eng_adverb:virulently{ MODIF_TYPE:ADJ } tag eng_adverb:visibly{ MODIF_TYPE:ADJ } tag eng_adverb:visually{ MODIF_TYPE:ADJ } tag eng_adverb:vivace{ MODIF_TYPE:ADJ } tag eng_adverb:vivaciously{ MODIF_TYPE:ADJ } tag eng_adverb:vividly{ MODIF_TYPE:ADJ } tag eng_adverb:vocally{ MODIF_TYPE:ADJ } tag eng_adverb:vociferously{ MODIF_TYPE:ADJ } tag eng_adverb:voraciously{ MODIF_TYPE:ADJ } tag eng_adverb:vulgarly{ MODIF_TYPE:ADJ } tag eng_adverb:wanly{ MODIF_TYPE:ADJ } tag eng_adverb:warily{ MODIF_TYPE:ADJ } tag eng_adverb:warmly{ MODIF_TYPE:ADJ } tag eng_adverb:weakly{ MODIF_TYPE:ADJ } tag eng_adverb:wearily{ MODIF_TYPE:ADJ } tag eng_adverb:weirdly{ MODIF_TYPE:ADJ } tag eng_adverb:westwards{ MODIF_TYPE:ADJ } tag eng_adverb:whereabout{ MODIF_TYPE:ADJ } tag eng_adverb:whereabouts{ MODIF_TYPE:ADJ } tag eng_adverb:whimsically{ MODIF_TYPE:ADJ } tag eng_adverb:wholeheartedly{ MODIF_TYPE:ADJ } tag eng_adverb:wickedly{ MODIF_TYPE:ADJ } tag eng_adverb:wildly{ MODIF_TYPE:ADJ } tag eng_adverb:wilfully{ MODIF_TYPE:ADJ } tag eng_adverb:willingly{ MODIF_TYPE:ADJ } tag eng_adverb:wisely{ MODIF_TYPE:ADJ } tag eng_adverb:wistfully{ MODIF_TYPE:ADJ } tag eng_adverb:woefully{ MODIF_TYPE:ADJ } tag eng_adverb:wonderfully{ MODIF_TYPE:ADJ } tag eng_adverb:worriedly{ MODIF_TYPE:ADJ } tag eng_adverb:wrongfully{ MODIF_TYPE:ADJ } tag eng_adverb:wrong-headedly{ MODIF_TYPE:ADJ } tag eng_adverb:wrongly{ MODIF_TYPE:ADJ } tag eng_adverb:wryly{ MODIF_TYPE:ADJ } tag eng_adverb:yearningly{ MODIF_TYPE:ADJ } tag eng_adverb:zealously{ MODIF_TYPE:ADJ } tag eng_adverb:zestfully{ MODIF_TYPE:ADJ } tag eng_adverb:differently{ MODIF_TYPE:ADJ } tag eng_adverb:independently{ MODIF_TYPE:ADJ } tag eng_adverb:too{ MODIF_TYPE:ADJ } tag eng_adverb:aberrantly{ MODIF_TYPE:ADJ } tag eng_adverb:abstractly{ MODIF_TYPE:ADJ } tag eng_adverb:acceptably{ MODIF_TYPE:ADJ } tag eng_adverb:acoustically{ MODIF_TYPE:ADJ } tag eng_adverb:acronymically{ MODIF_TYPE:ADJ } tag eng_adverb:actinically{ MODIF_TYPE:ADJ } tag eng_adverb:adaptively{ MODIF_TYPE:ADJ } tag eng_adverb:additively{ MODIF_TYPE:ADJ } tag eng_adverb:adjectively{ MODIF_TYPE:ADJ } tag eng_adverb:adjunctively{ MODIF_TYPE:ADJ } tag eng_adverb:ad nauseam{ MODIF_TYPE:ADJ } tag eng_adverb:adoptively{ MODIF_TYPE:ADJ } tag eng_adverb:adventitiously{ MODIF_TYPE:ADJ } tag eng_adverb:aerobically{ MODIF_TYPE:ADJ } tag eng_adverb:affectively{ MODIF_TYPE:ADJ } tag eng_adverb:affirmatively{ MODIF_TYPE:ADJ } tag eng_adverb:affordably{ MODIF_TYPE:ADJ } tag eng_adverb:agonistically{ MODIF_TYPE:ADJ } tag eng_adverb:algorithmically{ MODIF_TYPE:ADJ } tag eng_adverb:allosterically{ MODIF_TYPE:ADJ } tag eng_adverb:alphanumerically{ MODIF_TYPE:ADJ } tag eng_adverb:anaerobically{ MODIF_TYPE:ADJ } tag eng_adverb:anecdotally{ MODIF_TYPE:ADJ } tag eng_adverb:aneurysmally{ MODIF_TYPE:ADJ } tag eng_adverb:angiographically{ MODIF_TYPE:ADJ } tag eng_adverb:anionically{ MODIF_TYPE:ADJ } tag eng_adverb:anomalously{ MODIF_TYPE:ADJ } tag eng_adverb:antagonistically{ MODIF_TYPE:ADJ } tag eng_adverb:antenatally{ MODIF_TYPE:ADJ } tag eng_adverb:anteriorly{ MODIF_TYPE:ADJ } tag eng_adverb:anterogradely{ MODIF_TYPE:ADJ } tag eng_adverb:anteroposteriorly{ MODIF_TYPE:ADJ } tag eng_adverb:anthropometrically{ MODIF_TYPE:ADJ } tag eng_adverb:anthropomorphically{ MODIF_TYPE:ADJ } tag eng_adverb:antidromically{ MODIF_TYPE:ADJ } tag eng_adverb:antigenically{ MODIF_TYPE:ADJ } tag eng_adverb:antithetically{ MODIF_TYPE:ADJ } tag eng_adverb:antivirally{ MODIF_TYPE:ADJ } tag eng_adverb:any time{ MODIF_TYPE:ADJ } tag eng_adverb:apically{ MODIF_TYPE:ADJ } tag eng_adverb:archaeologically{ MODIF_TYPE:ADJ } tag eng_adverb:artefactually{ MODIF_TYPE:ADJ } tag eng_adverb:asynchronously{ MODIF_TYPE:ADJ } tag eng_adverb:atomistically{ MODIF_TYPE:ADJ } tag eng_adverb:attentionally{ MODIF_TYPE:ADJ } tag eng_adverb:audiovisually{ MODIF_TYPE:ADJ } tag eng_adverb:aurally{ MODIF_TYPE:ADJ } tag eng_adverb:autocatalytically{ MODIF_TYPE:ADJ } tag eng_adverb:autogenously{ MODIF_TYPE:ADJ } tag eng_adverb:autonomically{ MODIF_TYPE:ADJ } tag eng_adverb:autonomously{ MODIF_TYPE:ADJ } tag eng_adverb:autosomally{ MODIF_TYPE:ADJ } tag eng_adverb:autotrophically{ MODIF_TYPE:ADJ } tag eng_adverb:averagely{ MODIF_TYPE:ADJ } tag eng_adverb:axenically{ MODIF_TYPE:ADJ } tag eng_adverb:biannually{ MODIF_TYPE:ADJ } tag eng_adverb:bibliographically{ MODIF_TYPE:ADJ } tag eng_adverb:bidimensionally{ MODIF_TYPE:ADJ } tag eng_adverb:bifunctionally{ MODIF_TYPE:ADJ } tag eng_adverb:bimodally{ MODIF_TYPE:ADJ } tag eng_adverb:binocularly{ MODIF_TYPE:ADJ } tag eng_adverb:biomechanically{ MODIF_TYPE:ADJ } tag eng_adverb:biomedically{ MODIF_TYPE:ADJ } tag eng_adverb:biometrically{ MODIF_TYPE:ADJ } tag eng_adverb:biophysically{ MODIF_TYPE:ADJ } tag eng_adverb:biosynthetically{ MODIF_TYPE:ADJ } tag eng_adverb:biphasically{ MODIF_TYPE:ADJ } tag eng_adverb:bronchoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:calorimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:canonically{ MODIF_TYPE:ADJ } tag eng_adverb:cartographically{ MODIF_TYPE:ADJ } tag eng_adverb:catalytically{ MODIF_TYPE:ADJ } tag eng_adverb:catastrophically{ MODIF_TYPE:ADJ } tag eng_adverb:caudally{ MODIF_TYPE:ADJ } tag eng_adverb:cellularly{ MODIF_TYPE:ADJ } tag eng_adverb:centrifugally{ MODIF_TYPE:ADJ } tag eng_adverb:cheerlessly{ MODIF_TYPE:ADJ } tag eng_adverb:cholinergically{ MODIF_TYPE:ADJ } tag eng_adverb:chromatographically{ MODIF_TYPE:ADJ } tag eng_adverb:chromosomally{ MODIF_TYPE:ADJ } tag eng_adverb:cinematographically{ MODIF_TYPE:ADJ } tag eng_adverb:circularly{ MODIF_TYPE:ADJ } tag eng_adverb:circumferentially{ MODIF_TYPE:ADJ } tag eng_adverb:circumstantially{ MODIF_TYPE:ADJ } tag eng_adverb:cladistically{ MODIF_TYPE:ADJ } tag eng_adverb:clinicopathologically{ MODIF_TYPE:ADJ } tag eng_adverb:clonally{ MODIF_TYPE:ADJ } tag eng_adverb:advantageously{ MODIF_TYPE:ADJ } tag eng_adverb:abdominally{ MODIF_TYPE:ADJ } tag eng_adverb:anally{ MODIF_TYPE:ADJ } tag eng_adverb:ante meridiem{ MODIF_TYPE:ADJ } tag eng_adverb:anteromedially{ MODIF_TYPE:ADJ } tag eng_adverb:arterially{ MODIF_TYPE:ADJ } tag eng_adverb:axially{ MODIF_TYPE:ADJ } tag eng_adverb:buccally{ MODIF_TYPE:ADJ } tag eng_adverb:buccolingually{ MODIF_TYPE:ADJ } tag eng_adverb:cardiovascularly{ MODIF_TYPE:ADJ } tag eng_adverb:centroparietally{ MODIF_TYPE:ADJ } tag eng_adverb:centrotemporally{ MODIF_TYPE:ADJ } tag eng_adverb:contiguously{ MODIF_TYPE:ADJ } tag eng_adverb:cutaneously{ MODIF_TYPE:ADJ } tag eng_adverb:dermally{ MODIF_TYPE:ADJ } tag eng_adverb:dorso-ventrally{ MODIF_TYPE:ADJ } tag eng_adverb:ectodermally{ MODIF_TYPE:ADJ } tag eng_adverb:endotracheally{ MODIF_TYPE:ADJ } tag eng_adverb:epithelially{ MODIF_TYPE:ADJ } tag eng_adverb:extradurally{ MODIF_TYPE:ADJ } tag eng_adverb:extrahepatically{ MODIF_TYPE:ADJ } tag eng_adverb:incisionally{ MODIF_TYPE:ADJ } tag eng_adverb:inferolaterally{ MODIF_TYPE:ADJ } tag eng_adverb:inferoposteriorly{ MODIF_TYPE:ADJ } tag eng_adverb:inferotemporally{ MODIF_TYPE:ADJ } tag eng_adverb:intercellularly{ MODIF_TYPE:ADJ } tag eng_adverb:interfollicularly{ MODIF_TYPE:ADJ } tag eng_adverb:interictally{ MODIF_TYPE:ADJ } tag eng_adverb:intermolecularly{ MODIF_TYPE:ADJ } tag eng_adverb:interoinferiorly{ MODIF_TYPE:ADJ } tag eng_adverb:intestinally{ MODIF_TYPE:ADJ } tag eng_adverb:intra-abdominally{ MODIF_TYPE:ADJ } tag eng_adverb:intra-amniotically{ MODIF_TYPE:ADJ } tag eng_adverb:intra-arterially{ MODIF_TYPE:ADJ } tag eng_adverb:intra-atrially{ MODIF_TYPE:ADJ } tag eng_adverb:intracellularly{ MODIF_TYPE:ADJ } tag eng_adverb:intracerebroventricularly{ MODIF_TYPE:ADJ } tag eng_adverb:intradermally{ MODIF_TYPE:ADJ } tag eng_adverb:intragastrically{ MODIF_TYPE:ADJ } tag eng_adverb:intralymphatically{ MODIF_TYPE:ADJ } tag eng_adverb:intralymphocytically{ MODIF_TYPE:ADJ } tag eng_adverb:intramolecularly{ MODIF_TYPE:ADJ } tag eng_adverb:intramuscularly{ MODIF_TYPE:ADJ } tag eng_adverb:intranasally{ MODIF_TYPE:ADJ } tag eng_adverb:intraneuronally{ MODIF_TYPE:ADJ } tag eng_adverb:intraocularly{ MODIF_TYPE:ADJ } tag eng_adverb:intraorganically{ MODIF_TYPE:ADJ } tag eng_adverb:intraperitonally{ MODIF_TYPE:ADJ } tag eng_adverb:intraperitoneally{ MODIF_TYPE:ADJ } tag eng_adverb:intrapleurally{ MODIF_TYPE:ADJ } tag eng_adverb:intrathecally{ MODIF_TYPE:ADJ } tag eng_adverb:intravascularly{ MODIF_TYPE:ADJ } tag eng_adverb:intravitreally{ MODIF_TYPE:ADJ } tag eng_adverb:labially{ MODIF_TYPE:ADJ } tag eng_adverb:lingually{ MODIF_TYPE:ADJ } tag eng_adverb:linguoapically{ MODIF_TYPE:ADJ } tag eng_adverb:medially{ MODIF_TYPE:ADJ } tag eng_adverb:mesially{ MODIF_TYPE:ADJ } tag eng_adverb:mesothoracically{ MODIF_TYPE:ADJ } tag eng_adverb:neonatally{ MODIF_TYPE:ADJ } tag eng_adverb:neurally{ MODIF_TYPE:ADJ } tag eng_adverb:neuroectodermally{ MODIF_TYPE:ADJ } tag eng_adverb:nonsimultaneously{ MODIF_TYPE:ADJ } tag eng_adverb:peripherally{ MODIF_TYPE:ADJ } tag eng_adverb:pertrochanterically{ MODIF_TYPE:ADJ } tag eng_adverb:postanoxically{ MODIF_TYPE:ADJ } tag eng_adverb:postbulbarly{ MODIF_TYPE:ADJ } tag eng_adverb:posteriorly{ MODIF_TYPE:ADJ } tag eng_adverb:postero-anteriorly{ MODIF_TYPE:ADJ } tag eng_adverb:postsynaptically{ MODIF_TYPE:ADJ } tag eng_adverb:presynaptically{ MODIF_TYPE:ADJ } tag eng_adverb:proximally{ MODIF_TYPE:ADJ } tag eng_adverb:subcutaneously{ MODIF_TYPE:ADJ } tag eng_adverb:subdermally{ MODIF_TYPE:ADJ } tag eng_adverb:supraaortically{ MODIF_TYPE:ADJ } tag eng_adverb:suprabasally{ MODIF_TYPE:ADJ } tag eng_adverb:suprapubically{ MODIF_TYPE:ADJ } tag eng_adverb:thereto{ MODIF_TYPE:ADJ } tag eng_adverb:transversely{ MODIF_TYPE:ADJ } //tag eng_adverb:up and down{ MODIF_TYPE:ADJ } tag eng_adverb:ventrally{ MODIF_TYPE:ADJ } tag eng_adverb:aetiopathogenetically{ MODIF_TYPE:ADJ } tag eng_adverb:agricuturally{ MODIF_TYPE:ADJ } tag eng_adverb:cytochemically{ MODIF_TYPE:ADJ } tag eng_adverb:esthetically{ MODIF_TYPE:ADJ } tag eng_adverb:ethnoculturally{ MODIF_TYPE:ADJ } tag eng_adverb:overridingly{ MODIF_TYPE:ADJ } tag eng_adverb:pathogenetically{ MODIF_TYPE:ADJ } tag eng_adverb:priestly{ MODIF_TYPE:ADJ } tag eng_adverb:pseudomorphically{ MODIF_TYPE:ADJ } tag eng_adverb:psionically{ MODIF_TYPE:ADJ } tag eng_adverb:revolutionally{ MODIF_TYPE:ADJ } tag eng_adverb:abluminally{ MODIF_TYPE:ADJ } tag eng_adverb:a capite ad calcem{ MODIF_TYPE:ADJ } tag eng_adverb:accelographically{ MODIF_TYPE:ADJ } tag eng_adverb:acrosomally{ MODIF_TYPE:ADJ } tag eng_adverb:adaptometrically{ MODIF_TYPE:ADJ } tag eng_adverb:adenovirally{ MODIF_TYPE:ADJ } tag eng_adverb:adrenergically{ MODIF_TYPE:ADJ } tag eng_adverb:aesthesiometrically{ MODIF_TYPE:ADJ } tag eng_adverb:aetiologically{ MODIF_TYPE:ADJ } tag eng_adverb:agee{ MODIF_TYPE:ADJ } tag eng_adverb:allergologically{ MODIF_TYPE:ADJ } tag eng_adverb:allometrically{ MODIF_TYPE:ADJ } tag eng_adverb:allotopically{ MODIF_TYPE:ADJ } tag eng_adverb:amblyoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:amnioscopically{ MODIF_TYPE:ADJ } tag eng_adverb:amperometrically{ MODIF_TYPE:ADJ } tag eng_adverb:amphotropically{ MODIF_TYPE:ADJ } tag eng_adverb:anesthaesiologically{ MODIF_TYPE:ADJ } tag eng_adverb:anesthesiologically{ MODIF_TYPE:ADJ } tag eng_adverb:angiodynographically{ MODIF_TYPE:ADJ } tag eng_adverb:angiologically{ MODIF_TYPE:ADJ } tag eng_adverb:angioscopically{ MODIF_TYPE:ADJ } tag eng_adverb:angiospirometrically{ MODIF_TYPE:ADJ } tag eng_adverb:ante cibum{ MODIF_TYPE:ADJ } tag eng_adverb:anomaloscopically{ MODIF_TYPE:ADJ } tag eng_adverb:antero-inferiorly{ MODIF_TYPE:ADJ } tag eng_adverb:anteroinferiorly{ MODIF_TYPE:ADJ } tag eng_adverb:antero-posteriorly{ MODIF_TYPE:ADJ } tag eng_adverb:antero-superiorly{ MODIF_TYPE:ADJ } tag eng_adverb:anterosuperiorly{ MODIF_TYPE:ADJ } tag eng_adverb:aortographically{ MODIF_TYPE:ADJ } tag eng_adverb:arteriographically{ MODIF_TYPE:ADJ } tag eng_adverb:arteriometrically{ MODIF_TYPE:ADJ } tag eng_adverb:arterioscopically{ MODIF_TYPE:ADJ } tag eng_adverb:arthrographically{ MODIF_TYPE:ADJ } tag eng_adverb:arthrometrically{ MODIF_TYPE:ADJ } tag eng_adverb:arthroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:artifactually{ MODIF_TYPE:ADJ } tag eng_adverb:asymptomatically{ MODIF_TYPE:ADJ } tag eng_adverb:autoradiographically{ MODIF_TYPE:ADJ } tag eng_adverb:auscultoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:atraumatically{ MODIF_TYPE:ADJ } tag eng_adverb:ataxiagraphically{ MODIF_TYPE:ADJ } tag eng_adverb:auditorily{ MODIF_TYPE:ADJ } tag eng_adverb:aversively{ MODIF_TYPE:ADJ } tag eng_adverb:axonally{ MODIF_TYPE:ADJ } tag eng_adverb:bacterially{ MODIF_TYPE:ADJ } tag eng_adverb:bacteriologically{ MODIF_TYPE:ADJ } tag eng_adverb:baculovirally{ MODIF_TYPE:ADJ } tag eng_adverb:balefully{ MODIF_TYPE:ADJ } tag eng_adverb:ballistocardiographically{ MODIF_TYPE:ADJ } tag eng_adverb:basally{ MODIF_TYPE:ADJ } tag eng_adverb:basolaterally{ MODIF_TYPE:ADJ } tag eng_adverb:bimanually{ MODIF_TYPE:ADJ } tag eng_adverb:bioptically{ MODIF_TYPE:ADJ } tag eng_adverb:bioreductively{ MODIF_TYPE:ADJ } tag eng_adverb:biospecifically{ MODIF_TYPE:ADJ } tag eng_adverb:bivariately{ MODIF_TYPE:ADJ } tag eng_adverb:bronchospirometrically{ MODIF_TYPE:ADJ } tag eng_adverb:capillaroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:capnographically{ MODIF_TYPE:ADJ } tag eng_adverb:capnometrically{ MODIF_TYPE:ADJ } tag eng_adverb:cardiodynametrically{ MODIF_TYPE:ADJ } tag eng_adverb:cardiointegraphically{ MODIF_TYPE:ADJ } tag eng_adverb:cardiologically{ MODIF_TYPE:ADJ } tag eng_adverb:cardiophonically{ MODIF_TYPE:ADJ } tag eng_adverb:cardioscopically{ MODIF_TYPE:ADJ } tag eng_adverb:cardiotocographically{ MODIF_TYPE:ADJ } tag eng_adverb:cataclysmally{ MODIF_TYPE:ADJ } tag eng_adverb:cavographically{ MODIF_TYPE:ADJ } tag eng_adverb:centrifugationally{ MODIF_TYPE:ADJ } tag eng_adverb:centripetally{ MODIF_TYPE:ADJ } tag eng_adverb:centrosymmetrically{ MODIF_TYPE:ADJ } tag eng_adverb:chemotactically{ MODIF_TYPE:ADJ } tag eng_adverb:chemotaxonomically{ MODIF_TYPE:ADJ } tag eng_adverb:chemotrophically{ MODIF_TYPE:ADJ } tag eng_adverb:chirally{ MODIF_TYPE:ADJ } tag eng_adverb:chloridometrically{ MODIF_TYPE:ADJ } tag eng_adverb:cholangiographically{ MODIF_TYPE:ADJ } tag eng_adverb:cholangioscopically{ MODIF_TYPE:ADJ } tag eng_adverb:cholecystographically{ MODIF_TYPE:ADJ } tag eng_adverb:choledochoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:chromoradiometrically{ MODIF_TYPE:ADJ } tag eng_adverb:chronometrically{ MODIF_TYPE:ADJ } tag eng_adverb:chronomyometrically{ MODIF_TYPE:ADJ } tag eng_adverb:chronotropically{ MODIF_TYPE:ADJ } tag eng_adverb:cineangiographically{ MODIF_TYPE:ADJ } tag eng_adverb:cinefluoroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:cineradiographically{ MODIF_TYPE:ADJ } tag eng_adverb:clonotypically{ MODIF_TYPE:ADJ } tag eng_adverb:coagulantly{ MODIF_TYPE:ADJ } tag eng_adverb:coaxially{ MODIF_TYPE:ADJ } tag eng_adverb:coincidently{ MODIF_TYPE:ADJ } tag eng_adverb:cold-bloodedly{ MODIF_TYPE:ADJ } tag eng_adverb:cold-heartedly{ MODIF_TYPE:ADJ } tag eng_adverb:collaboratively{ MODIF_TYPE:ADJ } tag eng_adverb:collegially{ MODIF_TYPE:ADJ } tag eng_adverb:colonoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:colorimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:colposcopically{ MODIF_TYPE:ADJ } tag eng_adverb:combinatorially{ MODIF_TYPE:ADJ } tag eng_adverb:compactly{ MODIF_TYPE:ADJ } tag eng_adverb:compimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:complementarily{ MODIF_TYPE:ADJ } tag eng_adverb:complexly{ MODIF_TYPE:ADJ } tag eng_adverb:concentrically{ MODIF_TYPE:ADJ } tag eng_adverb:concertedly{ MODIF_TYPE:ADJ } tag eng_adverb:concomitantly{ MODIF_TYPE:ADJ } tag eng_adverb:concordantly{ MODIF_TYPE:ADJ } tag eng_adverb:conformally{ MODIF_TYPE:ADJ } tag eng_adverb:conformationally{ MODIF_TYPE:ADJ } tag eng_adverb:congenitally{ MODIF_TYPE:ADJ } tag eng_adverb:conjointly{ MODIF_TYPE:ADJ } tag eng_adverb:consensually{ MODIF_TYPE:ADJ } tag eng_adverb:constitutively{ MODIF_TYPE:ADJ } tag eng_adverb:contourographically{ MODIF_TYPE:ADJ } tag eng_adverb:contralaterally{ MODIF_TYPE:ADJ } tag eng_adverb:convergently{ MODIF_TYPE:ADJ } tag eng_adverb:convolutely{ MODIF_TYPE:ADJ } tag eng_adverb:coordinately{ MODIF_TYPE:ADJ } tag eng_adverb:coronally{ MODIF_TYPE:ADJ } tag eng_adverb:cortically{ MODIF_TYPE:ADJ } tag eng_adverb:cosmetically{ MODIF_TYPE:ADJ } tag eng_adverb:cotranslationally{ MODIF_TYPE:ADJ } tag eng_adverb:coulometrically{ MODIF_TYPE:ADJ } tag eng_adverb:covalently{ MODIF_TYPE:ADJ } tag eng_adverb:cross-reactively{ MODIF_TYPE:ADJ } tag eng_adverb:crossreactively{ MODIF_TYPE:ADJ } tag eng_adverb:cross sectionally{ MODIF_TYPE:ADJ } tag eng_adverb:cross-sectionally{ MODIF_TYPE:ADJ } tag eng_adverb:cryometrically{ MODIF_TYPE:ADJ } tag eng_adverb:crystallographically{ MODIF_TYPE:ADJ } tag eng_adverb:curatively{ MODIF_TYPE:ADJ } tag eng_adverb:curvilinearly{ MODIF_TYPE:ADJ } tag eng_adverb:cyclically{ MODIF_TYPE:ADJ } tag eng_adverb:cyclonically{ MODIF_TYPE:ADJ } tag eng_adverb:cystically{ MODIF_TYPE:ADJ } tag eng_adverb:cystometrically{ MODIF_TYPE:ADJ } tag eng_adverb:cystoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:cystourethroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:cyto-architecturally{ MODIF_TYPE:ADJ } tag eng_adverb:cytoarchitecturally{ MODIF_TYPE:ADJ } tag eng_adverb:cytofluorimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:cytofluorographically{ MODIF_TYPE:ADJ } tag eng_adverb:cytogenetically{ MODIF_TYPE:ADJ } tag eng_adverb:cytologically{ MODIF_TYPE:ADJ } tag eng_adverb:cytometrically{ MODIF_TYPE:ADJ } tag eng_adverb:cytomorphologically{ MODIF_TYPE:ADJ } tag eng_adverb:cytopathologically{ MODIF_TYPE:ADJ } tag eng_adverb:cytophotometrically{ MODIF_TYPE:ADJ } tag eng_adverb:cytoplasmically{ MODIF_TYPE:ADJ } tag eng_adverb:cytotoxically{ MODIF_TYPE:ADJ } tag eng_adverb:definitively{ MODIF_TYPE:ADJ } tag eng_adverb:deleteriously{ MODIF_TYPE:ADJ } tag eng_adverb:demographically{ MODIF_TYPE:ADJ } tag eng_adverb:de novo{ MODIF_TYPE:ADJ } tag eng_adverb:densitometrically{ MODIF_TYPE:ADJ } tag eng_adverb:dependantly{ MODIF_TYPE:ADJ } tag eng_adverb:dependently{ MODIF_TYPE:ADJ } tag eng_adverb:dermatoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:despitefully{ MODIF_TYPE:ADJ } tag eng_adverb:desultorily{ MODIF_TYPE:ADJ } tag eng_adverb:detectably{ MODIF_TYPE:ADJ } tag eng_adverb:deterministically{ MODIF_TYPE:ADJ } tag eng_adverb:developmentally{ MODIF_TYPE:ADJ } tag eng_adverb:diagnosably{ MODIF_TYPE:ADJ } tag eng_adverb:diagnostically{ MODIF_TYPE:ADJ } tag eng_adverb:dialectically{ MODIF_TYPE:ADJ } tag eng_adverb:dialytically{ MODIF_TYPE:ADJ } tag eng_adverb:diastereomerically{ MODIF_TYPE:ADJ } tag eng_adverb:dichotomously{ MODIF_TYPE:ADJ } tag eng_adverb:dihedrally{ MODIF_TYPE:ADJ } tag eng_adverb:dilatometrically{ MODIF_TYPE:ADJ } tag eng_adverb:dimensionally{ MODIF_TYPE:ADJ } tag eng_adverb:diopsimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:dioptometrically{ MODIF_TYPE:ADJ } tag eng_adverb:diplopiometrically{ MODIF_TYPE:ADJ } tag eng_adverb:directionally{ MODIF_TYPE:ADJ } tag eng_adverb:directoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:direfully{ MODIF_TYPE:ADJ } tag eng_adverb:discontinuously{ MODIF_TYPE:ADJ } tag eng_adverb:discordantly{ MODIF_TYPE:ADJ } tag eng_adverb:discrepantly{ MODIF_TYPE:ADJ } tag eng_adverb:disparately{ MODIF_TYPE:ADJ } tag eng_adverb:disproportionally{ MODIF_TYPE:ADJ } tag eng_adverb:disquietingly{ MODIF_TYPE:ADJ } tag eng_adverb:distally{ MODIF_TYPE:ADJ } tag eng_adverb:diurnally{ MODIF_TYPE:ADJ } tag eng_adverb:divergently{ MODIF_TYPE:ADJ } tag eng_adverb:dolorimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:dominantly{ MODIF_TYPE:ADJ } tag eng_adverb:dorsally{ MODIF_TYPE:ADJ } tag eng_adverb:dorsoventrally{ MODIF_TYPE:ADJ } tag eng_adverb:dosimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:dually{ MODIF_TYPE:ADJ } tag eng_adverb:duodenoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:dyadically{ MODIF_TYPE:ADJ } tag eng_adverb:dynographically{ MODIF_TYPE:ADJ } tag eng_adverb:eccentrically{ MODIF_TYPE:ADJ } tag eng_adverb:echocardiographically{ MODIF_TYPE:ADJ } tag eng_adverb:echoencephalographically{ MODIF_TYPE:ADJ } tag eng_adverb:echographically{ MODIF_TYPE:ADJ } tag eng_adverb:echoophthalmographically{ MODIF_TYPE:ADJ } tag eng_adverb:echotomographically{ MODIF_TYPE:ADJ } tag eng_adverb:eclectically{ MODIF_TYPE:ADJ } tag eng_adverb:econometrically{ MODIF_TYPE:ADJ } tag eng_adverb:ectopically{ MODIF_TYPE:ADJ } tag eng_adverb:edematogenically{ MODIF_TYPE:ADJ } tag eng_adverb:effectually{ MODIF_TYPE:ADJ } tag eng_adverb:egomaniacally{ MODIF_TYPE:ADJ } tag eng_adverb:eikonometrically{ MODIF_TYPE:ADJ } tag eng_adverb:ektacytometrically{ MODIF_TYPE:ADJ } tag eng_adverb:electively{ MODIF_TYPE:ADJ } tag eng_adverb:electro-acoustically{ MODIF_TYPE:ADJ } tag eng_adverb:electroacoustically{ MODIF_TYPE:ADJ } tag eng_adverb:electrobasographically{ MODIF_TYPE:ADJ } //tag eng_adverb:electrocardiocontourographically{ MODIF_TYPE:ADJ } tag eng_adverb:electrocardiographically{ MODIF_TYPE:ADJ } tag eng_adverb:electrocardioscopically{ MODIF_TYPE:ADJ } tag eng_adverb:electrochemically{ MODIF_TYPE:ADJ } tag eng_adverb:electrocorticographically{ MODIF_TYPE:ADJ } //tag eng_adverb:electroencephalographically{ MODIF_TYPE:ADJ } tag eng_adverb:electroencephaloscopically{ MODIF_TYPE:ADJ } tag eng_adverb:electrogastrographically{ MODIF_TYPE:ADJ } tag eng_adverb:electroglottographically{ MODIF_TYPE:ADJ } tag eng_adverb:electrogoniometrically{ MODIF_TYPE:ADJ } tag eng_adverb:electrographically{ MODIF_TYPE:ADJ } tag eng_adverb:electrohydraulically{ MODIF_TYPE:ADJ } tag eng_adverb:electromagnetically{ MODIF_TYPE:ADJ } tag eng_adverb:electromanometrically{ MODIF_TYPE:ADJ } tag eng_adverb:electromechanically{ MODIF_TYPE:ADJ } tag eng_adverb:electromicroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:electromyographically{ MODIF_TYPE:ADJ } tag eng_adverb:electroneurographically{ MODIF_TYPE:ADJ } tag eng_adverb:electroneuromyographically{ MODIF_TYPE:ADJ } tag eng_adverb:electron-microscopically{ MODIF_TYPE:ADJ } tag eng_adverb:electronmicroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:electronystagmographically{ MODIF_TYPE:ADJ } tag eng_adverb:electrooculographically{ MODIF_TYPE:ADJ } //tag eng_adverb:electrophonocardiographically{ MODIF_TYPE:ADJ } tag eng_adverb:electrophorectically{ MODIF_TYPE:ADJ } tag eng_adverb:electrophoretically{ MODIF_TYPE:ADJ } tag eng_adverb:electrophysiologically{ MODIF_TYPE:ADJ } tag eng_adverb:electropupillographically{ MODIF_TYPE:ADJ } tag eng_adverb:electrostatically{ MODIF_TYPE:ADJ } tag eng_adverb:electrosurgically{ MODIF_TYPE:ADJ } tag eng_adverb:embryologically{ MODIF_TYPE:ADJ } tag eng_adverb:emergently{ MODIF_TYPE:ADJ } tag eng_adverb:empathetically{ MODIF_TYPE:ADJ } tag eng_adverb:empathically{ MODIF_TYPE:ADJ } tag eng_adverb:enantiomerically{ MODIF_TYPE:ADJ } tag eng_adverb:en bloc{ MODIF_TYPE:ADJ } tag eng_adverb:encephalographically{ MODIF_TYPE:ADJ } tag eng_adverb:encephaloscopically{ MODIF_TYPE:ADJ } tag eng_adverb:endobronchially{ MODIF_TYPE:ADJ } tag eng_adverb:endocrinologically{ MODIF_TYPE:ADJ } tag eng_adverb:endodontically{ MODIF_TYPE:ADJ } tag eng_adverb:endogenously{ MODIF_TYPE:ADJ } tag eng_adverb:endonasally{ MODIF_TYPE:ADJ } tag eng_adverb:endonucleolytically{ MODIF_TYPE:ADJ } tag eng_adverb:endoradiographically{ MODIF_TYPE:ADJ } tag eng_adverb:endoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:endosmotically{ MODIF_TYPE:ADJ } tag eng_adverb:endourologically{ MODIF_TYPE:ADJ } tag eng_adverb:en face{ MODIF_TYPE:ADJ } tag eng_adverb:en passant{ MODIF_TYPE:ADJ } tag eng_adverb:enterally{ MODIF_TYPE:ADJ } tag eng_adverb:enterically{ MODIF_TYPE:ADJ } tag eng_adverb:enthalpically{ MODIF_TYPE:ADJ } tag eng_adverb:entomologically{ MODIF_TYPE:ADJ } tag eng_adverb:entoptoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:entropically{ MODIF_TYPE:ADJ } tag eng_adverb:enzymatically{ MODIF_TYPE:ADJ } tag eng_adverb:enzymically{ MODIF_TYPE:ADJ } tag eng_adverb:enzymocytochemically{ MODIF_TYPE:ADJ } tag eng_adverb:epicutaneously{ MODIF_TYPE:ADJ } tag eng_adverb:epidemiologically{ MODIF_TYPE:ADJ } tag eng_adverb:episodically{ MODIF_TYPE:ADJ } tag eng_adverb:episomally{ MODIF_TYPE:ADJ } tag eng_adverb:epistatically{ MODIF_TYPE:ADJ } tag eng_adverb:equipotently{ MODIF_TYPE:ADJ } tag eng_adverb:equivalently{ MODIF_TYPE:ADJ } tag eng_adverb:equivocally{ MODIF_TYPE:ADJ } tag eng_adverb:ergometrically{ MODIF_TYPE:ADJ } tag eng_adverb:ergonomically{ MODIF_TYPE:ADJ } tag eng_adverb:ergospirometrically{ MODIF_TYPE:ADJ } tag eng_adverb:esthesiometrically{ MODIF_TYPE:ADJ } tag eng_adverb:etiologically{ MODIF_TYPE:ADJ } tag eng_adverb:etiopathogenetically{ MODIF_TYPE:ADJ } tag eng_adverb:etymologically{ MODIF_TYPE:ADJ } tag eng_adverb:evolutionally{ MODIF_TYPE:ADJ } tag eng_adverb:evolutionarily{ MODIF_TYPE:ADJ } tag eng_adverb:excisionally{ MODIF_TYPE:ADJ } tag eng_adverb:exocyclically{ MODIF_TYPE:ADJ } tag eng_adverb:exogenously{ MODIF_TYPE:ADJ } tag eng_adverb:expandingly{ MODIF_TYPE:ADJ } tag eng_adverb:expectedly{ MODIF_TYPE:ADJ } tag eng_adverb:expeditionally{ MODIF_TYPE:ADJ } tag eng_adverb:expeditionaly{ MODIF_TYPE:ADJ } tag eng_adverb:expeditiously{ MODIF_TYPE:ADJ } tag eng_adverb:expensively{ MODIF_TYPE:ADJ } tag eng_adverb:ex planta{ MODIF_TYPE:ADJ } tag eng_adverb:exploratively{ MODIF_TYPE:ADJ } tag eng_adverb:extra-cellularly{ MODIF_TYPE:ADJ } tag eng_adverb:extracellularly{ MODIF_TYPE:ADJ } tag eng_adverb:extrathymically{ MODIF_TYPE:ADJ } tag eng_adverb:ex vivo{ MODIF_TYPE:ADJ } tag eng_adverb:facultatively{ MODIF_TYPE:ADJ } tag eng_adverb:feelingly{ MODIF_TYPE:ADJ } tag eng_adverb:fenestrometrically{ MODIF_TYPE:ADJ } tag eng_adverb:ferrokinetically{ MODIF_TYPE:ADJ } tag eng_adverb:fetascopically{ MODIF_TYPE:ADJ } tag eng_adverb:fiberscopically{ MODIF_TYPE:ADJ } tag eng_adverb:figurally{ MODIF_TYPE:ADJ } tag eng_adverb:filtrometrically{ MODIF_TYPE:ADJ } tag eng_adverb:firstly{ MODIF_TYPE:ADJ } tag eng_adverb:fluorescently{ MODIF_TYPE:ADJ } tag eng_adverb:fluorimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:fluorometrically{ MODIF_TYPE:ADJ } tag eng_adverb:fluorophotometrically{ MODIF_TYPE:ADJ } tag eng_adverb:fluoroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:focally{ MODIF_TYPE:ADJ } tag eng_adverb:foetascopically{ MODIF_TYPE:ADJ } tag eng_adverb:forensically{ MODIF_TYPE:ADJ } tag eng_adverb:for ever{ MODIF_TYPE:ADJ } tag eng_adverb:fractally{ MODIF_TYPE:ADJ } tag eng_adverb:fractionally{ MODIF_TYPE:ADJ } tag eng_adverb:fragmentographically{ MODIF_TYPE:ADJ } tag eng_adverb:frictionally{ MODIF_TYPE:ADJ } tag eng_adverb:fro{ MODIF_TYPE:ADJ } tag eng_adverb:frontally{ MODIF_TYPE:ADJ } tag eng_adverb:futuristically{ MODIF_TYPE:ADJ } tag eng_adverb:gastroduodenoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:gastroenterologically{ MODIF_TYPE:ADJ } tag eng_adverb:gastrographically{ MODIF_TYPE:ADJ } tag eng_adverb:gayly{ MODIF_TYPE:ADJ } tag eng_adverb:genomically{ MODIF_TYPE:ADJ } tag eng_adverb:genotypically{ MODIF_TYPE:ADJ } tag eng_adverb:geochemically{ MODIF_TYPE:ADJ } tag eng_adverb:geomagnetically{ MODIF_TYPE:ADJ } tag eng_adverb:gerontologically{ MODIF_TYPE:ADJ } tag eng_adverb:gerontopsychiatrically{ MODIF_TYPE:ADJ } tag eng_adverb:gestationally{ MODIF_TYPE:ADJ } tag eng_adverb:gesturally{ MODIF_TYPE:ADJ } tag eng_adverb:gingivally{ MODIF_TYPE:ADJ } tag eng_adverb:glucometrically{ MODIF_TYPE:ADJ } tag eng_adverb:glycosidically{ MODIF_TYPE:ADJ } tag eng_adverb:goniometrically{ MODIF_TYPE:ADJ } tag eng_adverb:gonioscopically{ MODIF_TYPE:ADJ } tag eng_adverb:gravitationally{ MODIF_TYPE:ADJ } tag eng_adverb:gustometrically{ MODIF_TYPE:ADJ } tag eng_adverb:gynecologically{ MODIF_TYPE:ADJ } tag eng_adverb:haemacytometrically{ MODIF_TYPE:ADJ } tag eng_adverb:haematofluorometrically{ MODIF_TYPE:ADJ } tag eng_adverb:haematologically{ MODIF_TYPE:ADJ } tag eng_adverb:haematopoetically{ MODIF_TYPE:ADJ } tag eng_adverb:haematopoietically{ MODIF_TYPE:ADJ } tag eng_adverb:haemodynamically{ MODIF_TYPE:ADJ } tag eng_adverb:haemoglobinometrically{ MODIF_TYPE:ADJ } tag eng_adverb:haemolytically{ MODIF_TYPE:ADJ } tag eng_adverb:haemorheologically{ MODIF_TYPE:ADJ } tag eng_adverb:haemorrheologically{ MODIF_TYPE:ADJ } tag eng_adverb:haemostatically{ MODIF_TYPE:ADJ } tag eng_adverb:half-maximally{ MODIF_TYPE:ADJ } tag eng_adverb:halfmaximally{ MODIF_TYPE:ADJ } tag eng_adverb:hand to knee{ MODIF_TYPE:ADJ } tag eng_adverb:haptically{ MODIF_TYPE:ADJ } tag eng_adverb:harmlessly{ MODIF_TYPE:ADJ } tag eng_adverb:head first{ MODIF_TYPE:ADJ } tag eng_adverb:head-first{ MODIF_TYPE:ADJ } tag eng_adverb:headfirst{ MODIF_TYPE:ADJ } tag eng_adverb:heedfully{ MODIF_TYPE:ADJ } tag eng_adverb:heedlessly{ MODIF_TYPE:ADJ } tag eng_adverb:heel to knee{ MODIF_TYPE:ADJ } tag eng_adverb:helically{ MODIF_TYPE:ADJ } tag eng_adverb:hemacytometrically{ MODIF_TYPE:ADJ } tag eng_adverb:hematofluorometrically{ MODIF_TYPE:ADJ } tag eng_adverb:hematologically{ MODIF_TYPE:ADJ } tag eng_adverb:hematopoetically{ MODIF_TYPE:ADJ } tag eng_adverb:hematopoietically{ MODIF_TYPE:ADJ } tag eng_adverb:hemodynamically{ MODIF_TYPE:ADJ } tag eng_adverb:hemoglobinometrically{ MODIF_TYPE:ADJ } tag eng_adverb:hemolytically{ MODIF_TYPE:ADJ } tag eng_adverb:hemorheologically{ MODIF_TYPE:ADJ } tag eng_adverb:hemorrheologically{ MODIF_TYPE:ADJ } tag eng_adverb:hemostatically{ MODIF_TYPE:ADJ } tag eng_adverb:hepatically{ MODIF_TYPE:ADJ } tag eng_adverb:hereof{ MODIF_TYPE:ADJ } tag eng_adverb:hereto{ MODIF_TYPE:ADJ } tag eng_adverb:herniographically{ MODIF_TYPE:ADJ } tag eng_adverb:heterogeneously{ MODIF_TYPE:ADJ } tag eng_adverb:heterogenously{ MODIF_TYPE:ADJ } tag eng_adverb:heterologously{ MODIF_TYPE:ADJ } //tag eng_adverb:heterosexually{ MODIF_TYPE:ADJ } tag eng_adverb:heterosynaptically{ MODIF_TYPE:ADJ } tag eng_adverb:heterotopically{ MODIF_TYPE:ADJ } tag eng_adverb:heterotrophically{ MODIF_TYPE:ADJ } tag eng_adverb:heterotypically{ MODIF_TYPE:ADJ } tag eng_adverb:heterozygously{ MODIF_TYPE:ADJ } tag eng_adverb:hierarchically{ MODIF_TYPE:ADJ } tag eng_adverb:histoautoradiographically{ MODIF_TYPE:ADJ } tag eng_adverb:histo-cytologically{ MODIF_TYPE:ADJ } tag eng_adverb:histocytologically{ MODIF_TYPE:ADJ } tag eng_adverb:histogenetically{ MODIF_TYPE:ADJ } tag eng_adverb:histologically{ MODIF_TYPE:ADJ } tag eng_adverb:histometrically{ MODIF_TYPE:ADJ } tag eng_adverb:histomorphologically{ MODIF_TYPE:ADJ } tag eng_adverb:histomorphometrically{ MODIF_TYPE:ADJ } tag eng_adverb:histopathologically{ MODIF_TYPE:ADJ } tag eng_adverb:histo-structurally{ MODIF_TYPE:ADJ } tag eng_adverb:histostructurally{ MODIF_TYPE:ADJ } tag eng_adverb:histotypically{ MODIF_TYPE:ADJ } tag eng_adverb:holographically{ MODIF_TYPE:ADJ } tag eng_adverb:homeostatically{ MODIF_TYPE:ADJ } tag eng_adverb:homogeneously{ MODIF_TYPE:ADJ } tag eng_adverb:homologously{ MODIF_TYPE:ADJ } tag eng_adverb:homosexually{ MODIF_TYPE:ADJ } tag eng_adverb:homotypically{ MODIF_TYPE:ADJ } tag eng_adverb:homozygously{ MODIF_TYPE:ADJ } tag eng_adverb:hormonally{ MODIF_TYPE:ADJ } tag eng_adverb:humanistically{ MODIF_TYPE:ADJ } tag eng_adverb:humorally{ MODIF_TYPE:ADJ } tag eng_adverb:hydrodensitometrically{ MODIF_TYPE:ADJ } tag eng_adverb:hydrolytically{ MODIF_TYPE:ADJ } tag eng_adverb:hydrophobically{ MODIF_TYPE:ADJ } tag eng_adverb:hydropically{ MODIF_TYPE:ADJ } tag eng_adverb:hydroponically{ MODIF_TYPE:ADJ } tag eng_adverb:hyperacutely{ MODIF_TYPE:ADJ } tag eng_adverb:hyperbolically{ MODIF_TYPE:ADJ } tag eng_adverb:hyperosmotically{ MODIF_TYPE:ADJ } tag eng_adverb:hyperoxically{ MODIF_TYPE:ADJ } tag eng_adverb:hyperreflexically{ MODIF_TYPE:ADJ } tag eng_adverb:hypersensitively{ MODIF_TYPE:ADJ } tag eng_adverb:hypoxically{ MODIF_TYPE:ADJ } tag eng_adverb:hysteroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:iatrogenically{ MODIF_TYPE:ADJ } tag eng_adverb:iconically{ MODIF_TYPE:ADJ } tag eng_adverb:iconographically{ MODIF_TYPE:ADJ } tag eng_adverb:ictally{ MODIF_TYPE:ADJ } tag eng_adverb:idiotypically{ MODIF_TYPE:ADJ } tag eng_adverb:immunobiologically{ MODIF_TYPE:ADJ } tag eng_adverb:immunochemically{ MODIF_TYPE:ADJ } tag eng_adverb:immunocyto-chemically{ MODIF_TYPE:ADJ } tag eng_adverb:immunofluorometrically{ MODIF_TYPE:ADJ } tag eng_adverb:immunogenetically{ MODIF_TYPE:ADJ } tag eng_adverb:immunohistochemically{ MODIF_TYPE:ADJ } tag eng_adverb:immunohistologically{ MODIF_TYPE:ADJ } tag eng_adverb:immunologically{ MODIF_TYPE:ADJ } tag eng_adverb:immunomorphologically{ MODIF_TYPE:ADJ } tag eng_adverb:immunospecifically{ MODIF_TYPE:ADJ } tag eng_adverb:inaptly{ MODIF_TYPE:ADJ } tag eng_adverb:inaudibly{ MODIF_TYPE:ADJ } tag eng_adverb:incrementally{ MODIF_TYPE:ADJ } tag eng_adverb:indecorously{ MODIF_TYPE:ADJ } tag eng_adverb:in dies{ MODIF_TYPE:ADJ } tag eng_adverb:indigenously{ MODIF_TYPE:ADJ } tag eng_adverb:inducibly{ MODIF_TYPE:ADJ } tag eng_adverb:inductively{ MODIF_TYPE:ADJ } tag eng_adverb:industrially{ MODIF_TYPE:ADJ } tag eng_adverb:inertially{ MODIF_TYPE:ADJ } tag eng_adverb:inexcusably{ MODIF_TYPE:ADJ } tag eng_adverb:in extenso{ MODIF_TYPE:ADJ } tag eng_adverb:infero-laterally{ MODIF_TYPE:ADJ } tag eng_adverb:infero-medially{ MODIF_TYPE:ADJ } tag eng_adverb:infero-posteriorly{ MODIF_TYPE:ADJ } tag eng_adverb:infero-temporally{ MODIF_TYPE:ADJ } tag eng_adverb:infiltratively{ MODIF_TYPE:ADJ } tag eng_adverb:infrahepatically{ MODIF_TYPE:ADJ } tag eng_adverb:in fundo{ MODIF_TYPE:ADJ } tag eng_adverb:inhibitorily{ MODIF_TYPE:ADJ } tag eng_adverb:inhomogeneously{ MODIF_TYPE:ADJ } tag eng_adverb:in lieu{ MODIF_TYPE:ADJ } tag eng_adverb:inotropically{ MODIF_TYPE:ADJ } tag eng_adverb:insecticidally{ MODIF_TYPE:ADJ } tag eng_adverb:inseparably{ MODIF_TYPE:ADJ } tag eng_adverb:insertionally{ MODIF_TYPE:ADJ } tag eng_adverb:inside-out{ MODIF_TYPE:ADJ } tag eng_adverb:insignificantly{ MODIF_TYPE:ADJ } tag eng_adverb:insofar{ MODIF_TYPE:ADJ } tag eng_adverb:interactively{ MODIF_TYPE:ADJ } tag eng_adverb:interatomically{ MODIF_TYPE:ADJ } tag eng_adverb:interferometrically{ MODIF_TYPE:ADJ } tag eng_adverb:intergenerically{ MODIF_TYPE:ADJ } tag eng_adverb:intermediately{ MODIF_TYPE:ADJ } tag eng_adverb:interpretatively{ MODIF_TYPE:ADJ } tag eng_adverb:interpretively{ MODIF_TYPE:ADJ } tag eng_adverb:interstitially{ MODIF_TYPE:ADJ } tag eng_adverb:intraabdominally{ MODIF_TYPE:ADJ } tag eng_adverb:intra-amnionically{ MODIF_TYPE:ADJ } tag eng_adverb:intraamnionically{ MODIF_TYPE:ADJ } tag eng_adverb:intraamniotically{ MODIF_TYPE:ADJ } tag eng_adverb:intraaortically{ MODIF_TYPE:ADJ } tag eng_adverb:intraarterially{ MODIF_TYPE:ADJ } tag eng_adverb:intraarticularly{ MODIF_TYPE:ADJ } tag eng_adverb:intra-cellularly{ MODIF_TYPE:ADJ } tag eng_adverb:intracerebrally{ MODIF_TYPE:ADJ } tag eng_adverb:intracervically{ MODIF_TYPE:ADJ } tag eng_adverb:intracolonically{ MODIF_TYPE:ADJ } tag eng_adverb:intracortically{ MODIF_TYPE:ADJ } tag eng_adverb:intracranially{ MODIF_TYPE:ADJ } tag eng_adverb:intraduodenally{ MODIF_TYPE:ADJ } tag eng_adverb:intra-epidermally{ MODIF_TYPE:ADJ } tag eng_adverb:intraepidermally{ MODIF_TYPE:ADJ } tag eng_adverb:intra-epithelially{ MODIF_TYPE:ADJ } tag eng_adverb:intraepithelially{ MODIF_TYPE:ADJ } tag eng_adverb:intrahypothalamically{ MODIF_TYPE:ADJ } tag eng_adverb:intra-individually{ MODIF_TYPE:ADJ } tag eng_adverb:intraindividually{ MODIF_TYPE:ADJ } tag eng_adverb:intrajejunally{ MODIF_TYPE:ADJ } tag eng_adverb:intralesionally{ MODIF_TYPE:ADJ } tag eng_adverb:intraluminally{ MODIF_TYPE:ADJ } tag eng_adverb:intramurally{ MODIF_TYPE:ADJ } tag eng_adverb:intra-muscularly{ MODIF_TYPE:ADJ } tag eng_adverb:intra-operatively{ MODIF_TYPE:ADJ } tag eng_adverb:intraoperatively{ MODIF_TYPE:ADJ } tag eng_adverb:intraorally{ MODIF_TYPE:ADJ } tag eng_adverb:intraportally{ MODIF_TYPE:ADJ } tag eng_adverb:intrarenally{ MODIF_TYPE:ADJ } tag eng_adverb:intrasplenically{ MODIF_TYPE:ADJ } tag eng_adverb:intratracheally{ MODIF_TYPE:ADJ } tag eng_adverb:intratypically{ MODIF_TYPE:ADJ } tag eng_adverb:intra-venously{ MODIF_TYPE:ADJ } tag eng_adverb:intravitally{ MODIF_TYPE:ADJ } tag eng_adverb:intriguingly{ MODIF_TYPE:ADJ } tag eng_adverb:intrusively{ MODIF_TYPE:ADJ } tag eng_adverb:invasively{ MODIF_TYPE:ADJ } tag eng_adverb:invertedly{ MODIF_TYPE:ADJ } tag eng_adverb:in vitro{ MODIF_TYPE:ADJ } tag eng_adverb:in vivo{ MODIF_TYPE:ADJ } tag eng_adverb:iontophoretically{ MODIF_TYPE:ADJ } tag eng_adverb:ipsilaterally{ MODIF_TYPE:ADJ } tag eng_adverb:irrevocably{ MODIF_TYPE:ADJ } tag eng_adverb:ischemically{ MODIF_TYPE:ADJ } tag eng_adverb:isometrically{ MODIF_TYPE:ADJ } tag eng_adverb:isotachophoretically{ MODIF_TYPE:ADJ } tag eng_adverb:isothermally{ MODIF_TYPE:ADJ } tag eng_adverb:isotopically{ MODIF_TYPE:ADJ } tag eng_adverb:isotropically{ MODIF_TYPE:ADJ } tag eng_adverb:iteratively{ MODIF_TYPE:ADJ } tag eng_adverb:karyotypically{ MODIF_TYPE:ADJ } tag eng_adverb:keratoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:kinaesthesiometrically{ MODIF_TYPE:ADJ } tag eng_adverb:kinematically{ MODIF_TYPE:ADJ } tag eng_adverb:kinesimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:kinesthesiometrically{ MODIF_TYPE:ADJ } tag eng_adverb:kinetically{ MODIF_TYPE:ADJ } tag eng_adverb:laminagraphically{ MODIF_TYPE:ADJ } tag eng_adverb:laparoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:laryngostroboscopically{ MODIF_TYPE:ADJ } tag eng_adverb:latently{ MODIF_TYPE:ADJ } tag eng_adverb:legalistically{ MODIF_TYPE:ADJ } tag eng_adverb:lensometrically{ MODIF_TYPE:ADJ } tag eng_adverb:lethally{ MODIF_TYPE:ADJ } tag eng_adverb:likewise{ MODIF_TYPE:ADJ } tag eng_adverb:limitedly{ MODIF_TYPE:ADJ } tag eng_adverb:linguo-apically{ MODIF_TYPE:ADJ } tag eng_adverb:lithometrically{ MODIF_TYPE:ADJ } tag eng_adverb:lithoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:lumboscopically{ MODIF_TYPE:ADJ } tag eng_adverb:luminometrically{ MODIF_TYPE:ADJ } tag eng_adverb:lymphangiographically{ MODIF_TYPE:ADJ } tag eng_adverb:lymphographically{ MODIF_TYPE:ADJ } tag eng_adverb:lymphoscintigraphically{ MODIF_TYPE:ADJ } tag eng_adverb:lytically{ MODIF_TYPE:ADJ } tag eng_adverb:macroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:magnetocardiographically{ MODIF_TYPE:ADJ } tag eng_adverb:magnocellularly{ MODIF_TYPE:ADJ } tag eng_adverb:mammographically{ MODIF_TYPE:ADJ } tag eng_adverb:manipulatively{ MODIF_TYPE:ADJ } tag eng_adverb:mechanographically{ MODIF_TYPE:ADJ } tag eng_adverb:mechanomyographically{ MODIF_TYPE:ADJ } tag eng_adverb:meiotically{ MODIF_TYPE:ADJ } tag eng_adverb:metabolically{ MODIF_TYPE:ADJ } tag eng_adverb:metamorphically{ MODIF_TYPE:ADJ } tag eng_adverb:metastatically{ MODIF_TYPE:ADJ } tag eng_adverb:microanalytically{ MODIF_TYPE:ADJ } tag eng_adverb:microanatomically{ MODIF_TYPE:ADJ } tag eng_adverb:microangiographically{ MODIF_TYPE:ADJ } tag eng_adverb:microbially{ MODIF_TYPE:ADJ } tag eng_adverb:microbiologically{ MODIF_TYPE:ADJ } tag eng_adverb:microcalorimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:microchemically{ MODIF_TYPE:ADJ } tag eng_adverb:microdensitometrically{ MODIF_TYPE:ADJ } tag eng_adverb:microelectrophoretically{ MODIF_TYPE:ADJ } tag eng_adverb:microfluorometrically{ MODIF_TYPE:ADJ } tag eng_adverb:microgasometrically{ MODIF_TYPE:ADJ } tag eng_adverb:microiontophoretically{ MODIF_TYPE:ADJ } tag eng_adverb:microneurographically{ MODIF_TYPE:ADJ } tag eng_adverb:microphotometrically{ MODIF_TYPE:ADJ } tag eng_adverb:microradiographically{ MODIF_TYPE:ADJ } //tag eng_adverb:microspectrofluorometrically{ MODIF_TYPE:ADJ } //tag eng_adverb:microspectrophotometrically{ MODIF_TYPE:ADJ } tag eng_adverb:microsurgically{ MODIF_TYPE:ADJ } tag eng_adverb:midsystolically{ MODIF_TYPE:ADJ } tag eng_adverb:mineralogically{ MODIF_TYPE:ADJ } tag eng_adverb:mirthlessly{ MODIF_TYPE:ADJ } tag eng_adverb:mitochondrially{ MODIF_TYPE:ADJ } tag eng_adverb:mitotically{ MODIF_TYPE:ADJ } tag eng_adverb:molecularly{ MODIF_TYPE:ADJ } tag eng_adverb:monocularly{ MODIF_TYPE:ADJ } tag eng_adverb:monophasically{ MODIF_TYPE:ADJ } tag eng_adverb:monotonically{ MODIF_TYPE:ADJ } tag eng_adverb:morphologically{ MODIF_TYPE:ADJ } tag eng_adverb:morphometrically{ MODIF_TYPE:ADJ } tag eng_adverb:motorically{ MODIF_TYPE:ADJ } tag eng_adverb:muscularly{ MODIF_TYPE:ADJ } tag eng_adverb:mutagenically{ MODIF_TYPE:ADJ } tag eng_adverb:myeloscopically{ MODIF_TYPE:ADJ } tag eng_adverb:nasographically{ MODIF_TYPE:ADJ } tag eng_adverb:nasopharyngoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:nasoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:natally{ MODIF_TYPE:ADJ } tag eng_adverb:natively{ MODIF_TYPE:ADJ } tag eng_adverb:negligibly{ MODIF_TYPE:ADJ } tag eng_adverb:neoplastically{ MODIF_TYPE:ADJ } tag eng_adverb:nephrologically{ MODIF_TYPE:ADJ } tag eng_adverb:nephroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:neurobiologically{ MODIF_TYPE:ADJ } tag eng_adverb:neurochemically{ MODIF_TYPE:ADJ } tag eng_adverb:neurographically{ MODIF_TYPE:ADJ } tag eng_adverb:neurolinguistically{ MODIF_TYPE:ADJ } tag eng_adverb:neuronally{ MODIF_TYPE:ADJ } tag eng_adverb:neuropathologically{ MODIF_TYPE:ADJ } tag eng_adverb:neuropsychologically{ MODIF_TYPE:ADJ } tag eng_adverb:neurovascularly{ MODIF_TYPE:ADJ } tag eng_adverb:noncompetitively{ MODIF_TYPE:ADJ } tag eng_adverb:nonconventionally{ MODIF_TYPE:ADJ } tag eng_adverb:noncovalently{ MODIF_TYPE:ADJ } tag eng_adverb:noncyclically{ MODIF_TYPE:ADJ } tag eng_adverb:nonenzymatically{ MODIF_TYPE:ADJ } tag eng_adverb:nongenetically{ MODIF_TYPE:ADJ } tag eng_adverb:nonhaematologically{ MODIF_TYPE:ADJ } tag eng_adverb:nonhematologically{ MODIF_TYPE:ADJ } tag eng_adverb:nonimmunologically{ MODIF_TYPE:ADJ } tag eng_adverb:non-invasively{ MODIF_TYPE:ADJ } tag eng_adverb:noninvasively{ MODIF_TYPE:ADJ } tag eng_adverb:non-isotopically{ MODIF_TYPE:ADJ } tag eng_adverb:nonisotopically{ MODIF_TYPE:ADJ } tag eng_adverb:nonmetastatically{ MODIF_TYPE:ADJ } tag eng_adverb:nonmetrically{ MODIF_TYPE:ADJ } tag eng_adverb:non-occupationally{ MODIF_TYPE:ADJ } tag eng_adverb:nonoccupationally{ MODIF_TYPE:ADJ } tag eng_adverb:non-operatively{ MODIF_TYPE:ADJ } tag eng_adverb:nonoperatively{ MODIF_TYPE:ADJ } tag eng_adverb:nonosmotically{ MODIF_TYPE:ADJ } tag eng_adverb:non-pharmacologically{ MODIF_TYPE:ADJ } tag eng_adverb:nonpharmacologically{ MODIF_TYPE:ADJ } tag eng_adverb:nonpolymorphically{ MODIF_TYPE:ADJ } tag eng_adverb:nonpsychiatrically{ MODIF_TYPE:ADJ } tag eng_adverb:non-randomly{ MODIF_TYPE:ADJ } tag eng_adverb:nonrandomly{ MODIF_TYPE:ADJ } tag eng_adverb:non-sexually{ MODIF_TYPE:ADJ } tag eng_adverb:nonsexually{ MODIF_TYPE:ADJ } tag eng_adverb:nonsignificantly{ MODIF_TYPE:ADJ } tag eng_adverb:non-simultaneously{ MODIF_TYPE:ADJ } tag eng_adverb:nonsurgically{ MODIF_TYPE:ADJ } tag eng_adverb:nosographically{ MODIF_TYPE:ADJ } tag eng_adverb:nuclearly{ MODIF_TYPE:ADJ } tag eng_adverb:nystagmographically{ MODIF_TYPE:ADJ } tag eng_adverb:obligatorily{ MODIF_TYPE:ADJ } tag eng_adverb:observerscopically{ MODIF_TYPE:ADJ } tag eng_adverb:occcasionally{ MODIF_TYPE:ADJ } tag eng_adverb:occupationally{ MODIF_TYPE:ADJ } tag eng_adverb:octahedrally{ MODIF_TYPE:ADJ } tag eng_adverb:oculographically{ MODIF_TYPE:ADJ } tag eng_adverb:oculoplethysmographically{ MODIF_TYPE:ADJ } tag eng_adverb:odynometrically{ MODIF_TYPE:ADJ } tag eng_adverb:oft{ MODIF_TYPE:ADJ } tag eng_adverb:olfactometrically{ MODIF_TYPE:ADJ } tag eng_adverb:omnicardiographically{ MODIF_TYPE:ADJ } tag eng_adverb:omni nocte{ MODIF_TYPE:ADJ } tag eng_adverb:oncometrically{ MODIF_TYPE:ADJ } tag eng_adverb:one-sidedly{ MODIF_TYPE:ADJ } tag eng_adverb:operationally{ MODIF_TYPE:ADJ } tag eng_adverb:operatively{ MODIF_TYPE:ADJ } //tag eng_adverb:ophthalmodiaphanoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:ophthalmodiastimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:ophthalmodynamometrically{ MODIF_TYPE:ADJ } tag eng_adverb:ophthalmofunduscopically{ MODIF_TYPE:ADJ } tag eng_adverb:ophthalmographically{ MODIF_TYPE:ADJ } tag eng_adverb:ophthalmoleucoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:ophthalmoleukoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:ophthalmometrically{ MODIF_TYPE:ADJ } tag eng_adverb:ophthalmometroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:ophthalmotonometrically{ MODIF_TYPE:ADJ } tag eng_adverb:ophthalmotropometrically{ MODIF_TYPE:ADJ } tag eng_adverb:oppositely{ MODIF_TYPE:ADJ } tag eng_adverb:optoelectronically{ MODIF_TYPE:ADJ } tag eng_adverb:optometrically{ MODIF_TYPE:ADJ } tag eng_adverb:optomyometrically{ MODIF_TYPE:ADJ } tag eng_adverb:orchidometrically{ MODIF_TYPE:ADJ } tag eng_adverb:ordinately{ MODIF_TYPE:ADJ } tag eng_adverb:organismically{ MODIF_TYPE:ADJ } tag eng_adverb:orogastrically{ MODIF_TYPE:ADJ } tag eng_adverb:orthotopically{ MODIF_TYPE:ADJ } tag eng_adverb:oscillographically{ MODIF_TYPE:ADJ } tag eng_adverb:oscillometrically{ MODIF_TYPE:ADJ } tag eng_adverb:oscillotonometrically{ MODIF_TYPE:ADJ } tag eng_adverb:osmometrically{ MODIF_TYPE:ADJ } tag eng_adverb:osmoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:osmotically{ MODIF_TYPE:ADJ } tag eng_adverb:osteosynthetically{ MODIF_TYPE:ADJ } tag eng_adverb:otoacoustically{ MODIF_TYPE:ADJ } tag eng_adverb:otomicroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:otoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:out of doors{ MODIF_TYPE:ADJ } tag eng_adverb:over-ridingly{ MODIF_TYPE:ADJ } tag eng_adverb:oxidatively{ MODIF_TYPE:ADJ } tag eng_adverb:pachymetrically{ MODIF_TYPE:ADJ } tag eng_adverb:panendoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:pantographically{ MODIF_TYPE:ADJ } tag eng_adverb:para-arterially{ MODIF_TYPE:ADJ } tag eng_adverb:paraarterially{ MODIF_TYPE:ADJ } tag eng_adverb:paracentrically{ MODIF_TYPE:ADJ } tag eng_adverb:paradigmatically{ MODIF_TYPE:ADJ } tag eng_adverb:paramagnetically{ MODIF_TYPE:ADJ } tag eng_adverb:parasitologically{ MODIF_TYPE:ADJ } tag eng_adverb:parasystolically{ MODIF_TYPE:ADJ } tag eng_adverb:parenterally{ MODIF_TYPE:ADJ } tag eng_adverb:pari passu{ MODIF_TYPE:ADJ } tag eng_adverb:parthenogenetically{ MODIF_TYPE:ADJ } tag eng_adverb:parturiometrically{ MODIF_TYPE:ADJ } tag eng_adverb:pathomorphologically{ MODIF_TYPE:ADJ } tag eng_adverb:pelvimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:pelviscopically{ MODIF_TYPE:ADJ } tag eng_adverb:penetrometrically{ MODIF_TYPE:ADJ } tag eng_adverb:pentagonally{ MODIF_TYPE:ADJ } tag eng_adverb:peranally{ MODIF_TYPE:ADJ } tag eng_adverb:per annum{ MODIF_TYPE:ADJ } tag eng_adverb:per anum{ MODIF_TYPE:ADJ } tag eng_adverb:per cent{ MODIF_TYPE:ADJ } tag eng_adverb:per contiguum{ MODIF_TYPE:ADJ } tag eng_adverb:per continuum{ MODIF_TYPE:ADJ } tag eng_adverb:percutaneously{ MODIF_TYPE:ADJ } tag eng_adverb:per cutem{ MODIF_TYPE:ADJ } tag eng_adverb:perforce{ MODIF_TYPE:ADJ } tag eng_adverb:perinatally{ MODIF_TYPE:ADJ } tag eng_adverb:periodontally{ MODIF_TYPE:ADJ } tag eng_adverb:perioperatively{ MODIF_TYPE:ADJ } tag eng_adverb:periplasmically{ MODIF_TYPE:ADJ } tag eng_adverb:peritoneally{ MODIF_TYPE:ADJ } tag eng_adverb:peritoneoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:peritrichously{ MODIF_TYPE:ADJ } tag eng_adverb:perorally{ MODIF_TYPE:ADJ } tag eng_adverb:per os{ MODIF_TYPE:ADJ } tag eng_adverb:per primam{ MODIF_TYPE:ADJ } tag eng_adverb:per primam intentionem{ MODIF_TYPE:ADJ } tag eng_adverb:per rectum{ MODIF_TYPE:ADJ } tag eng_adverb:per saltum{ MODIF_TYPE:ADJ } tag eng_adverb:per se{ MODIF_TYPE:ADJ } tag eng_adverb:per secundam{ MODIF_TYPE:ADJ } tag eng_adverb:per secundam intentionem{ MODIF_TYPE:ADJ } tag eng_adverb:per tertiam{ MODIF_TYPE:ADJ } tag eng_adverb:pertinently{ MODIF_TYPE:ADJ } tag eng_adverb:per tubam{ MODIF_TYPE:ADJ } tag eng_adverb:per vaginam{ MODIF_TYPE:ADJ } tag eng_adverb:per vias naturales{ MODIF_TYPE:ADJ } tag eng_adverb:petechiometrically{ MODIF_TYPE:ADJ } tag eng_adverb:phaneroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:pharmaceutically{ MODIF_TYPE:ADJ } tag eng_adverb:pharyngoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:phenotypically{ MODIF_TYPE:ADJ } tag eng_adverb:phoniatrically{ MODIF_TYPE:ADJ } tag eng_adverb:phonostethographically{ MODIF_TYPE:ADJ } tag eng_adverb:phorometrically{ MODIF_TYPE:ADJ } tag eng_adverb:photoacoustically{ MODIF_TYPE:ADJ } tag eng_adverb:photochemically{ MODIF_TYPE:ADJ } tag eng_adverb:photofluorometrically{ MODIF_TYPE:ADJ } tag eng_adverb:photofluoroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:photomicrographically{ MODIF_TYPE:ADJ } tag eng_adverb:photoplethysmographically{ MODIF_TYPE:ADJ } tag eng_adverb:phototachometrically{ MODIF_TYPE:ADJ } tag eng_adverb:phototactically{ MODIF_TYPE:ADJ } tag eng_adverb:phototrophically{ MODIF_TYPE:ADJ } tag eng_adverb:phylogenetically{ MODIF_TYPE:ADJ } tag eng_adverb:physiologically{ MODIF_TYPE:ADJ } tag eng_adverb:physiotherapeutically{ MODIF_TYPE:ADJ } tag eng_adverb:piezoelectrically{ MODIF_TYPE:ADJ } tag eng_adverb:placentally{ MODIF_TYPE:ADJ } tag eng_adverb:planigraphically{ MODIF_TYPE:ADJ } tag eng_adverb:planimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:plethysmographically{ MODIF_TYPE:ADJ } tag eng_adverb:pluralistically{ MODIF_TYPE:ADJ } tag eng_adverb:pneumatographically{ MODIF_TYPE:ADJ } tag eng_adverb:pneumotachographically{ MODIF_TYPE:ADJ } tag eng_adverb:polycardiographically{ MODIF_TYPE:ADJ } tag eng_adverb:polyclonally{ MODIF_TYPE:ADJ } tag eng_adverb:polygraphically{ MODIF_TYPE:ADJ } tag eng_adverb:polysomnographically{ MODIF_TYPE:ADJ } tag eng_adverb:polyspermically{ MODIF_TYPE:ADJ } tag eng_adverb:post-catheterisation{ MODIF_TYPE:ADJ } tag eng_adverb:postcatheterisation{ MODIF_TYPE:ADJ } tag eng_adverb:post cibos{ MODIF_TYPE:ADJ } tag eng_adverb:posteroanteriorly{ MODIF_TYPE:ADJ } tag eng_adverb:postischaemically{ MODIF_TYPE:ADJ } tag eng_adverb:postischemically{ MODIF_TYPE:ADJ } tag eng_adverb:postmetamorphically{ MODIF_TYPE:ADJ } tag eng_adverb:post mortem{ MODIF_TYPE:ADJ } tag eng_adverb:postnatally{ MODIF_TYPE:ADJ } tag eng_adverb:post operatively{ MODIF_TYPE:ADJ } tag eng_adverb:post-operatively{ MODIF_TYPE:ADJ } tag eng_adverb:post partum{ MODIF_TYPE:ADJ } tag eng_adverb:postprandially{ MODIF_TYPE:ADJ } //tag eng_adverb:post singulas sedes liquidas{ MODIF_TYPE:ADJ } tag eng_adverb:postthrombotically{ MODIF_TYPE:ADJ } tag eng_adverb:posttranscriptionally{ MODIF_TYPE:ADJ } tag eng_adverb:post-translationally{ MODIF_TYPE:ADJ } tag eng_adverb:posttranslationally{ MODIF_TYPE:ADJ } tag eng_adverb:potentiometrically{ MODIF_TYPE:ADJ } //tag eng_adverb:pow{ MODIF_TYPE:ADJ } tag eng_adverb:pre-attentively{ MODIF_TYPE:ADJ } tag eng_adverb:preattentively{ MODIF_TYPE:ADJ } tag eng_adverb:precociously{ MODIF_TYPE:ADJ } tag eng_adverb:preconceptionally{ MODIF_TYPE:ADJ } tag eng_adverb:predominately{ MODIF_TYPE:ADJ } tag eng_adverb:preferentially{ MODIF_TYPE:ADJ } tag eng_adverb:preliminarily{ MODIF_TYPE:ADJ } tag eng_adverb:premenopausally{ MODIF_TYPE:ADJ } tag eng_adverb:prenatally{ MODIF_TYPE:ADJ } tag eng_adverb:pre-operatively{ MODIF_TYPE:ADJ } tag eng_adverb:presumptively{ MODIF_TYPE:ADJ } tag eng_adverb:prethymically{ MODIF_TYPE:ADJ } tag eng_adverb:prevalently{ MODIF_TYPE:ADJ } tag eng_adverb:proctosigmoidoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:prolately{ MODIF_TYPE:ADJ } tag eng_adverb:prophylactically{ MODIF_TYPE:ADJ } tag eng_adverb:pro rata{ MODIF_TYPE:ADJ } tag eng_adverb:pro re nata{ MODIF_TYPE:ADJ } tag eng_adverb:prospectively{ MODIF_TYPE:ADJ } tag eng_adverb:proteolytically{ MODIF_TYPE:ADJ } tag eng_adverb:prototypically{ MODIF_TYPE:ADJ } tag eng_adverb:psychiatrically{ MODIF_TYPE:ADJ } tag eng_adverb:psychoanalytically{ MODIF_TYPE:ADJ } tag eng_adverb:psychometrically{ MODIF_TYPE:ADJ } tag eng_adverb:psychotically{ MODIF_TYPE:ADJ } tag eng_adverb:pulselessly{ MODIF_TYPE:ADJ } tag eng_adverb:pupillographically{ MODIF_TYPE:ADJ } tag eng_adverb:pupillometrically{ MODIF_TYPE:ADJ } tag eng_adverb:pyeloscopically{ MODIF_TYPE:ADJ } tag eng_adverb:pyrolytically{ MODIF_TYPE:ADJ } tag eng_adverb:pyrometrically{ MODIF_TYPE:ADJ } tag eng_adverb:pyroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:quaque nocte{ MODIF_TYPE:ADJ } tag eng_adverb:radiatively{ MODIF_TYPE:ADJ } tag eng_adverb:radioactively{ MODIF_TYPE:ADJ } tag eng_adverb:radiobiologically{ MODIF_TYPE:ADJ } tag eng_adverb:radiocardiographically{ MODIF_TYPE:ADJ } tag eng_adverb:radiochemically{ MODIF_TYPE:ADJ } tag eng_adverb:radiochromatographically{ MODIF_TYPE:ADJ } tag eng_adverb:radioenzymatically{ MODIF_TYPE:ADJ } tag eng_adverb:radiogenically{ MODIF_TYPE:ADJ } tag eng_adverb:radiographically{ MODIF_TYPE:ADJ } tag eng_adverb:radioimmunologically{ MODIF_TYPE:ADJ } tag eng_adverb:radiologically{ MODIF_TYPE:ADJ } tag eng_adverb:radiolytically{ MODIF_TYPE:ADJ } tag eng_adverb:radiotelemetrically{ MODIF_TYPE:ADJ } tag eng_adverb:rakishly{ MODIF_TYPE:ADJ } tag eng_adverb:reactively{ MODIF_TYPE:ADJ } tag eng_adverb:recessively{ MODIF_TYPE:ADJ } tag eng_adverb:reciprocally{ MODIF_TYPE:ADJ } tag eng_adverb:rectally{ MODIF_TYPE:ADJ } tag eng_adverb:reflexively{ MODIF_TYPE:ADJ } tag eng_adverb:regardless{ MODIF_TYPE:ADJ } tag eng_adverb:renographically{ MODIF_TYPE:ADJ } tag eng_adverb:reproducibly{ MODIF_TYPE:ADJ } tag eng_adverb:resectoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:retinoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:retrogradely{ MODIF_TYPE:ADJ } tag eng_adverb:retrovirally{ MODIF_TYPE:ADJ } tag eng_adverb:revengefully{ MODIF_TYPE:ADJ } tag eng_adverb:reversely{ MODIF_TYPE:ADJ } tag eng_adverb:rheologically{ MODIF_TYPE:ADJ } tag eng_adverb:rheumatologically{ MODIF_TYPE:ADJ } tag eng_adverb:rhinoanemometrically{ MODIF_TYPE:ADJ } tag eng_adverb:rhinomanometrically{ MODIF_TYPE:ADJ } tag eng_adverb:ritardando{ MODIF_TYPE:ADJ } tag eng_adverb:roentgenographically{ MODIF_TYPE:ADJ } tag eng_adverb:rostrally{ MODIF_TYPE:ADJ } tag eng_adverb:rostrocaudally{ MODIF_TYPE:ADJ } tag eng_adverb:rotametrically{ MODIF_TYPE:ADJ } tag eng_adverb:rotationally{ MODIF_TYPE:ADJ } tag eng_adverb:ruminally{ MODIF_TYPE:ADJ } tag eng_adverb:saprophytically{ MODIF_TYPE:ADJ } tag eng_adverb:satisfyingly{ MODIF_TYPE:ADJ } tag eng_adverb:scandalously{ MODIF_TYPE:ADJ } tag eng_adverb:scintigraphically{ MODIF_TYPE:ADJ } tag eng_adverb:secundum artem{ MODIF_TYPE:ADJ } tag eng_adverb:secundum naturam{ MODIF_TYPE:ADJ } tag eng_adverb:sedimentometrically{ MODIF_TYPE:ADJ } tag eng_adverb:segmentally{ MODIF_TYPE:ADJ } tag eng_adverb:semiautomatically{ MODIF_TYPE:ADJ } tag eng_adverb:semiologically{ MODIF_TYPE:ADJ } tag eng_adverb:semi-quantitatively{ MODIF_TYPE:ADJ } tag eng_adverb:semiquantitatively{ MODIF_TYPE:ADJ } tag eng_adverb:semispecifically{ MODIF_TYPE:ADJ } tag eng_adverb:serendipitously{ MODIF_TYPE:ADJ } tag eng_adverb:serologically{ MODIF_TYPE:ADJ } tag eng_adverb:serospecifically{ MODIF_TYPE:ADJ } tag eng_adverb:shoddily{ MODIF_TYPE:ADJ } tag eng_adverb:sialographically{ MODIF_TYPE:ADJ } tag eng_adverb:siderose{ MODIF_TYPE:ADJ } tag eng_adverb:sigmoidally{ MODIF_TYPE:ADJ } tag eng_adverb:sigmoidoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:simplistically{ MODIF_TYPE:ADJ } tag eng_adverb:sinusoidally{ MODIF_TYPE:ADJ } tag eng_adverb:skeletally{ MODIF_TYPE:ADJ } tag eng_adverb:sketchily{ MODIF_TYPE:ADJ } tag eng_adverb:skiascopically{ MODIF_TYPE:ADJ } tag eng_adverb:sociodemographically{ MODIF_TYPE:ADJ } tag eng_adverb:sociometrically{ MODIF_TYPE:ADJ } tag eng_adverb:somatically{ MODIF_TYPE:ADJ } tag eng_adverb:some day{ MODIF_TYPE:ADJ } tag eng_adverb:sonographically{ MODIF_TYPE:ADJ } tag eng_adverb:soundlessly{ MODIF_TYPE:ADJ } tag eng_adverb:spatiotemporally{ MODIF_TYPE:ADJ } tag eng_adverb:spectrally{ MODIF_TYPE:ADJ } tag eng_adverb:spectrofluorimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:spectrographically{ MODIF_TYPE:ADJ } tag eng_adverb:spectrophotometrically{ MODIF_TYPE:ADJ } tag eng_adverb:spectroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:speculatively{ MODIF_TYPE:ADJ } tag eng_adverb:spheroidally{ MODIF_TYPE:ADJ } tag eng_adverb:sphincteroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:sphygmocardiographically{ MODIF_TYPE:ADJ } tag eng_adverb:spinally{ MODIF_TYPE:ADJ } tag eng_adverb:spinelessly{ MODIF_TYPE:ADJ } tag eng_adverb:spiritlessly{ MODIF_TYPE:ADJ } tag eng_adverb:spirographically{ MODIF_TYPE:ADJ } tag eng_adverb:stably{ MODIF_TYPE:ADJ } tag eng_adverb:stereologically{ MODIF_TYPE:ADJ } tag eng_adverb:stereometrically{ MODIF_TYPE:ADJ } tag eng_adverb:stereomicroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:stereophotogrammetrically{ MODIF_TYPE:ADJ } tag eng_adverb:stereospecifically{ MODIF_TYPE:ADJ } tag eng_adverb:stereotactically{ MODIF_TYPE:ADJ } tag eng_adverb:stereotaxically{ MODIF_TYPE:ADJ } tag eng_adverb:sterically{ MODIF_TYPE:ADJ } tag eng_adverb:stertorously{ MODIF_TYPE:ADJ } tag eng_adverb:stethographically{ MODIF_TYPE:ADJ } tag eng_adverb:stoichiometrically{ MODIF_TYPE:ADJ } tag eng_adverb:stolidly{ MODIF_TYPE:ADJ } tag eng_adverb:subchronically{ MODIF_TYPE:ADJ } tag eng_adverb:subepithelially{ MODIF_TYPE:ADJ } tag eng_adverb:sublethally{ MODIF_TYPE:ADJ } tag eng_adverb:sublingually{ MODIF_TYPE:ADJ } tag eng_adverb:submaximally{ MODIF_TYPE:ADJ } tag eng_adverb:suboptimally{ MODIF_TYPE:ADJ } tag eng_adverb:subperiodically{ MODIF_TYPE:ADJ } tag eng_adverb:subserosally{ MODIF_TYPE:ADJ } tag eng_adverb:subtotally{ MODIF_TYPE:ADJ } tag eng_adverb:sudorimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:sulkily{ MODIF_TYPE:ADJ } tag eng_adverb:superparamagnetically{ MODIF_TYPE:ADJ } tag eng_adverb:supportively{ MODIF_TYPE:ADJ } tag eng_adverb:supranormally{ MODIF_TYPE:ADJ } tag eng_adverb:supraphysiologically{ MODIF_TYPE:ADJ } tag eng_adverb:supratubercular{ MODIF_TYPE:ADJ } tag eng_adverb:symptomatically{ MODIF_TYPE:ADJ } tag eng_adverb:synaptically{ MODIF_TYPE:ADJ } tag eng_adverb:synchronously{ MODIF_TYPE:ADJ } tag eng_adverb:synergistically{ MODIF_TYPE:ADJ } tag eng_adverb:systemically{ MODIF_TYPE:ADJ } tag eng_adverb:tachometrically{ MODIF_TYPE:ADJ } tag eng_adverb:tandemly{ MODIF_TYPE:ADJ } tag eng_adverb:td{ MODIF_TYPE:ADJ } tag eng_adverb:tearlessly{ MODIF_TYPE:ADJ } tag eng_adverb:telediastolically{ MODIF_TYPE:ADJ } tag eng_adverb:telemetrically{ MODIF_TYPE:ADJ } tag eng_adverb:telephonically{ MODIF_TYPE:ADJ } tag eng_adverb:telethermometrically{ MODIF_TYPE:ADJ } tag eng_adverb:temporally{ MODIF_TYPE:ADJ } tag eng_adverb:tendentiously{ MODIF_TYPE:ADJ } tag eng_adverb:ter dia{ MODIF_TYPE:ADJ } tag eng_adverb:tetanically{ MODIF_TYPE:ADJ } tag eng_adverb:tetragonally{ MODIF_TYPE:ADJ } tag eng_adverb:tetrahedrally{ MODIF_TYPE:ADJ } tag eng_adverb:thalamically{ MODIF_TYPE:ADJ } tag eng_adverb:thematically{ MODIF_TYPE:ADJ } tag eng_adverb:thence{ MODIF_TYPE:ADJ } tag eng_adverb:thereof{ MODIF_TYPE:ADJ } tag eng_adverb:therewith{ MODIF_TYPE:ADJ } tag eng_adverb:thermodynamically{ MODIF_TYPE:ADJ } tag eng_adverb:thermographically{ MODIF_TYPE:ADJ } tag eng_adverb:thermometrically{ MODIF_TYPE:ADJ } tag eng_adverb:thermostatically{ MODIF_TYPE:ADJ } tag eng_adverb:thioyltically{ MODIF_TYPE:ADJ } tag eng_adverb:thoracoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:thrice{ MODIF_TYPE:ADJ } tag eng_adverb:thromboelastographically{ MODIF_TYPE:ADJ } tag eng_adverb:thrombometrically{ MODIF_TYPE:ADJ } tag eng_adverb:tid{ MODIF_TYPE:ADJ } tag eng_adverb:tocodynamometrically{ MODIF_TYPE:ADJ } tag eng_adverb:tomodensitometrically{ MODIF_TYPE:ADJ } tag eng_adverb:tomographically{ MODIF_TYPE:ADJ } tag eng_adverb:tonally{ MODIF_TYPE:ADJ } tag eng_adverb:tonically{ MODIF_TYPE:ADJ } tag eng_adverb:tonographically{ MODIF_TYPE:ADJ } tag eng_adverb:tonometrically{ MODIF_TYPE:ADJ } tag eng_adverb:tonoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:topologically{ MODIF_TYPE:ADJ } tag eng_adverb:tracheally{ MODIF_TYPE:ADJ } tag eng_adverb:transcardially{ MODIF_TYPE:ADJ } tag eng_adverb:transcranially{ MODIF_TYPE:ADJ } tag eng_adverb:transcriptionally{ MODIF_TYPE:ADJ } tag eng_adverb:transcrotally{ MODIF_TYPE:ADJ } tag eng_adverb:transiently{ MODIF_TYPE:ADJ } tag eng_adverb:translaryngeally{ MODIF_TYPE:ADJ } tag eng_adverb:transmurally{ MODIF_TYPE:ADJ } tag eng_adverb:transovumly{ MODIF_TYPE:ADJ } tag eng_adverb:transplacentally{ MODIF_TYPE:ADJ } tag eng_adverb:transpylorically{ MODIF_TYPE:ADJ } tag eng_adverb:transrectally{ MODIF_TYPE:ADJ } tag eng_adverb:transstadially{ MODIF_TYPE:ADJ } tag eng_adverb:transtadially{ MODIF_TYPE:ADJ } tag eng_adverb:transtelephonically{ MODIF_TYPE:ADJ } tag eng_adverb:transvaginally{ MODIF_TYPE:ADJ } tag eng_adverb:transvenously{ MODIF_TYPE:ADJ } tag eng_adverb:traumatically{ MODIF_TYPE:ADJ } tag eng_adverb:traumatologically{ MODIF_TYPE:ADJ } tag eng_adverb:tremographically{ MODIF_TYPE:ADJ } tag eng_adverb:triadically{ MODIF_TYPE:ADJ } tag eng_adverb:tropometrically{ MODIF_TYPE:ADJ } tag eng_adverb:troposcopically{ MODIF_TYPE:ADJ } tag eng_adverb:typoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:ubiquitously{ MODIF_TYPE:ADJ } tag eng_adverb:ultrasonically{ MODIF_TYPE:ADJ } tag eng_adverb:ultrasonographically{ MODIF_TYPE:ADJ } tag eng_adverb:ultrastructurally{ MODIF_TYPE:ADJ } tag eng_adverb:unaggressively{ MODIF_TYPE:ADJ } tag eng_adverb:unclearly{ MODIF_TYPE:ADJ } tag eng_adverb:uncompetitively{ MODIF_TYPE:ADJ } tag eng_adverb:uniparentally{ MODIF_TYPE:ADJ } tag eng_adverb:univalently{ MODIF_TYPE:ADJ } tag eng_adverb:univariately{ MODIF_TYPE:ADJ } tag eng_adverb:unnaturally{ MODIF_TYPE:ADJ } tag eng_adverb:unphysiologically{ MODIF_TYPE:ADJ } tag eng_adverb:unpredictably{ MODIF_TYPE:ADJ } tag eng_adverb:unproblematically{ MODIF_TYPE:ADJ } tag eng_adverb:unrealistically{ MODIF_TYPE:ADJ } tag eng_adverb:unsympathetically{ MODIF_TYPE:ADJ } tag eng_adverb:unsystematically{ MODIF_TYPE:ADJ } tag eng_adverb:upside down{ MODIF_TYPE:ADJ } tag eng_adverb:ureterorenoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:ureteroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:urethrographically{ MODIF_TYPE:ADJ } tag eng_adverb:urethrometrically{ MODIF_TYPE:ADJ } tag eng_adverb:urinometrically{ MODIF_TYPE:ADJ } tag eng_adverb:urodynamically{ MODIF_TYPE:ADJ } tag eng_adverb:uroflowmetrically{ MODIF_TYPE:ADJ } tag eng_adverb:usefully{ MODIF_TYPE:ADJ } tag eng_adverb:vagally{ MODIF_TYPE:ADJ } tag eng_adverb:vaginally{ MODIF_TYPE:ADJ } tag eng_adverb:vaginometrically{ MODIF_TYPE:ADJ } tag eng_adverb:vaginoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:validly{ MODIF_TYPE:ADJ } tag eng_adverb:variably{ MODIF_TYPE:ADJ } tag eng_adverb:vascularly{ MODIF_TYPE:ADJ } tag eng_adverb:vectorcardiographically{ MODIF_TYPE:ADJ } tag eng_adverb:vectorially{ MODIF_TYPE:ADJ } tag eng_adverb:velocimetrically{ MODIF_TYPE:ADJ } tag eng_adverb:venographically{ MODIF_TYPE:ADJ } tag eng_adverb:ventriculographically{ MODIF_TYPE:ADJ } tag eng_adverb:ventriculo-peritoneally{ MODIF_TYPE:ADJ } tag eng_adverb:ventriculoscopically{ MODIF_TYPE:ADJ } tag eng_adverb:vibrometrically{ MODIF_TYPE:ADJ } //tag eng_adverb:vibrophonocardiographically{ MODIF_TYPE:ADJ } tag eng_adverb:vice versa{ MODIF_TYPE:ADJ } tag eng_adverb:videodensitometrically{ MODIF_TYPE:ADJ } tag eng_adverb:videomicroscopically{ MODIF_TYPE:ADJ } tag eng_adverb:vilely{ MODIF_TYPE:ADJ } tag eng_adverb:virally{ MODIF_TYPE:ADJ } tag eng_adverb:viscometrically{ MODIF_TYPE:ADJ } tag eng_adverb:visuometrically{ MODIF_TYPE:ADJ } tag eng_adverb:vitreally{ MODIF_TYPE:ADJ } tag eng_adverb:voltammetrically{ MODIF_TYPE:ADJ } tag eng_adverb:volubly{ MODIF_TYPE:ADJ } tag eng_adverb:voluptuously{ MODIF_TYPE:ADJ } tag eng_adverb:wastefully{ MODIF_TYPE:ADJ } tag eng_adverb:willfully{ MODIF_TYPE:ADJ } tag eng_adverb:wrathfully{ MODIF_TYPE:ADJ } tag eng_adverb:xenically{ MODIF_TYPE:ADJ } tag eng_adverb:xeromammographically{ MODIF_TYPE:ADJ } tag eng_adverb:xeroradiographically{ MODIF_TYPE:ADJ } tag eng_adverb:zygotically{ MODIF_TYPE:ADJ } tag eng_adverb:zymographically{ MODIF_TYPE:ADJ } tag eng_adverb:just{ MODIF_TYPE:ADJ } tag eng_adverb:almost{ MODIF_TYPE:ADJ } tag eng_adverb:always{ MODIF_TYPE:ADJ } tag eng_adverb:nearly{ MODIF_TYPE:ADJ } // Quarter Horses come in nearly all colors. tag eng_adverb:wide{ MODIF_TYPE:ADJ } // He was wide awake tag eng_adverb:wincingly{ MODIF_TYPE:ADJ } // The speech was wincingly bad tag eng_adverb:startlingly{ MODIF_TYPE:ADJ } // a startlingly modern voice tag eng_adverb:signally{ MODIF_TYPE:ADJ } // signally inappropriate methods tag eng_adverb:shaggily{ MODIF_TYPE:ADJ } // shaggily unkempt mane tag eng_adverb:ruinously{ MODIF_TYPE:ADJ } // ruinously high wages tag eng_adverb:racily{ MODIF_TYPE:ADJ } // racily vernacular language tag eng_adverb:palely{ MODIF_TYPE:ADJ } // a palely entertaining show tag eng_adverb:farcically{ MODIF_TYPE:ADJ } // a farcically inept bungler tag eng_adverb:excusably{ MODIF_TYPE:ADJ } // He was excusably late. tag eng_adverb:only{ MODIF_TYPE:ADJ } #endregion MODIF_TYPE:ADJ #region MODIF_TYPE:VERB tag eng_adverb:weekly{ MODIF_TYPE:VERB } // She visited her aunt weekly. tag eng_adverb:Professionally{ MODIF_TYPE:VERB } // Professionally trained staff tag eng_adverb:greatly{ MODIF_TYPE:VERB } // Feedback is greatly appreciated! tag eng_adverb:then{ MODIF_TYPE:VERB } // He was then imprisoned tag eng_adverb:early{ MODIF_TYPE:VERB } // The sun sets early these days. tag eng_adverb:now{ MODIF_TYPE:VERB } // The brand is now owned by Unilever. tag eng_adverb:late{ MODIF_TYPE:VERB } // As usual, she arrived late. tag eng_adverb:initially{ MODIF_TYPE:VERB } // Selection was initially limited to military pilots. tag eng_adverb:automatically{ MODIF_TYPE:VERB } // This machine automatically cycles. tag eng_adverb:barely{ MODIF_TYPE:VERB } // We barely made the plane. tag eng_adverb:reluctantly{ MODIF_TYPE:VERB } // I gave in and reluctantly mounted the narrow stairs. tag eng_adverb:gradually{ MODIF_TYPE:VERB } // The liquid gradually settled. tag eng_adverb:unblushingly{ MODIF_TYPE:VERB } // His principal opponent unblushingly declared victory before the ballots had been counted. tag eng_adverb:suddenly{ MODIF_TYPE:VERB } // The ship suddenly lurched to the left. tag eng_adverb:just{ MODIF_TYPE:VERB } // He just adored his wife. tag eng_adverb:also{ MODIF_TYPE:VERB } // Inflows of gas into a galaxy also fuel the formation of new stars. tag eng_adverb:seldom{ MODIF_TYPE:VERB } // He seldom suppressed his autobiographical tendencies. tag eng_adverb:slowly{ MODIF_TYPE:VERB } // The reality of his situation slowly dawned on him. tag eng_adverb:slow{ MODIF_TYPE:VERB } tag eng_adverb:fast{ MODIF_TYPE:VERB } // He matured fast. tag eng_adverb:often{ MODIF_TYPE:VERB } // Her husband often abuses alcohol. tag eng_adverb:here{ MODIF_TYPE:VERB } // The perfect climate here develops the grain. tag eng_adverb:immediately{ MODIF_TYPE:VERB } // This immediately concerns your future. tag eng_adverb:implicitly{ MODIF_TYPE:VERB } // I implicitly trust him. tag eng_adverb:strongly{ MODIF_TYPE:VERB } // Mongolian syntax strongly resembles Korean syntax tag eng_adverb:no longer{ MODIF_TYPE:VERB } // Technically, the term is no longer used by experts. tag eng_adverb:flagrantly{ MODIF_TYPE:VERB } // He is flagrantly disregarding the law. tag eng_adverb:kindly{ MODIF_TYPE:VERB } // She kindly overlooked the mistake. tag eng_adverb:pointedly{ MODIF_TYPE:VERB } // He pointedly ignored the question. tag eng_adverb:callously{ MODIF_TYPE:VERB } // He callously exploited their feelings. tag eng_adverb:pompously{ MODIF_TYPE:VERB } // He pompously described his achievements. tag eng_adverb:unerringly{ MODIF_TYPE:VERB } // He unerringly fixed things for us. tag eng_adverb:voluntarily{ MODIF_TYPE:VERB } // He voluntarily submitted to the fingerprinting. tag eng_adverb:cheerfully{ MODIF_TYPE:VERB } // He cheerfully agreed to do it. tag eng_adverb:tenuously{ MODIF_TYPE:VERB } // His works tenuously survive in the minds of a few scholars. tag eng_adverb:angrily{ MODIF_TYPE:VERB } // He angrily denied the accusation. tag eng_adverb:habitually{ MODIF_TYPE:VERB } // He habitually keeps his office door closed. tag eng_adverb:mistakenly{ MODIF_TYPE:VERB } // He mistakenly believed it. tag eng_adverb:universally{ MODIF_TYPE:VERB } // People universally agree on this. tag eng_adverb:considerately{ MODIF_TYPE:VERB } // They considerately withdrew. tag eng_adverb:adamantly{ MODIF_TYPE:VERB } // She adamantly opposed to the marriage. tag eng_adverb:patiently{ MODIF_TYPE:VERB } // He patiently played with the child. tag eng_adverb:actually{ MODIF_TYPE:VERB } // She actually spoke Latin. tag eng_adverb:systematically{ MODIF_TYPE:VERB } // They systematically excluded women. tag eng_adverb:virtually{ MODIF_TYPE:VERB } // The strike virtually paralyzed the city. tag eng_adverb:humbly{ MODIF_TYPE:VERB } // He humbly lowered his head. tag eng_adverb:promptly{ MODIF_TYPE:VERB } // He promptly forgot the address. tag eng_adverb:openly{ MODIF_TYPE:VERB } // He openly flaunted his affection for his sister. tag eng_adverb:unanimously{ MODIF_TYPE:VERB } // The Senate unanimously approved the bill. tag eng_adverb:firmly{ MODIF_TYPE:VERB } // We firmly believed it. tag eng_adverb:rarely{ MODIF_TYPE:VERB } // We rarely met. tag eng_adverb:flatly{ MODIF_TYPE:VERB } // He flatly denied the charges. tag eng_adverb:deftly{ MODIF_TYPE:VERB } // Lois deftly removed her scarf. tag eng_adverb:gallantly{ MODIF_TYPE:VERB } // He gallantly offered to take her home. tag eng_adverb:bureaucratically{ MODIF_TYPE:VERB } // His bureaucratically petty behavior annoyed her. tag eng_adverb:still{ MODIF_TYPE:VERB } // The old man still walks erectly. tag eng_adverb:only{ MODIF_TYPE:VERB } // This event only deepened my convictions. tag eng_adverb:finally{ MODIF_TYPE:VERB } // The pain finally remitted. tag eng_adverb:emulously{ MODIF_TYPE:VERB } // She emulously tried to outdo her older sister. tag eng_adverb:prophetically{ MODIF_TYPE:VERB } // He prophetically anticipated the disaster. tag eng_adverb:instinctively{ MODIF_TYPE:VERB } // He instinctively grabbed the knife. tag eng_adverb:light-heartedly{ MODIF_TYPE:VERB } // He light-heartedly overlooks some of the basic facts of life. tag eng_adverb:lugubriously{ MODIF_TYPE:VERB } // His long face lugubriously reflects a hidden and unexpressed compassion. tag eng_adverb:unreservedly{ MODIF_TYPE:VERB } // I can unreservedly recommend this restaurant! tag eng_adverb:wittily{ MODIF_TYPE:VERB } // He would wittily chime into our conversation. tag eng_adverb:vehemently{ MODIF_TYPE:VERB } // He vehemently denied the accusations against him. tag eng_adverb:verily{ MODIF_TYPE:VERB } // I verily think so. tag eng_adverb:wishfully{ MODIF_TYPE:VERB } // He wishfully indulged in dreams of fame. tag eng_adverb:inaugurally{ MODIF_TYPE:VERB } // The mayor inaugurally drove the spade into the ground. tag eng_adverb:evenly{ MODIF_TYPE:VERB } // A class evenly divided between girls and boys. tag eng_adverb:dutifully{ MODIF_TYPE:VERB } // He dutifully visited his mother every Sunday. tag eng_adverb:slavishly{ MODIF_TYPE:VERB } // His followers slavishly believed in his new diet. tag eng_adverb:roguishly{ MODIF_TYPE:VERB } // He roguishly intended to keep the money. tag eng_adverb:meanly{ MODIF_TYPE:VERB } // This new leader meanly threatens the deepest values of our society. tag eng_adverb:always{ MODIF_TYPE:VERB } // I always stand here. tag eng_adverb:sometimes{ MODIF_TYPE:VERB } // We sometimes go to Spain. tag eng_adverb:now{ MODIF_TYPE:VERB } // He now works for the air force tag eng_adverb:hardly{ MODIF_TYPE:VERB } // She hardly knows. tag eng_adverb:nearly{ MODIF_TYPE:VERB } // I nearly missed the train tag eng_adverb:vigorously{ MODIF_TYPE:VERB } // The lawyer vigorously defended her client tag eng_adverb:thoughtlessly{ MODIF_TYPE:VERB } // He thoughtlessly invited her tag eng_adverb:usually{ MODIF_TYPE:VERB } // He usually walks to work tag eng_adverb:quickly{ MODIF_TYPE:VERB } // He very quickly left the room tag eng_adverb:first{ MODIF_TYPE:VERB } // I have loved you since I first met you tag eng_adverb:allegedly{ MODIF_TYPE:VERB } // He allegedly lost consciousness. tag eng_adverb:already{ MODIF_TYPE:VERB } // I already asked you. tag eng_adverb:unduly{ MODIF_TYPE:VERB } // The speaker unduly criticized his opponent tag eng_adverb:ever{ MODIF_TYPE:VERB } // He never ever sleeps tag eng_adverb:"never ever"{ MODIF_TYPE:VERB } tag eng_adverb:almost{ MODIF_TYPE:VERB } // He almost closed the door. tag eng_adverb:probably{ MODIF_TYPE:VERB } // He probably closed the door tag eng_adverb:fortunately{ MODIF_TYPE:VERB } // He fortunately closed the door tag eng_adverb:biochemically{ MODIF_TYPE:VERB } // We biochemically altered the materials tag eng_adverb:successfully{ MODIF_TYPE:VERB } // He successfully climbed the mountain tag eng_adverb:never{ MODIF_TYPE:VERB } // He never sleeps tag eng_adverb:wisely{ MODIF_TYPE:VERB } // She wisely decided to re-check her homework before submitting it. tag eng_adverb:really{ MODIF_TYPE:VERB } // He really messed up tag eng_adverb:consistently{ MODIF_TYPE:VERB } // Urban interests were consistently underrepresented in the legislature. tag eng_adverb:densely{ MODIF_TYPE:VERB } // The most densely inhabited area is Flanders. tag eng_adverb:sharply{ MODIF_TYPE:VERB } // She was being sharply questioned. tag eng_adverb:up{ MODIF_TYPE:VERB } // The audience got up and applauded. tag eng_adverb:manually{ MODIF_TYPE:VERB } // Tense the rope manually before tensing the spring. tag eng_adverb:sexually{ MODIF_TYPE:VERB } tag eng_adverb:rapidly{ MODIF_TYPE:VERB } // Lanthanum oxidizes rapidly when exposed to air. tag eng_adverb:auspiciously{ MODIF_TYPE:VERB } // He started his new job auspiciously on his birthday. tag eng_adverb:sensitively{ MODIF_TYPE:VERB } // She questioned the rape victim very sensitively about the attack. tag eng_adverb:insensitively{ MODIF_TYPE:VERB } // The police officer questioned the woman rather insensitively about the attack. tag eng_adverb:headlong{ MODIF_TYPE:VERB } // He fell headlong in love with his cousin. tag eng_adverb:compulsively{ MODIF_TYPE:VERB } // He cleaned his shoes compulsively after every walk. tag eng_adverb:additionally{ MODIF_TYPE:VERB } // Most fiction is additionally categorized by genre. tag eng_adverb:severely{ MODIF_TYPE:VERB } // Political freedoms are severely restricted in Burkina Faso. tag eng_adverb:fitfully{ MODIF_TYPE:VERB } // External investment in Botswana has grown fitfully. tag eng_adverb:likely{ MODIF_TYPE:VERB } // His baptism likely took place at Canterbury. tag eng_adverb:chemically{ MODIF_TYPE:VERB } // What is formed when a sodium atom and chlorine atom react chemically? tag eng_adverb:partially{ MODIF_TYPE:VERB } // Simony had been partially checked. tag eng_adverb:freely{ MODIF_TYPE:VERB } // I couldn't move freely. tag eng_adverb:synthetically{ MODIF_TYPE:VERB } // Boron nitride is produced synthetically. tag eng_adverb:ultimately{ MODIF_TYPE:VERB } // The players were ultimately acquitted. tag eng_adverb:differently{ MODIF_TYPE:VERB } // Each type is manufactured differently. tag eng_adverb:alone{ MODIF_TYPE:VERB } // Mature bulls rarely travel alone. tag eng_adverb:geographically{ MODIF_TYPE:VERB } // Church congregations are organized geographically. tag eng_adverb:critically{ MODIF_TYPE:VERB } // The game was critically acclaimed. tag eng_adverb:home{ MODIF_TYPE:VERB } // Kaye flew home for dinner. tag eng_adverb:together{ MODIF_TYPE:VERB } // In colloquium, subjects are grouped together. tag eng_adverb:primarily{ MODIF_TYPE:VERB } // Islam is practised primarily by ethnic Malays. tag eng_adverb:otherwise{ MODIF_TYPE:VERB } // It was otherwise optimized for low-level penetration. tag eng_adverb:traditionally{ MODIF_TYPE:VERB } // It is traditionally written with embossed paper. tag eng_adverb:forward{ MODIF_TYPE:VERB } // They lay flat and kept driving forward. tag eng_adverb:badly{ MODIF_TYPE:VERB } // They are badly damaged by souvenir seekers. tag eng_adverb:even{ MODIF_TYPE:VERB } // This performance was even recorded on video. tag eng_adverb:currently{ MODIF_TYPE:VERB } tag eng_adverb:Frequently{ MODIF_TYPE:VERB } // Frequently invoked in modern logic and philosophy. tag eng_adverb:late{ MODIF_TYPE:VERB } // Gantry later joined The Alan Parsons Project. tag eng_adverb:closely{ MODIF_TYPE:VERB } // The resulting sound closely mimics numerous instruments. tag eng_adverb:down{ MODIF_TYPE:VERB } // Commercial operations will be gradually wound down. tag eng_adverb:independently{ MODIF_TYPE:VERB } // Special forces operate independently under MOD direction. tag eng_adverb:broadly{ MODIF_TYPE:VERB } // Often the word is defined more broadly. tag eng_adverb:back{ MODIF_TYPE:VERB } // Verlinsky did not get his title back. tag eng_adverb:directly{ MODIF_TYPE:VERB } // Plugins can extend the GCC compiler directly. tag eng_adverb:carefully{ MODIF_TYPE:VERB } // Even his fiction contained carefully concealed parables. tag eng_adverb:slightly{ MODIF_TYPE:VERB } // It is sometimes abbreviated slightly to gobbledygoo. tag eng_adverb:since{ MODIF_TYPE:VERB } // Urocor was since acquired by Dianon Systems. tag eng_adverb:out{ MODIF_TYPE:VERB } // They flew out over Skegness and Cromer. tag eng_adverb:as well{ MODIF_TYPE:VERB } // It also broke along generational lines as well; tag eng_adverb:tableside{ MODIF_TYPE:VERB } // It is often prepared tableside. tag eng_adverb:south{ MODIF_TYPE:VERB } // He then continued south towards the Peloponnese. tag eng_adverb:scantily{ MODIF_TYPE:VERB } // Aequian is scantily documented by two inscriptions. tag eng_adverb:abroad{ MODIF_TYPE:VERB } // He had rarely travelled abroad; tag eng_adverb:where{ MODIF_TYPE:VERB } // My taxes go where? tag eng_adverb:today{ MODIF_TYPE:VERB } // This support continues even today. tag eng_adverb:simultaneously{ MODIF_TYPE:VERB } // Chemotherapy may be used simultaneously. tag eng_adverb:backward{ MODIF_TYPE:VERB } // The rotor is tilted backward. tag eng_adverb:regularly{ MODIF_TYPE:VERB } // Security clearances are checked regularly; tag eng_adverb:off{ MODIF_TYPE:VERB } tag eng_adverb:above{ MODIF_TYPE:VERB } tag eng_adverb:hard{ MODIF_TYPE:VERB } tag eng_adverb:skywards{ MODIF_TYPE:VERB } tag eng_adverb:amiss{ MODIF_TYPE:VERB } tag eng_adverb:well{ MODIF_TYPE:VERB } tag eng_adverb:alike{ MODIF_TYPE:VERB } tag eng_adverb:Conically{ MODIF_TYPE:VERB } tag eng_adverb:in{ MODIF_TYPE:VERB } // The wall gave in. tag eng_adverb:near{ MODIF_TYPE:VERB } // They drew nearer. tag eng_adverb:too{ MODIF_TYPE:VERB } tag eng_adverb:over{ MODIF_TYPE:VERB } // Can I sleep over? tag eng_adverb:inwards{ MODIF_TYPE:VERB } // tag eng_adverb:so{ MODIF_TYPE:VERB } // My head aches so! tag eng_adverb:nearby{ MODIF_TYPE:VERB } // She works nearby. tag eng_adverb:easily{ MODIF_TYPE:VERB } // He angers easily. tag eng_adverb:monthly{ MODIF_TYPE:VERB } // They meet monthly. tag eng_adverb:under{ MODIF_TYPE:VERB } // Get under quickly! tag eng_adverb:astray{ MODIF_TYPE:VERB } // He was led astray. tag eng_adverb:whole{ MODIF_TYPE:VERB } // I ate a fish whole! tag eng_adverb:inside{ MODIF_TYPE:VERB } // Was the dog inside? tag eng_adverb:all over{ MODIF_TYPE:VERB } // She ached all over. tag eng_adverb:wide{ MODIF_TYPE:VERB } // Open your eyes wide. tag eng_adverb:upcountry{ MODIF_TYPE:VERB } // They live upcountry. tag eng_adverb:merrily{ MODIF_TYPE:VERB } // The bird sang merrily tag eng_adverb:poorly{ MODIF_TYPE:VERB } // She's feeling poorly. tag eng_adverb:nobly{ MODIF_TYPE:VERB } // She has behaved nobly. tag eng_adverb:low{ MODIF_TYPE:VERB } // The branches hung low. tag eng_adverb:heavenward{ MODIF_TYPE:VERB } // He pointed heavenward. tag eng_adverb:loudly{ MODIF_TYPE:VERB } // Don't speak so loudly. tag eng_adverb:wanly{ MODIF_TYPE:VERB } // She was smiling wanly. tag eng_adverb:leisurely{ MODIF_TYPE:VERB } // He traveled leisurely. tag eng_adverb:by{ MODIF_TYPE:VERB } // An enemy plane flew by. tag eng_adverb:westerly{ MODIF_TYPE:VERB } // The wind blew westerly. tag eng_adverb:outright{ MODIF_TYPE:VERB } // He was killed outright. tag eng_adverb:quietly{ MODIF_TYPE:VERB } // She was crying quietly. tag eng_adverb:sideways{ MODIF_TYPE:VERB } // A picture lit sideways. tag eng_adverb:legibly{ MODIF_TYPE:VERB } // You must write legibly. tag eng_adverb:rationally{ MODIF_TYPE:VERB } // We must act rationally. tag eng_adverb:westbound{ MODIF_TYPE:VERB } // He was driving westbound tag eng_adverb:malapropos{ MODIF_TYPE:VERB } // She answered malapropos. tag eng_adverb:man-to-man{ MODIF_TYPE:VERB } // We must talk man-to-man. tag eng_adverb:face to face{ MODIF_TYPE:VERB } // They spoke face to face. tag eng_adverb:soon{ MODIF_TYPE:VERB } // The time will come soon. tag eng_adverb:cleanly{ MODIF_TYPE:VERB } // The motor burns cleanly. tag eng_adverb:responsibly{ MODIF_TYPE:VERB } // We must act responsibly. tag eng_adverb:weirdly{ MODIF_TYPE:VERB } // She was dressed weirdly. tag eng_adverb:plainly{ MODIF_TYPE:VERB } // She was dressed plainly. tag eng_adverb:tight{ MODIF_TYPE:VERB } // The pub was packed tight. tag eng_adverb:noisily{ MODIF_TYPE:VERB } // He blew his nose noisily. tag eng_adverb:raucously{ MODIF_TYPE:VERB } // His voice rang raucously. tag eng_adverb:hand in hand{ MODIF_TYPE:VERB } // They walked hand in hand. tag eng_adverb:onshore{ MODIF_TYPE:VERB } // They were living onshore. tag eng_adverb:outside{ MODIF_TYPE:VERB } // In summer we play outside. tag eng_adverb:presently{ MODIF_TYPE:VERB } // She will arrive presently. tag eng_adverb:head-on{ MODIF_TYPE:VERB } // The cars collided head-on. tag eng_adverb:seaward{ MODIF_TYPE:VERB } // The sailor looked seaward. tag eng_adverb:roundly{ MODIF_TYPE:VERB } // He was criticized roundly. tag eng_adverb:aloft{ MODIF_TYPE:VERB } // Eagles were soaring aloft. tag eng_adverb:singly{ MODIF_TYPE:VERB } // They were arranged singly. tag eng_adverb:in vain{ MODIF_TYPE:VERB } // He looked for her in vain. tag eng_adverb:crosswise{ MODIF_TYPE:VERB } // Things are going crosswise. tag eng_adverb:behind{ MODIF_TYPE:VERB } // My watch is running behind. tag eng_adverb:sky-high{ MODIF_TYPE:VERB } // Garbage was piled sky-high. tag eng_adverb:uppermost{ MODIF_TYPE:VERB } // The blade turned uppermost. tag eng_adverb:dourly{ MODIF_TYPE:VERB } // He sat in his chair dourly. tag eng_adverb:transversely{ MODIF_TYPE:VERB } // They were cut transversely. tag eng_adverb:thick{ MODIF_TYPE:VERB } // Snow lay thick on the ground tag eng_adverb:negligently{ MODIF_TYPE:VERB } // He did his work negligently. tag eng_adverb:posthumously{ MODIF_TYPE:VERB } // He was honored posthumously. tag eng_adverb:hopelessly{ MODIF_TYPE:VERB } // He hung his head hopelessly. tag eng_adverb:unhesitatingly{ MODIF_TYPE:VERB } // She said yes unhesitatingly. tag eng_adverb:yesterday{ MODIF_TYPE:VERB } // I swam in the river yesterday tag eng_adverb:hot{ MODIF_TYPE:VERB } // The casserole was piping hot. tag eng_adverb:steadily{ MODIF_TYPE:VERB } // His interest eroded steadily. tag eng_adverb:shortly{ MODIF_TYPE:VERB } // The book will appear shortly. tag eng_adverb:coastwise{ MODIF_TYPE:VERB } // We were travelling coastwise. tag eng_adverb:fearfully{ MODIF_TYPE:VERB } // They were fearfully attacked. tag eng_adverb:mechanically{ MODIF_TYPE:VERB } // This door opens mechanically. tag eng_adverb:half-and-half{ MODIF_TYPE:VERB } // It was divided half-and-half. tag eng_adverb:repeatedly{ MODIF_TYPE:VERB } // It must be washed repeatedly. tag eng_adverb:excitedly{ MODIF_TYPE:VERB } // She shook his hand excitedly. tag eng_adverb:affectionately{ MODIF_TYPE:VERB } // He treats her affectionately. tag eng_adverb:somewhat{ MODIF_TYPE:VERB } // Unfortunately the surviving copy is somewhat mutilated. tag eng_adverb:socially{ MODIF_TYPE:VERB } // In this view expertise is socially constructed; tag eng_adverb:uniformly{ MODIF_TYPE:VERB } // However, this is not uniformly accepted. tag eng_adverb:subsequently{ MODIF_TYPE:VERB } // These were subsequently confirmed by Heinrich Hertz. tag eng_adverb:effectively{ MODIF_TYPE:VERB } // The country was effectively divided in two. tag eng_adverb:asleep{ MODIF_TYPE:VERB } // When she fell asleep Apollo raped her. tag eng_adverb:similarly{ MODIF_TYPE:VERB } // Financial engineering has similarly borrowed the term. tag eng_adverb:generally{ MODIF_TYPE:VERB } // Universities are generally composed of several colleges. tag eng_adverb:formally{ MODIF_TYPE:VERB } // These cells are formally called equivalence classes. tag eng_adverb:precipitously{ MODIF_TYPE:VERB } tag eng_adverb:easterly{ MODIF_TYPE:VERB } // The winds blew easterly all night. tag eng_adverb:unchangeably{ MODIF_TYPE:VERB } // His views were unchangeably fixed. tag eng_adverb:asymmetrically{ MODIF_TYPE:VERB } // They were asymmetrically arranged. tag eng_adverb:upstage{ MODIF_TYPE:VERB } // The actor turned and walked upstage tag eng_adverb:foully{ MODIF_TYPE:VERB } // Two policemen were foully murdered. tag eng_adverb:unpleasantly{ MODIF_TYPE:VERB } // He has been unpleasantly surprised. tag eng_adverb:overnight{ MODIF_TYPE:VERB } // The mud had consolidated overnight. tag eng_adverb:east{ MODIF_TYPE:VERB } // We travelled east for several miles. tag eng_adverb:west{ MODIF_TYPE:VERB } tag eng_adverb:amply{ MODIF_TYPE:VERB } // These voices were amply represented. tag eng_adverb:tonight{ MODIF_TYPE:VERB } // She is flying to Cincinnati tonight. tag eng_adverb:ninefold { MODIF_TYPE:VERB } // My investment has increased ninefold. tag eng_adverb:noticeably{ MODIF_TYPE:VERB } // He changed noticeably over the years. tag eng_adverb:awry{ MODIF_TYPE:VERB } // Something has gone awry in our plans. tag eng_adverb:zigzag{ MODIF_TYPE:VERB } // Birds flew zigzag across the blue sky. tag eng_adverb:cosmetically{ MODIF_TYPE:VERB } // It is used cosmetically by many women. tag eng_adverb:casually{ MODIF_TYPE:VERB } // He dealt with his course work casually. tag eng_adverb:shiftily{ MODIF_TYPE:VERB } // He looked at his new customer shiftily. tag eng_adverb:perplexedly{ MODIF_TYPE:VERB } // He looked at his professor perplexedly. tag eng_adverb:impassively{ MODIF_TYPE:VERB } // He submitted impassively to his arrest. tag eng_adverb:supinely{ MODIF_TYPE:VERB } // She was stretched supinely on her back. tag eng_adverb:clear{ MODIF_TYPE:VERB } // The bullet went clear through the wall. tag eng_adverb:unquestioningly{ MODIF_TYPE:VERB } // He followed his leader unquestioningly. tag eng_adverb:stoutly{ MODIF_TYPE:VERB } // He was stoutly replying to his critics. tag eng_adverb:apologetically{ MODIF_TYPE:VERB } // He spoke apologetically about his past. tag eng_adverb:readily{ MODIF_TYPE:VERB } // These snakes can be identified readily. tag eng_adverb:kinesthetically{ MODIF_TYPE:VERB } // He can perceive shapes kinesthetically. tag eng_adverb:microscopically{ MODIF_TYPE:VERB } // The blood was examined microscopically. tag eng_adverb:separably{ MODIF_TYPE:VERB } // The two ideas were considered separably. tag eng_adverb:administratively{ MODIF_TYPE:VERB } // This decision was made administratively. tag eng_adverb:inconspicuously{ MODIF_TYPE:VERB } // He had entered the room inconspicuously. tag eng_adverb:condescendingly{ MODIF_TYPE:VERB } // He treats his secretary condescendingly. tag eng_adverb:underground{ MODIF_TYPE:VERB } // The organization was driven underground. tag eng_adverb:vivaciously{ MODIF_TYPE:VERB } // He describes his adventures vivaciously. tag eng_adverb:macroscopically{ MODIF_TYPE:VERB } // The tubes were examined macroscopically. tag eng_adverb:temperately{ MODIF_TYPE:VERB } // These preferences are temperately stated. tag eng_adverb:northeastward{ MODIF_TYPE:VERB } // The river flows northeastward to the gulf. tag eng_adverb:southeastward{ MODIF_TYPE:VERB } // The river flows southeastward to the gulf. tag eng_adverb:unattractively{ MODIF_TYPE:VERB } // She was unattractively dressed last night. tag eng_adverb:insolently{ MODIF_TYPE:VERB } // He had replied insolently to his superiors. tag eng_adverb:downstream{ MODIF_TYPE:VERB } // The raft floated downstream on the current. tag eng_adverb:restrictively{ MODIF_TYPE:VERB } // This relative clause is used restrictively. tag eng_adverb:sedulously{ MODIF_TYPE:VERB } // This illusion has been sedulously fostered. tag eng_adverb:lukewarmly{ MODIF_TYPE:VERB } // He was lukewarmly received by his relatives. tag eng_adverb:erratically{ MODIF_TYPE:VERB } // Economic changes are proceeding erratically. tag eng_adverb:bombastically{ MODIF_TYPE:VERB } // He lectured bombastically about his theories. tag eng_adverb:maniacally{ MODIF_TYPE:VERB } // He will be maniacally obsessed with jealousy. tag eng_adverb:interdepartmentally{ MODIF_TYPE:VERB } // This memo was circulated interdepartmentally. tag eng_adverb:rhythmically{ MODIF_TYPE:VERB } // The chair rocked rhythmically back and forth. tag eng_adverb:piggyback{ MODIF_TYPE:VERB } // The trailer rode piggyback across the country. tag eng_adverb:inadequately{ MODIF_TYPE:VERB } // The temporary camps were inadequately equipped. tag eng_adverb:piecemeal{ MODIF_TYPE:VERB } // The research structure has developed piecemeal. tag eng_adverb:mournfully{ MODIF_TYPE:VERB } // The young man stared into his glass mournfully. tag eng_adverb:regretfully{ MODIF_TYPE:VERB } // I must regretfully decline your kind invitation. tag eng_adverb:airily{ MODIF_TYPE:VERB } // This cannot be airily explained to your children. tag eng_adverb:needlessly{ MODIF_TYPE:VERB } // It would needlessly bring badness into the world. tag eng_adverb:upstairs{ MODIF_TYPE:VERB } // He went upstairs into the best rooms only on rare occasions. tag eng_adverb:hurriedly{ MODIF_TYPE:VERB } // They departed hurriedly because of some great urgency in their affairs. tag eng_adverb:distinctly{ MODIF_TYPE:VERB } // Urbanization in Spain is distinctly correlated with a fall in reproductive rate. tag eng_adverb:upside down{ MODIF_TYPE:VERB } // The thief had turned the room upside down tag eng_adverb:edgeways{ MODIF_TYPE:VERB } // He sawed the board edgeways. tag eng_adverb:far{ MODIF_TYPE:VERB } // Branches are straggling out quite far. tag eng_adverb:mainly{ MODIF_TYPE:VERB } // He is mainly interested in butterflies. tag eng_adverb:broadside{ MODIF_TYPE:VERB } // The train hit the truck broadside. tag eng_adverb:high{ MODIF_TYPE:VERB } // The eagle beat its wings and soared high into the sky. tag eng_adverb:aside{ MODIF_TYPE:VERB } // Put her sewing aside when he entered. tag eng_adverb:eastward{ MODIF_TYPE:VERB } // We have to advance clocks and watches when we travel eastward. tag eng_adverb:stateside{ MODIF_TYPE:VERB } // I'll be going stateside next month! tag eng_adverb:counterclockwise{ MODIF_TYPE:VERB } // Please move counterclockwise in a circle! tag eng_adverb:eventually{ MODIF_TYPE:VERB } // tag eng_adverb:widely{ MODIF_TYPE:VERB } // It was widely adopted as a replacement. tag eng_adverb:duly{ MODIF_TYPE:VERB } // A band was duly assembled. tag eng_adverb:close{ MODIF_TYPE:VERB } // Come closer, my dear! tag eng_adverb:deeply{ MODIF_TYPE:VERB } // I was deeply impressed. tag eng_adverb:officially{ MODIF_TYPE:VERB } // Citizens are officially called Barbadians. tag eng_adverb:north{ MODIF_TYPE:VERB } // Let's go north! tag eng_adverb:clearly{ MODIF_TYPE:VERB } // They were clearly lost. tag eng_adverb:aloud{ MODIF_TYPE:VERB } // Please read the passage aloud. tag eng_adverb:tomorrow{ MODIF_TYPE:VERB } // I shall buy a new pen tomorrow tag eng_adverb:romantically{ MODIF_TYPE:VERB } // They were romantically linked. tag eng_adverb:barbarously{ MODIF_TYPE:VERB } // They were barbarously murdered. tag eng_adverb:empirically{ MODIF_TYPE:VERB } // This can be empirically tested. tag eng_adverb:substantially{ MODIF_TYPE:VERB } // The price went up substantially tag eng_adverb:overhead{ MODIF_TYPE:VERB } // The seagulls fluttered overhead. tag eng_adverb:offstage{ MODIF_TYPE:VERB } // The actors were waiting offstage. tag eng_adverb:overseas{ MODIF_TYPE:VERB } // He lived overseas for many years. tag eng_adverb:tenfold{ MODIF_TYPE:VERB } // The population increased tenfold. tag eng_adverb:symmetrically{ MODIF_TYPE:VERB } // They were asymmetrically arranged. tag eng_adverb:clockwise{ MODIF_TYPE:VERB } // Please move clockwise in a circle. tag eng_adverb:typically{ MODIF_TYPE:VERB } // Priming effects are typically analysed as being internal to the IT classification system. tag eng_adverb:experimentally{ MODIF_TYPE:VERB } // This can be experimentally determined. tag eng_adverb:inherently{ MODIF_TYPE:VERB } // Module and chip characteristics are inherently linked. #endregion MODIF_TYPE:VERB // The roles are but three; tag eng_adverb:but{ MODIF_TYPE:NUMBER } }
He would wittily chime into our conversation.
tag eng_adverb:wittily{ MODIF_TYPE:VERB }
6,445,964
[ 1, 5256, 4102, 31039, 1025, 93, 462, 494, 1368, 3134, 10039, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 2692, 24691, 67, 361, 16629, 30, 28450, 1025, 93, 95, 8663, 5501, 67, 2399, 30, 2204, 38, 289, 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 ]
./full_match/5/0x8798334320e74FA8156130c61A61aFBe647a850d/sources/contracts/ERC721PresetMinterPauserAutoId.sol
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the account that deploys the contract. Token URIs will be autogenerated based on `baseURI` and their token IDs. See {ERC721-tokenURI}./
) ERC721(name, symbol) { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); _setupRole(BASE_URI_SETTER_ROLE, _msgSender()); }
7,055,999
[ 1, 29598, 1375, 5280, 67, 15468, 67, 16256, 9191, 1375, 6236, 2560, 67, 16256, 68, 471, 1375, 4066, 4714, 67, 16256, 68, 358, 326, 2236, 716, 5993, 383, 1900, 326, 6835, 18, 3155, 24565, 903, 506, 7840, 2511, 603, 1375, 1969, 3098, 68, 471, 3675, 1147, 7115, 18, 2164, 288, 654, 39, 27, 5340, 17, 2316, 3098, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 262, 4232, 39, 27, 5340, 12, 529, 16, 3273, 13, 288, 203, 203, 203, 3639, 389, 8401, 2996, 12, 5280, 67, 15468, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 203, 3639, 389, 8401, 2996, 12, 6236, 2560, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 3639, 389, 8401, 2996, 12, 4066, 4714, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 3639, 389, 8401, 2996, 12, 8369, 67, 3098, 67, 1090, 11976, 67, 16256, 16, 389, 3576, 12021, 10663, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xd924AdA45Ead5B3A0f6025893AE14282A3da8f35/sources/contracts/YoinkIt.sol
Add to the current round if the game is active
currentRoundPrizePool += msg.value;
7,042,926
[ 1, 986, 358, 326, 783, 3643, 309, 326, 7920, 353, 2695, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5411, 783, 11066, 2050, 554, 2864, 1011, 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, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; // For safe math operations library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; assert(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; assert(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // sets owner of contract, allows for ownership transfer contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner, "Only Owner Can Call This function"); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // basic token implementation, with only required functions interface token{ function approve(address _spender, uint _value) external returns (bool success); function transferFrom(address _from, address _to, uint _tokens) external returns (bool success); function transfer(address _to, uint _value)external returns (bool success); } // basic Crowdsale contract contract Crowdsale{ using SafeMath for uint; // wallet in which ether will be sent to address public organizationWallet; // token to be used fo reward token public tokenForReward; // name of tokenForReward string public nameOfTokenForReward; // How many token units a buyer gets per wei uint24 public ratePer; // amount raised in wei uint public weiRaised; // event logging purchase of token event TokenPurchase(address indexed purchaser, uint256 value, uint256 amount); modifier isNotNullAddress{ require(tokenForReward != address(0)); _; } modifier isNotNullWallet{ require(organizationWallet != address(0)); _; } function etherRaised() public view returns(uint){ return weiRaised / 1 ether; } } contract AdvanceCrowdsale is Crowdsale, Owned{ // is paused bool public isPaused; // has started bool public isStarted; // has ended bool public isEnded; // which phase is sale on uint8 public phase; uint public rewardTokensAvailable ; // reduces with every purchase uint public tokensApprovedForReward; // constant amount after funding uint public minimumPurchase; // minimum purchase amount in wei. if 0 then no minimum uint public maximumPurchase; // maximum purchase amount in wei. if 0 then no maximum // add to functions which should only execute if sale is on modifier saleIsOn{ require(isStarted && !isEnded && !isPaused, "sale not on"); _; } modifier onlyWhenPaused{ if(!isPaused && isStarted) revert(); _; } // returns if crowdsale is accepting purchase function isAcceptingPurchase() public view returns(bool){ return (isStarted && !isEnded && !isPaused); } // returns if crowdsale has been completed function isCompleted() public view returns(bool){ return (isEnded&&isStarted); } // used by owner to pause or unpause sale function pauseOrUnpause() public onlyOwner{ require(isStarted&&!isEnded, "sale has not started"); if(isPaused){ isPaused = false; }else{ isPaused = true; } } //used by owner to end sale function endSale() public onlyOwner{ require(!isEnded); isEnded = true; } // change organizationWallet function changeOrgWallet(address _wallet) public onlyOwner{ require(_wallet != address(0)); organizationWallet = _wallet; } // set a token for reward function setTokenForReward(address _tokenAddress) public onlyOwner{ require(isContract(_tokenAddress)); tokenForReward = token(_tokenAddress); } // set name of token function setNameOfTokenForReward(string _name) public onlyOwner isNotNullAddress{ nameOfTokenForReward = _name; } // function used to check if address is a contract function isContract(address _addr) internal 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); } // used by owner to start sale function startSale() public onlyOwner{ require(!isEnded&&!isStarted); require(tokenForReward != address(0), "set a token to use for reward"); require(tokensApprovedForReward > 0, "must send tokens to crowdsale using approveAndCall"); phase = 1; isStarted = true; isPaused = false; } // set minimum purchase turned into ether equivalent. 100 == 1 ether // 10 equals 0.10 ether and so on function onlyOwnerSetMinimum(uint24 _minimum)public onlyOwner onlyWhenPaused{ if(_minimum == 0){ require(minimumPurchase != 0); minimumPurchase = _minimum; }else{ uint24 minimumAmount = _minimum/100; minimumPurchase = uint(minimumAmount * 1 ether); } } // set maximum purchase turned into ether equivalent. 100 == 1 ether // 10 equals 0.10 ether and so on function onlyOwnerSetMaximum(uint24 _maximum)public onlyOwner onlyWhenPaused{ if(_maximum == 0){ require(maximumPurchase != 0, "Already set to zero"); maximumPurchase = _maximum; // sets to zero == no maximum }else{ require(_maximum > minimumPurchase, "maximum must be greater than minimumPurchase"); uint24 maximumAmount = _maximum/100; maximumPurchase = uint(maximumAmount * 1 ether); } } // used to change rate of tokens per ether function onlyOwnerChangeRate(uint24 _rate)public onlyOwner onlyWhenPaused returns (bool success){ ratePer = _rate; return true; } // change the phase function onlyOwnerChangePhase(uint8 _phase) public onlyOwner onlyWhenPaused returns (bool success){ phase = _phase; return true; } function onlyOwnerChangeWallet(address _newWallet) public onlyOwner onlyWhenPaused returns(bool success){ require(!isContract(_newWallet)); organizationWallet = _newWallet; return true; } // withdraw ether raised to Organization Wallet function onlyOwnerWithdraw() external onlyOwner returns (bool){ require(isCompleted()); // get ether balance uint amount = address(this).balance; require(amount > 0); // transfer balance of ether to Organization's Wallet organizationWallet.transfer(amount); return true; } } contract OMainSale is AdvanceCrowdsale{ mapping(address => uint) public allowed; // mapping of address and tokens allowed for withdrawal mapping(address => uint) public contributions; event OMainSaleFunded(address indexed _funder, uint _amount,address indexed _rewardToken, bytes _data); // log when contract is fund event TokensWithdrawn(address indexed _backer, address indexed _beneficiary, uint _amount); constructor(address _orgWallet, address _tokenAddress, uint24 _rate) public{ isPaused = true; isStarted = false; isEnded = false; organizationWallet = address(_orgWallet); tokenForReward = token(_tokenAddress); ratePer = _rate; } // called when sent spending approval using approveAndCall() of token function receiveApproval(address _from, uint _tokens, address _theToken, bytes _data) public{ require(address(tokenForReward) == address(_theToken)); require(address(_from) == owner, "must be funded by owner"); require(tokensApprovedForReward == 0 && _tokens > 0); // sets the total tokens available tokensApprovedForReward = _tokens; rewardTokensAvailable = tokensApprovedForReward; bool success = token(_theToken).transferFrom(_from, this, _tokens); require(success); emit OMainSaleFunded(_from, _tokens, _theToken, _data); } // used to buy tokens, will revert if sale isn't on function buyToken() public saleIsOn payable{ uint weiAmount = msg.value; _preValidatePurchase(weiAmount); uint numOfTokens = weiAmount.mul(ratePer); require(rewardTokensAvailable >= numOfTokens); weiRaised = weiRaised.add(weiAmount); contributions[msg.sender] = contributions[msg.sender].add(weiAmount); _postValidatePurchase(msg.sender); rewardTokensAvailable = rewardTokensAvailable.sub(numOfTokens); allowed[msg.sender] = allowed[msg.sender].add(numOfTokens); emit TokenPurchase(msg.sender, weiAmount, numOfTokens); } // return tokens to msg.sender will be receiving. can't check for others function tokensToReceive() public view returns (uint){ return allowed[msg.sender]; } // used by participants to get withdraw token into wallet. must be called by function getYourTokens(address _beneficiary) public returns(bool success) { // sale must have have ended require(allowed[msg.sender] > 0); require(isCompleted()); uint payoutAmount = allowed[msg.sender]; allowed[msg.sender] = 0; if (_beneficiary == address(0)){ success = tokenForReward.transfer(msg.sender, payoutAmount); require(success); emit TokensWithdrawn(msg.sender, msg.sender, payoutAmount); }else { success = tokenForReward.transfer(_beneficiary, payoutAmount); require(success); emit TokensWithdrawn(msg.sender, _beneficiary, payoutAmount); } } function _preValidatePurchase( uint256 _weiAmount) internal pure { require(_weiAmount != 0); } /** * validate after purchase */ function _postValidatePurchase(address _sender) internal view{ // check minimums if(minimumPurchase > 0){ require(contributions[_sender] >= minimumPurchase, "contributions less than minimum"); } // check maximums if(maximumPurchase > 0){ require(contributions[_sender] <= maximumPurchase, "contributions greater than maximum"); } } }
set maximum purchase turned into ether equivalent. 100 == 1 ether 10 equals 0.10 ether and so on
function onlyOwnerSetMaximum(uint24 _maximum)public onlyOwner onlyWhenPaused{ if(_maximum == 0){ require(maximumPurchase != 0, "Already set to zero"); require(_maximum > minimumPurchase, "maximum must be greater than minimumPurchase"); uint24 maximumAmount = _maximum/100; maximumPurchase = uint(maximumAmount * 1 ether); } }
13,062,225
[ 1, 542, 4207, 23701, 21826, 1368, 225, 2437, 7680, 18, 2130, 422, 404, 225, 2437, 1728, 1606, 374, 18, 2163, 225, 2437, 471, 1427, 603, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1338, 5541, 694, 13528, 12, 11890, 3247, 389, 15724, 13, 482, 1338, 5541, 1338, 9434, 28590, 95, 203, 540, 203, 3639, 309, 24899, 15724, 422, 374, 15329, 203, 5411, 2583, 12, 15724, 23164, 480, 374, 16, 315, 9430, 444, 358, 3634, 8863, 203, 5411, 2583, 24899, 15724, 405, 5224, 23164, 16, 315, 15724, 1297, 506, 6802, 2353, 5224, 23164, 8863, 203, 5411, 2254, 3247, 4207, 6275, 273, 389, 15724, 19, 6625, 31, 203, 5411, 4207, 23164, 273, 2254, 12, 15724, 6275, 380, 404, 225, 2437, 1769, 203, 3639, 289, 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 ]
./partial_match/1/0xCFB70415aAc3Ed12C496758DDca54E7c7dAB053f/sources/wyckett_tea_potts.sol
Owner Only Function
function flipSaleState() external onlyOwner { isSaleActive = !isSaleActive; }
16,059,648
[ 1, 5541, 5098, 4284, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 565, 445, 9668, 30746, 1119, 1435, 3903, 1338, 5541, 288, 203, 3639, 11604, 5349, 3896, 273, 401, 291, 30746, 3896, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x9e570c99d6AdA14E8A8f2A54D6E4895d51ecD6ab/sources/browser/github/radicle-dev/radicle-contracts/contracts/Pool.sol
The sum of all the future changes to the per-second amount the proxy receives. This is also the per-second amount the proxy receives per weight in the current cycle, but with its sign inverted. Thus if `multiplier` is `1`, then this value is negative and if `-1`, it's positive.
int128 totalDelta = 0;
14,129,591
[ 1, 1986, 2142, 434, 777, 326, 3563, 3478, 358, 326, 1534, 17, 8538, 3844, 326, 2889, 17024, 18, 1220, 353, 2546, 326, 1534, 17, 8538, 3844, 326, 2889, 17024, 1534, 3119, 316, 326, 783, 8589, 16, 1496, 598, 2097, 1573, 18150, 18, 22073, 309, 1375, 20538, 68, 353, 1375, 21, 9191, 1508, 333, 460, 353, 6092, 471, 309, 1375, 17, 21, 9191, 518, 1807, 6895, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 3639, 509, 10392, 2078, 9242, 273, 374, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol'; import {IReserveInterestRateStrategy} from '../../interfaces/IReserveInterestRateStrategy.sol'; import {WadRayMath} from '../libraries/math/WadRayMath.sol'; import {PercentageMath} from '../libraries/math/PercentageMath.sol'; import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol'; import {ILendingRateOracle} from '../../interfaces/ILendingRateOracle.sol'; /** * @title DefaultReserveInterestRateStrategy contract * @notice Implements the calculation of the interest rates depending on the reserve state * @dev The model of interest rate is based on 2 slopes, one before the `OPTIMAL_UTILIZATION_RATE` * point of utilization and another from that one to 100% * - An instance of this same contract, can't be used across different Aave markets, due to the caching * of the LendingPoolAddressesProvider * @author Aave **/ contract DefaultReserveInterestRateStrategy is IReserveInterestRateStrategy { using WadRayMath for uint256; using SafeMath for uint256; using PercentageMath for uint256; /** * @dev this constant represents the utilization rate at which the pool aims to obtain most competitive borrow rates. * Expressed in ray **/ uint256 public immutable OPTIMAL_UTILIZATION_RATE; /** * @dev This constant represents the excess utilization rate above the optimal. It's always equal to * 1-optimal utilization rate. Added as a constant here for gas optimizations. * Expressed in ray **/ uint256 public immutable EXCESS_UTILIZATION_RATE; ILendingPoolAddressesProvider public immutable addressesProvider; // Base variable borrow rate when Utilization rate = 0. Expressed in ray uint256 internal immutable _baseVariableBorrowRate; // Slope of the variable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _variableRateSlope1; // Slope of the variable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _variableRateSlope2; // Slope of the stable interest curve when utilization rate > 0 and <= OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _stableRateSlope1; // Slope of the stable interest curve when utilization rate > OPTIMAL_UTILIZATION_RATE. Expressed in ray uint256 internal immutable _stableRateSlope2; constructor( ILendingPoolAddressesProvider provider, uint256 optimalUtilizationRate, uint256 baseVariableBorrowRate, uint256 variableRateSlope1, uint256 variableRateSlope2, uint256 stableRateSlope1, uint256 stableRateSlope2 ) public { OPTIMAL_UTILIZATION_RATE = optimalUtilizationRate; EXCESS_UTILIZATION_RATE = WadRayMath.ray().sub(optimalUtilizationRate); addressesProvider = provider; _baseVariableBorrowRate = baseVariableBorrowRate; _variableRateSlope1 = variableRateSlope1; _variableRateSlope2 = variableRateSlope2; _stableRateSlope1 = stableRateSlope1; _stableRateSlope2 = stableRateSlope2; } function variableRateSlope1() external view returns (uint256) { return _variableRateSlope1; } function variableRateSlope2() external view returns (uint256) { return _variableRateSlope2; } function stableRateSlope1() external view returns (uint256) { return _stableRateSlope1; } function stableRateSlope2() external view returns (uint256) { return _stableRateSlope2; } function baseVariableBorrowRate() external view override returns (uint256) { return _baseVariableBorrowRate; } function getMaxVariableBorrowRate() external view override returns (uint256) { return _baseVariableBorrowRate.add(_variableRateSlope1).add(_variableRateSlope2); } struct CalcInterestRatesLocalVars { uint256 totalDebt; uint256 currentVariableBorrowRate; uint256 currentStableBorrowRate; uint256 currentLiquidityRate; uint256 utilizationRate; } /** * @dev Calculates the interest rates depending on the reserve's state and configurations * @param reserve The address of the reserve * @param availableLiquidity The liquidity available in the reserve * @param totalStableDebt The total borrowed from the reserve a stable rate * @param totalVariableDebt The total borrowed from the reserve at a variable rate * @param averageStableBorrowRate The weighted average of all the stable rate loans * @param reserveFactor The reserve portion of the interest that goes to the treasury of the market * @return The liquidity rate, the stable borrow rate and the variable borrow rate **/ function calculateInterestRates( address reserve, uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view override returns ( uint256, uint256, uint256 ) { CalcInterestRatesLocalVars memory vars; vars.totalDebt = totalStableDebt.add(totalVariableDebt); vars.currentVariableBorrowRate = 0; vars.currentStableBorrowRate = 0; vars.currentLiquidityRate = 0; uint256 utilizationRate = vars.totalDebt == 0 ? 0 : vars.totalDebt.rayDiv(availableLiquidity.add(vars.totalDebt)); vars.currentStableBorrowRate = ILendingRateOracle(addressesProvider.getLendingRateOracle()) .getMarketBorrowRate(reserve); if (utilizationRate > OPTIMAL_UTILIZATION_RATE) { uint256 excessUtilizationRateRatio = utilizationRate.sub(OPTIMAL_UTILIZATION_RATE).rayDiv(EXCESS_UTILIZATION_RATE); vars.currentStableBorrowRate = vars.currentStableBorrowRate.add(_stableRateSlope1).add( _stableRateSlope2.rayMul(excessUtilizationRateRatio) ); vars.currentVariableBorrowRate = _baseVariableBorrowRate.add(_variableRateSlope1).add( _variableRateSlope2.rayMul(excessUtilizationRateRatio) ); } else { vars.currentStableBorrowRate = vars.currentStableBorrowRate.add( _stableRateSlope1.rayMul(utilizationRate.rayDiv(OPTIMAL_UTILIZATION_RATE)) ); vars.currentVariableBorrowRate = _baseVariableBorrowRate.add( utilizationRate.rayMul(_variableRateSlope1).rayDiv(OPTIMAL_UTILIZATION_RATE) ); } vars.currentLiquidityRate = _getOverallBorrowRate( totalStableDebt, totalVariableDebt, vars .currentVariableBorrowRate, averageStableBorrowRate ) .rayMul(utilizationRate) .percentMul(PercentageMath.PERCENTAGE_FACTOR.sub(reserveFactor)); return ( vars.currentLiquidityRate, vars.currentStableBorrowRate, vars.currentVariableBorrowRate ); } /** * @dev Calculates the overall borrow rate as the weighted average between the total variable debt and total stable debt * @param totalStableDebt The total borrowed from the reserve a stable rate * @param totalVariableDebt The total borrowed from the reserve at a variable rate * @param currentVariableBorrowRate The current variable borrow rate of the reserve * @param currentAverageStableBorrowRate The current weighted average of all the stable rate loans * @return The weighted averaged borrow rate **/ function _getOverallBorrowRate( uint256 totalStableDebt, uint256 totalVariableDebt, uint256 currentVariableBorrowRate, uint256 currentAverageStableBorrowRate ) internal pure returns (uint256) { uint256 totalDebt = totalStableDebt.add(totalVariableDebt); if (totalDebt == 0) return 0; uint256 weightedVariableRate = totalVariableDebt.wadToRay().rayMul(currentVariableBorrowRate); uint256 weightedStableRate = totalStableDebt.wadToRay().rayMul(currentAverageStableBorrowRate); uint256 overallBorrowRate = weightedVariableRate.add(weightedStableRate).rayDiv(totalDebt.wadToRay()); return overallBorrowRate; } } // SPDX-License-Identifier: agpl-3.0 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. */ 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; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title IReserveInterestRateStrategyInterface interface * @dev Interface for the calculation of the interest rates * @author Aave */ interface IReserveInterestRateStrategy { function baseVariableBorrowRate() external view returns (uint256); function getMaxVariableBorrowRate() external view returns (uint256); function calculateInterestRates( address reserve, uint256 utilizationRate, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 averageStableBorrowRate, uint256 reserveFactor ) external view returns ( uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate ); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; /** * @title WadRayMath library * @author Aave * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits) **/ library WadRayMath { uint256 internal constant WAD = 1e18; uint256 internal constant halfWAD = WAD / 2; uint256 internal constant RAY = 1e27; uint256 internal constant halfRAY = RAY / 2; uint256 internal constant WAD_RAY_RATIO = 1e9; /** * @return One ray, 1e27 **/ function ray() internal pure returns (uint256) { return RAY; } /** * @return One wad, 1e18 **/ function wad() internal pure returns (uint256) { return WAD; } /** * @return Half ray, 1e27/2 **/ function halfRay() internal pure returns (uint256) { return halfRAY; } /** * @return Half ray, 1e18/2 **/ function halfWad() internal pure returns (uint256) { return halfWAD; } /** * @dev Multiplies two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a*b, in wad **/ function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfWAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfWAD) / WAD; } /** * @dev Divides two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a/b, in wad **/ function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / WAD, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * WAD + halfB) / b; } /** * @dev Multiplies two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a*b, in ray **/ function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - halfRAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + halfRAY) / RAY; } /** * @dev Divides two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a/b, in ray **/ function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / RAY, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * RAY + halfB) / b; } /** * @dev Casts ray down to wad * @param a Ray * @return a casted to wad, rounded half up to the nearest wad **/ function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = WAD_RAY_RATIO / 2; uint256 result = halfRatio + a; require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW); return result / WAD_RAY_RATIO; } /** * @dev Converts wad up to ray * @param a Wad * @return a converted in ray **/ function wadToRay(uint256 a) internal pure returns (uint256) { uint256 result = a * WAD_RAY_RATIO; require(result / WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW); return result; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title Errors library * @author Aave * @notice Defines the error messages emitted by the different contracts of the Aave protocol * @dev Error messages prefix glossary: * - VL = ValidationLogic * - MATH = Math libraries * - CT = Common errors between tokens (AToken, VariableDebtToken and StableDebtToken) * - AT = AToken * - SDT = StableDebtToken * - VDT = VariableDebtToken * - LP = LendingPool * - LPAPR = LendingPoolAddressesProviderRegistry * - LPC = LendingPoolConfiguration * - RL = ReserveLogic * - LPCM = LendingPoolCollateralManager * - P = Pausable */ library Errors { //common errors string public constant CALLER_NOT_POOL_ADMIN = '33'; // 'The caller must be the pool admin' string public constant BORROW_ALLOWANCE_NOT_ENOUGH = '59'; // User borrows on behalf, but allowance are too small //contract specific errors string public constant VL_INVALID_AMOUNT = '1'; // 'Amount must be greater than 0' string public constant VL_NO_ACTIVE_RESERVE = '2'; // 'Action requires an active reserve' string public constant VL_RESERVE_FROZEN = '3'; // 'Action cannot be performed because the reserve is frozen' string public constant VL_CURRENT_AVAILABLE_LIQUIDITY_NOT_ENOUGH = '4'; // 'The current liquidity is not enough' string public constant VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE = '5'; // 'User cannot withdraw more than the available balance' string public constant VL_TRANSFER_NOT_ALLOWED = '6'; // 'Transfer cannot be allowed.' string public constant VL_BORROWING_NOT_ENABLED = '7'; // 'Borrowing is not enabled' string public constant VL_INVALID_INTEREST_RATE_MODE_SELECTED = '8'; // 'Invalid interest rate mode selected' string public constant VL_COLLATERAL_BALANCE_IS_0 = '9'; // 'The collateral balance is 0' string public constant VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD = '10'; // 'Health factor is lesser than the liquidation threshold' string public constant VL_COLLATERAL_CANNOT_COVER_NEW_BORROW = '11'; // 'There is not enough collateral to cover a new borrow' string public constant VL_STABLE_BORROWING_NOT_ENABLED = '12'; // stable borrowing not enabled string public constant VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY = '13'; // collateral is (mostly) the same currency that is being borrowed string public constant VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE = '14'; // 'The requested amount is greater than the max loan size in stable rate mode string public constant VL_NO_DEBT_OF_SELECTED_TYPE = '15'; // 'for repayment of stable debt, the user needs to have stable debt, otherwise, he needs to have variable debt' string public constant VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF = '16'; // 'To repay on behalf of an user an explicit amount to repay is needed' string public constant VL_NO_STABLE_RATE_LOAN_IN_RESERVE = '17'; // 'User does not have a stable rate loan in progress on this reserve' string public constant VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE = '18'; // 'User does not have a variable rate loan in progress on this reserve' string public constant VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0 = '19'; // 'The underlying balance needs to be greater than 0' string public constant VL_DEPOSIT_ALREADY_IN_USE = '20'; // 'User deposit is already being used as collateral' string public constant LP_NOT_ENOUGH_STABLE_BORROW_BALANCE = '21'; // 'User does not have any stable rate loan for this reserve' string public constant LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET = '22'; // 'Interest rate rebalance conditions were not met' string public constant LP_LIQUIDATION_CALL_FAILED = '23'; // 'Liquidation call failed' string public constant LP_NOT_ENOUGH_LIQUIDITY_TO_BORROW = '24'; // 'There is not enough liquidity available to borrow' string public constant LP_REQUESTED_AMOUNT_TOO_SMALL = '25'; // 'The requested amount is too small for a FlashLoan.' string public constant LP_INCONSISTENT_PROTOCOL_ACTUAL_BALANCE = '26'; // 'The actual balance of the protocol is inconsistent' string public constant LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR = '27'; // 'The caller of the function is not the lending pool configurator' string public constant LP_INCONSISTENT_FLASHLOAN_PARAMS = '28'; string public constant CT_CALLER_MUST_BE_LENDING_POOL = '29'; // 'The caller of this function must be a lending pool' string public constant CT_CANNOT_GIVE_ALLOWANCE_TO_HIMSELF = '30'; // 'User cannot give allowance to himself' string public constant CT_TRANSFER_AMOUNT_NOT_GT_0 = '31'; // 'Transferred amount needs to be greater than zero' string public constant RL_RESERVE_ALREADY_INITIALIZED = '32'; // 'Reserve has already been initialized' string public constant LPC_RESERVE_LIQUIDITY_NOT_0 = '34'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_ATOKEN_POOL_ADDRESS = '35'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_STABLE_DEBT_TOKEN_POOL_ADDRESS = '36'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_POOL_ADDRESS = '37'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_STABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '38'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_VARIABLE_DEBT_TOKEN_UNDERLYING_ADDRESS = '39'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_ADDRESSES_PROVIDER_ID = '40'; // 'The liquidity of the reserve needs to be 0' string public constant LPC_INVALID_CONFIGURATION = '75'; // 'Invalid risk parameters for the reserve' string public constant LPC_CALLER_NOT_EMERGENCY_ADMIN = '76'; // 'The caller must be the emergency admin' string public constant LPAPR_PROVIDER_NOT_REGISTERED = '41'; // 'Provider is not registered' string public constant LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD = '42'; // 'Health factor is not below the threshold' string public constant LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED = '43'; // 'The collateral chosen cannot be liquidated' string public constant LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER = '44'; // 'User did not borrow the specified currency' string public constant LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE = '45'; // "There isn't enough liquidity available to liquidate" string public constant LPCM_NO_ERRORS = '46'; // 'No errors' string public constant LP_INVALID_FLASHLOAN_MODE = '47'; //Invalid flashloan mode selected string public constant MATH_MULTIPLICATION_OVERFLOW = '48'; string public constant MATH_ADDITION_OVERFLOW = '49'; string public constant MATH_DIVISION_BY_ZERO = '50'; string public constant RL_LIQUIDITY_INDEX_OVERFLOW = '51'; // Liquidity index overflows uint128 string public constant RL_VARIABLE_BORROW_INDEX_OVERFLOW = '52'; // Variable borrow index overflows uint128 string public constant RL_LIQUIDITY_RATE_OVERFLOW = '53'; // Liquidity rate overflows uint128 string public constant RL_VARIABLE_BORROW_RATE_OVERFLOW = '54'; // Variable borrow rate overflows uint128 string public constant RL_STABLE_BORROW_RATE_OVERFLOW = '55'; // Stable borrow rate overflows uint128 string public constant CT_INVALID_MINT_AMOUNT = '56'; //invalid amount to mint string public constant LP_FAILED_REPAY_WITH_COLLATERAL = '57'; string public constant CT_INVALID_BURN_AMOUNT = '58'; //invalid amount to burn string public constant LP_FAILED_COLLATERAL_SWAP = '60'; string public constant LP_INVALID_EQUAL_ASSETS_TO_SWAP = '61'; string public constant LP_REENTRANCY_NOT_ALLOWED = '62'; string public constant LP_CALLER_MUST_BE_AN_ATOKEN = '63'; string public constant LP_IS_PAUSED = '64'; // 'Pool is paused' string public constant LP_NO_MORE_RESERVES_ALLOWED = '65'; string public constant LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN = '66'; string public constant RC_INVALID_LTV = '67'; string public constant RC_INVALID_LIQ_THRESHOLD = '68'; string public constant RC_INVALID_LIQ_BONUS = '69'; string public constant RC_INVALID_DECIMALS = '70'; string public constant RC_INVALID_RESERVE_FACTOR = '71'; string public constant LPAPR_INVALID_ADDRESSES_PROVIDER_ID = '72'; string public constant VL_INCONSISTENT_FLASHLOAN_PARAMS = '73'; string public constant LP_INCONSISTENT_PARAMS_LENGTH = '74'; string public constant UL_INVALID_INDEX = '77'; string public constant LP_NOT_CONTRACT = '78'; string public constant SDT_STABLE_DEBT_OVERFLOW = '79'; string public constant SDT_BURN_EXCEEDS_BALANCE = '80'; enum CollateralManagerErrors { NO_ERROR, NO_COLLATERAL_AVAILABLE, COLLATERAL_CANNOT_BE_LIQUIDATED, CURRRENCY_NOT_BORROWED, HEALTH_FACTOR_ABOVE_THRESHOLD, NOT_ENOUGH_LIQUIDITY, NO_ACTIVE_RESERVE, HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD, INVALID_EQUAL_ASSETS_TO_SWAP, FROZEN_RESERVE } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import {Errors} from '../helpers/Errors.sol'; /** * @title PercentageMath library * @author Aave * @notice Provides functions to perform percentage calculations * @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR * @dev Operations are rounded half up **/ library PercentageMath { uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2; /** * @dev Executes a percentage multiplication * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The percentage of value **/ function percentMul(uint256 value, uint256 percentage) internal pure returns (uint256) { if (value == 0 || percentage == 0) { return 0; } require( value <= (type(uint256).max - HALF_PERCENT) / percentage, Errors.MATH_MULTIPLICATION_OVERFLOW ); return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR; } /** * @dev Executes a percentage division * @param value The value of which the percentage needs to be calculated * @param percentage The percentage of the value to be calculated * @return The value divided the percentage **/ function percentDiv(uint256 value, uint256 percentage) internal pure returns (uint256) { require(percentage != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfPercentage = percentage / 2; require( value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR, Errors.MATH_MULTIPLICATION_OVERFLOW ); return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProvider { event MarketIdSet(string newMarketId); event LendingPoolUpdated(address indexed newAddress); event ConfigurationAdminUpdated(address indexed newAddress); event EmergencyAdminUpdated(address indexed newAddress); event LendingPoolConfiguratorUpdated(address indexed newAddress); event LendingPoolCollateralManagerUpdated(address indexed newAddress); event PriceOracleUpdated(address indexed newAddress); event LendingRateOracleUpdated(address indexed newAddress); event ProxyCreated(bytes32 id, address indexed newAddress); event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy); function getMarketId() external view returns (string memory); function setMarketId(string calldata marketId) external; function setAddress(bytes32 id, address newAddress) external; function setAddressAsProxy(bytes32 id, address impl) external; function getAddress(bytes32 id) external view returns (address); function getLendingPool() external view returns (address); function setLendingPoolImpl(address pool) external; function getLendingPoolConfigurator() external view returns (address); function setLendingPoolConfiguratorImpl(address configurator) external; function getLendingPoolCollateralManager() external view returns (address); function setLendingPoolCollateralManager(address manager) external; function getPoolAdmin() external view returns (address); function setPoolAdmin(address admin) external; function getEmergencyAdmin() external view returns (address); function setEmergencyAdmin(address admin) external; function getPriceOracle() external view returns (address); function setPriceOracle(address priceOracle) external; function getLendingRateOracle() external view returns (address); function setLendingRateOracle(address lendingRateOracle) external; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; /** * @title ILendingRateOracle interface * @notice Interface for the Aave borrow rate oracle. Provides the average market borrow rate to be used as a base for the stable borrow rate calculations **/ interface ILendingRateOracle { /** @dev returns the market borrow rate in ray **/ function getMarketBorrowRate(address asset) external view returns (uint256); /** @dev sets the market borrow rate. Rate value must be in ray **/ function setMarketBorrowRate(address asset, uint256 rate) external; }
* @dev Calculates the overall borrow rate as the weighted average between the total variable debt and total stable debt @param totalStableDebt The total borrowed from the reserve a stable rate @param totalVariableDebt The total borrowed from the reserve at a variable rate @param currentVariableBorrowRate The current variable borrow rate of the reserve @param currentAverageStableBorrowRate The current weighted average of all the stable rate loans @return The weighted averaged borrow rate/
function _getOverallBorrowRate( uint256 totalStableDebt, uint256 totalVariableDebt, uint256 currentVariableBorrowRate, uint256 currentAverageStableBorrowRate ) internal pure returns (uint256) { uint256 totalDebt = totalStableDebt.add(totalVariableDebt); if (totalDebt == 0) return 0; uint256 weightedVariableRate = totalVariableDebt.wadToRay().rayMul(currentVariableBorrowRate); uint256 weightedStableRate = totalStableDebt.wadToRay().rayMul(currentAverageStableBorrowRate); uint256 overallBorrowRate = weightedVariableRate.add(weightedStableRate).rayDiv(totalDebt.wadToRay()); return overallBorrowRate; }
65,669
[ 1, 10587, 326, 13914, 29759, 4993, 487, 326, 13747, 8164, 3086, 326, 2078, 2190, 18202, 88, 471, 2078, 14114, 18202, 88, 225, 2078, 30915, 758, 23602, 1021, 2078, 29759, 329, 628, 326, 20501, 279, 14114, 4993, 225, 2078, 3092, 758, 23602, 1021, 2078, 29759, 329, 628, 326, 20501, 622, 279, 2190, 4993, 225, 783, 3092, 38, 15318, 4727, 1021, 783, 2190, 29759, 4993, 434, 326, 20501, 225, 783, 17115, 30915, 38, 15318, 4727, 1021, 783, 13747, 8164, 434, 777, 326, 14114, 4993, 437, 634, 327, 1021, 13747, 23713, 11349, 29759, 4993, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 389, 588, 4851, 454, 38, 15318, 4727, 12, 203, 565, 2254, 5034, 2078, 30915, 758, 23602, 16, 203, 565, 2254, 5034, 2078, 3092, 758, 23602, 16, 203, 565, 2254, 5034, 783, 3092, 38, 15318, 4727, 16, 203, 565, 2254, 5034, 783, 17115, 30915, 38, 15318, 4727, 203, 225, 262, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 565, 2254, 5034, 2078, 758, 23602, 273, 2078, 30915, 758, 23602, 18, 1289, 12, 4963, 3092, 758, 23602, 1769, 203, 203, 565, 309, 261, 4963, 758, 23602, 422, 374, 13, 327, 374, 31, 203, 203, 565, 2254, 5034, 13747, 3092, 4727, 273, 2078, 3092, 758, 23602, 18, 91, 361, 774, 54, 528, 7675, 435, 27860, 12, 2972, 3092, 38, 15318, 4727, 1769, 203, 203, 565, 2254, 5034, 13747, 30915, 4727, 273, 2078, 30915, 758, 23602, 18, 91, 361, 774, 54, 528, 7675, 435, 27860, 12, 2972, 17115, 30915, 38, 15318, 4727, 1769, 203, 203, 565, 2254, 5034, 13914, 38, 15318, 4727, 273, 203, 1377, 13747, 3092, 4727, 18, 1289, 12, 30890, 30915, 4727, 2934, 435, 7244, 12, 4963, 758, 23602, 18, 91, 361, 774, 54, 528, 10663, 203, 203, 565, 327, 13914, 38, 15318, 4727, 31, 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 ]
pragma solidity 0.5.0; //////////////////////////////////////////////////////////////////////////////// // XXX: Do not use in production until this code has been audited. //////////////////////////////////////////////////////////////////////////////// /** **************************************************************************** @notice on-chain verification of verifiable-random-function (VRF) proofs as described in https://eprint.iacr.org/2017/099.pdf (security proofs) and https://tools.ietf.org/html/draft-goldbe-vrf-01#section-5 (spec) **************************************************************************** @dev PURPOSE @dev Reggie the Random Oracle (not his real job) wants to provide randomness to Vera the verifier in such a way that Vera can be sure he's not making his output up to suit himself. Reggie provides Vera a public key to which he knows the secret key. Each time Vera provides a seed to Reggie, he gives back a value which is computed completely deterministically from the seed and the secret key, but which is indistinguishable from randomness to Vera. Nonetheless, Vera is able to verify that Reggie's output came from her seed and his secret key. @dev The purpose of this contract is to perform that verification. **************************************************************************** @dev USAGE @dev The main entry point is isValidVRFOutput. See its docstring. Design notes ------------ An elliptic curve point is generally represented in the solidity code as a uint256[2], corresponding to its affine coordinates in GF(fieldSize). For the sake of efficiency, this implementation deviates from the spec in some minor ways: - Keccak hash rather than SHA256. This is because it's provided natively by the EVM, and therefore costs much less gas. The impact on security should be minor. - Secp256k1 curve instead of P-256. It abuses ECRECOVER for the most expensive ECC arithmetic. - scalarFromCurve recursively hashes and takes the relevant hash bits until it finds a point less than the group order. This results in uniform sampling over the the possible values scalarFromCurve could take. The spec recommends just uing the first hash output as a uint256, which is a slightly biased sample. See the zqHash function. - hashToCurve recursively hashes until it finds a curve x-ordinate. The spec recommends that the initial input should be concatenated with a nonce and then hashed, and this input should be rehashed with the nonce updated until an x-ordinate is found. Recursive hashing is slightly more efficient. The spec also recommends (https://tools.ietf.org/html/rfc8032#section-5.1.3 , by the specification of RS2ECP) that the x-ordinate should be rejected if it is greater than the modulus. - In the calculation of the challenge value "c", the "u" value (or "k*g", if you know the secret nonce) The spec also requires the y ordinate of the hashToCurve to be negated if y is odd. See http://www.secg.org/sec1-v2.pdf#page=17 . This sacrifices one bit of entropy in the random output. Instead, here y is chosen based on whether an extra hash of the inputs is even or odd. */ contract VRF { // See https://en.bitcoin.it/wiki/Secp256k1 for these constants. uint256 constant public GROUP_ORDER = // Number of points in Secp256k1 // solium-disable-next-line indentation 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141; // Prime characteristic of the galois field over which Secp256k1 is defined // solium-disable-next-line zeppelin/no-arithmetic-operations uint256 constant public FIELD_SIZE = // solium-disable-next-line indentation 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; // solium-disable zeppelin/no-arithmetic-operations uint256 constant public MINUS_ONE = FIELD_SIZE - 1; uint256 constant public MULTIPLICATIVE_GROUP_ORDER = FIELD_SIZE - 1; // pow(x, SQRT_POWER, FIELD_SIZE) == √x, since FIELD_SIZE % 4 = 3 // https://en.wikipedia.org/wiki/Modular_square_root#Prime_or_prime_power_modulus uint256 constant public SQRT_POWER = (FIELD_SIZE + 1) >> 2; uint256 constant public WORD_LENGTH_BYTES = 0x20; // (base**exponent) % modulus // Cribbed from https://medium.com/@rbkhmrcr/precompiles-solidity-e5d29bd428c4 function bigModExp(uint256 base, uint256 exponent, uint256 modulus) public view returns (uint256 exponentiation) { uint256 callResult; uint256[6] memory bigModExpContractInputs; bigModExpContractInputs[0] = WORD_LENGTH_BYTES; // Length of base bigModExpContractInputs[1] = WORD_LENGTH_BYTES; // Length of exponent bigModExpContractInputs[2] = WORD_LENGTH_BYTES; // Length of modulus bigModExpContractInputs[3] = base; bigModExpContractInputs[4] = exponent; bigModExpContractInputs[5] = modulus; uint256[1] memory output; assembly { // solhint-disable-line no-inline-assembly callResult := staticcall(13056, // Gas cost. See EIP-198's 1st e.g. 0x05, // Bigmodexp contract address bigModExpContractInputs, 0xc0, // Length of input segment output, 0x20) // Length of output segment } if (callResult == 0) {revert("bigModExp failure!");} return output[0]; } // Computes a s.t. a^2 = x in the field. Assumes x is a square. function squareRoot(uint256 x) public view returns (uint256) { return bigModExp(x, SQRT_POWER, FIELD_SIZE); } function ySquared(uint256 x) public view returns (uint256) { // Curve equation is y^2=x^3+7. See return (bigModExp(x, 3, FIELD_SIZE) + 7) % FIELD_SIZE; } // Hash x uniformly into {0, ..., q-1}. Expects x to ALREADY have the // necessary entropy... If x < q, returns x! function zqHash(uint256 q, uint256 x) public pure returns (uint256 x_) { x_ = x; while (x_ >= q) { x_ = uint256(keccak256(abi.encodePacked(x_))); } } // One-way hash function onto the curve. function hashToCurve(uint256[2] memory k, uint256 input) public view returns (uint256[2] memory rv) { bytes32 hash = keccak256(abi.encodePacked(k, input)); rv[0] = zqHash(FIELD_SIZE, uint256(hash)); while (true) { rv[0] = zqHash(FIELD_SIZE, uint256(keccak256(abi.encodePacked(rv[0])))); rv[1] = squareRoot(ySquared(rv[0])); if (mulmod(rv[1], rv[1], FIELD_SIZE) == ySquared(rv[0])) { break; } } // Two possible y ordinates for x ordinate rv[0]; pick one "randomly" if (uint256(keccak256(abi.encodePacked(rv[0], input))) % 2 == 0) { rv[1] = -rv[1]; } } // Bits used in Ethereum address uint256 constant public BOTTOM_160_BITS = 2**161 - 1; // Returns the ethereum address associated with point. function pointAddress(uint256[2] calldata point) external pure returns(address) { bytes memory packedPoint = abi.encodePacked(point); // Lower 160 bits of the keccak hash of (x,y) as 64 bytes return address(uint256(keccak256(packedPoint)) & BOTTOM_160_BITS); } // Returns true iff q==scalar*x, with cryptographically high probability. // Based on Vitalik Buterin's idea in above ethresear.ch post. function ecmulVerify(uint256[2] memory x, uint256 scalar, uint256[2] memory q) public pure returns(bool) { // This ecrecover returns the address associated with c*R. See // https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9 // The point corresponding to the address returned by ecrecover(0,v,r,s=c*r) // is (r⁻¹ mod Q) * (c*r * R - 0 * g) = c * R, where R is the point // specified by (v, r). See https://crypto.stackexchange.com/a/18106 bytes32 cTimesX0 = bytes32(mulmod(scalar, x[0], GROUP_ORDER)); uint8 parity = x[1] % 2 != 0 ? 28 : 27; return ecrecover(bytes32(0), parity, bytes32(x[0]), cTimesX0) == address(uint256(keccak256(abi.encodePacked(q))) & BOTTOM_160_BITS); } // Returns x1/z1+x2/z2=(x1z2+x2z1)/(z1z2) in projective coordinates on P¹(𝔽ₙ) function projectiveAdd(uint256 x1, uint256 z1, uint256 x2, uint256 z2) external pure returns(uint256 x3, uint256 z3) { uint256 crossMultNumerator1 = mulmod(z2, x1, FIELD_SIZE); uint256 crossMultNumerator2 = mulmod(z1, x2, FIELD_SIZE); uint256 denom = mulmod(z1, z2, FIELD_SIZE); uint256 numerator = addmod(crossMultNumerator1, crossMultNumerator2, FIELD_SIZE); return (numerator, denom); } // Returns x1/z1-x2/z2=(x1z2+x2z1)/(z1z2) in projective coordinates on P¹(𝔽ₙ) function projectiveSub(uint256 x1, uint256 z1, uint256 x2, uint256 z2) public pure returns(uint256 x3, uint256 z3) { uint256 num1 = mulmod(z2, x1, FIELD_SIZE); uint256 num2 = mulmod(FIELD_SIZE - x2, z1, FIELD_SIZE); (x3, z3) = (addmod(num1, num2, FIELD_SIZE), mulmod(z1, z2, FIELD_SIZE)); } // Returns x1/z1*x2/z2=(x1x2)/(z1z2), in projective coordinates on P¹(𝔽ₙ) function projectiveMul(uint256 x1, uint256 z1, uint256 x2, uint256 z2) public pure returns(uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, x2, FIELD_SIZE), mulmod(z1, z2, FIELD_SIZE)); } // Returns x1/z1/(x2/z2)=(x1z2)/(x2z1), in projective coordinates on P¹(𝔽ₙ) function projectiveDiv(uint256 x1, uint256 z1, uint256 x2, uint256 z2) external pure returns(uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, z2, FIELD_SIZE), mulmod(z1, x2, FIELD_SIZE)); } /** ************************************************************************** @notice Computes elliptic-curve sum, in projective co-ordinates @dev Using projective coordinates avoids costly divisions @dev To use this with x and y in affine coordinates, compute projectiveECAdd(x[0], x[1], 1, y[0], y[1], 1) @dev This can be used to calculate the z which is the inverse to zInv in isValidVRFOutput. But consider using a faster re-implementation. @dev This function assumes [x1,y1,z1],[x2,y2,z2] are valid projective coordinates of secp256k1 points. That is safe in this contract, because this method is only used by linearCombination, which checks points are on the curve via ecrecover, and ensures valid projective coordinates by passing z1=z2=1. ************************************************************************** @param x1 The first affine coordinate of the first summand @param y1 The second affine coordinate of the first summand @param x2 The first affine coordinate of the second summand @param y2 The second affine coordinate of the second summand ************************************************************************** @return [x1,y1,z1]+[x2,y2,z2] as points on secp256k1, in P²(𝔽ₙ) */ function projectiveECAdd(uint256 x1, uint256 y1, uint256 x2, uint256 y2) public pure returns(uint256 x3, uint256 y3, uint256 z3) { // See "Group law for E/K : y^2 = x^3 + ax + b", in section 3.1.2, p. 80, // "Guide to Elliptic Curve Cryptography" by Hankerson, Menezes and Vanstone // We take the equations there for (x3,y3), and homogenize them to // projective coordinates. That way, no inverses are required, here, and we // only need the one inverse in affineECAdd. // We only need the "point addition" equations from Hankerson et al. Can // skip the "point doubling" equations because p1 == p2 is cryptographically // impossible, and require'd not to be the case in linearCombination. // Add extra "projective coordinate" to the two points (uint256 z1, uint256 z2) = (1, 1); // (lx, lz) = (y2-y1)/(x2-x1), i.e., gradient of secant line. uint256 lx = addmod(y2, FIELD_SIZE - y1, FIELD_SIZE); uint256 lz = addmod(x2, FIELD_SIZE - x1, FIELD_SIZE); uint256 dx; // Accumulates denominator from x3 calculation // x3=((y2-y1)/(x2-x1))^2-x1-x2 (x3, dx) = projectiveMul(lx, lz, lx, lz); // ((y2-y1)/(x2-x1))^2 (x3, dx) = projectiveSub(x3, dx, x1, z1); // ((y2-y1)/(x2-x1))^2-x1 (x3, dx) = projectiveSub(x3, dx, x2, z2); // ((y2-y1)/(x2-x1))^2-x1-x2 uint256 dy; // Accumulates denominator from y3 calculation // y3=((y2-y1)/(x2-x1))(x1-x3)-y1 (y3, dy) = projectiveSub(x1, z1, x3, dx); // x1-x3 (y3, dy) = projectiveMul(y3, dy, lx, lz); // ((y2-y1)/(x2-x1))(x1-x3) (y3, dy) = projectiveSub(y3, dy, y1, z1); // ((y2-y1)/(x2-x1))(x1-x3)-y1 if (dx != dy) { // Cross-multiply to put everything over a common denominator x3 = mulmod(x3, dy, FIELD_SIZE); y3 = mulmod(y3, dx, FIELD_SIZE); z3 = mulmod(dx, dy, FIELD_SIZE); } else { z3 = dx; } } // Returns p1+p2, as affine points on secp256k1. invZ must be the inverse of // the z returned by projectiveECAdd(p1, p2). It is computed off-chain to // save gas. function affineECAdd( uint256[2] memory p1, uint256[2] memory p2, uint256 invZ) public pure returns (uint256[2] memory) { uint256 x; uint256 y; uint256 z; (x, y, z) = projectiveECAdd(p1[0], p1[1], p2[0], p2[1]); require(mulmod(z, invZ, FIELD_SIZE) == 1, "_invZ must be inverse of z"); // Clear the z ordinate of the projective representation by dividing through // by it, to obtain the affine representation return [mulmod(x, invZ, FIELD_SIZE), mulmod(y, invZ, FIELD_SIZE)]; } // Returns true iff address(c*p+s*g) == lcWitness, where g is generator. function verifyLinearCombinationWithGenerator( uint256 c, uint256[2] memory p, uint256 s, address lcWitness) public pure returns (bool) { // ecrecover returns 0x0 in certain failure modes. Ensure witness differs. require(lcWitness != address(0), "bad witness"); // https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9 // The point corresponding to the address returned by // ecrecover(-s*p[0],v,_p[0],_c*p[0]) is // (p[0]⁻¹ mod GROUP_ORDER)*(c*p[0]-(-s)*p[0]*g)=_c*p+s*g, where v // is the parity of p[1]. See https://crypto.stackexchange.com/a/18106 bytes32 pseudoHash = bytes32(GROUP_ORDER - mulmod(p[0], s, GROUP_ORDER)); // https://bitcoin.stackexchange.com/questions/38351/ecdsa-v-r-s-what-is-v uint8 v = (p[1] % 2 == 0) ? 27 : 28; bytes32 pseudoSignature = bytes32(mulmod(c, p[0], GROUP_ORDER)); address computed = ecrecover(pseudoHash, v, bytes32(p[0]), pseudoSignature); return computed == lcWitness; } // c*p1 + s*p2 function linearCombination( uint256 c, uint256[2] memory p1, uint256[2] memory cp1Witness, uint256 s, uint256[2] memory p2, uint256[2] memory sp2Witness, uint256 zInv) public pure returns (uint256[2] memory) { require(cp1Witness[0] != sp2Witness[0], "points must differ in sum"); require(ecmulVerify(p1, c, cp1Witness), "First multiplication check failed"); require(ecmulVerify(p2, s, sp2Witness), "Second multiplication check failed"); return affineECAdd(cp1Witness, sp2Witness, zInv); } // Pseudo-random number from inputs. Corresponds to vrf.go/scalarFromCurve. function scalarFromCurve( uint256[2] memory hash, uint256[2] memory pk, uint256[2] memory gamma, address uWitness, uint256[2] memory v) public pure returns (uint256 s) { bytes32 iHash = keccak256(abi.encodePacked(hash, pk, gamma, v, uWitness)); return zqHash(GROUP_ORDER, uint256(iHash)); } // True if (gamma, c, s) is a correctly constructed randomness proof from pk // and seed. zInv must be the inverse of the third ordinate from // projectiveECAdd applied to cGammaWitness and sHashWitness function verifyVRFProof( uint256[2] memory pk, uint256[2] memory gamma, uint256 c, uint256 s, uint256 seed, address uWitness, uint256[2] memory cGammaWitness, uint256[2] memory sHashWitness, uint256 zInv) public view returns (bool) { // NB: Curve operations already check that (pkX, pkY), (gammaX, gammaY) // are valid curve points. No need to do that explicitly. require( verifyLinearCombinationWithGenerator(c, pk, s, uWitness), "Could not verify that address(c*pk+s*generator)=_uWitness"); uint256[2] memory hash = hashToCurve(pk, seed); uint256[2] memory v = linearCombination( c, gamma, cGammaWitness, s, hash, sHashWitness, zInv); return (c == scalarFromCurve(hash, pk, gamma, uWitness, v)); } /** ************************************************************************** @notice isValidVRFOutput returns true iff the proof can be verified as showing that output was generated as mandated. @dev See the invocation of verifyVRFProof in VRF.js, for an example. ************************************************************************** @dev Let x be the secret key associated with the public key pk @param pk Affine coordinates of the secp256k1 public key for this VRF @param gamma Intermediate output of the VRF as an affine secp256k1 point @param c The challenge value for proof that gamma = x*hashToCurve(seed) See the variable c on p. 28 of https://www.cs.bu.edu/~goldbe/papers/VRF_ietf99_print.pdf @param s The response value for the proof. See s on p. 28 @param seed The input seed from which the VRF output is computed @param uWitness The ethereum address of c*pk + s*<generator>, in elliptic-curve arithmetic @param cGammaWitness c*gamma on the elliptic-curve @param sHashWitness s*hashToCurve(seed) on the elliptic-curve @param zInv Inverse of the third ordinate of the return value from projectiveECAdd(c*gamma, s*hashToCurve(seed)). Passed in here to save gas, because computing modular inverses is expensive in the EVM. @param output The actual output of the VRF. ************************************************************************** @return True iff all the above parameters are correct */ function isValidVRFOutput( uint256[2] calldata pk, uint256[2] calldata gamma, uint256 c, uint256 s, uint256 seed, address uWitness, uint256[2] calldata cGammaWitness, uint256[2] calldata sHashWitness, uint256 zInv, uint256 output) external view returns (bool) { return verifyVRFProof( pk, gamma, c, s, seed, uWitness, cGammaWitness, sHashWitness, zInv) && (uint256(keccak256(abi.encodePacked(gamma))) == output); } }
Curve equation is y^2=x^3+7. See
function ySquared(uint256 x) public view returns (uint256) { return (bigModExp(x, 3, FIELD_SIZE) + 7) % FIELD_SIZE; }
12,662,679
[ 1, 9423, 15778, 353, 677, 66, 22, 33, 92, 66, 23, 15, 27, 18, 2164, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 677, 20888, 12, 11890, 5034, 619, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 261, 14002, 1739, 2966, 12, 92, 16, 890, 16, 9921, 67, 4574, 13, 397, 2371, 13, 738, 9921, 67, 4574, 31, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.6.0; pragma AbiHeader expire; // Import the interface file import "5_BankClientInterfaces.sol"; // This contract implements 'IBankClient' interface. contract BankClient is IBankClient { uint public creditLimit = 0; // allowed credit limit; uint public totalDebt = 0; // contract total debt; uint public balance = 0; // contract balance; uint public value = 0; // inbound message value. constructor() public { // check that contract's public key is set require(tvm.pubkey() != 0, 101); // Check that message has signature (msg.pubkey() is not zero) and message is signed with the owner's private key require(msg.pubkey() == tvm.pubkey(), 102); tvm.accept(); } modifier checkOwnerAndAccept { // Check that message was signed with contracts key. require(msg.pubkey() == tvm.pubkey(), 102); tvm.accept(); _; } // This function calls a remote IBank contract to get the credit limit. function getMyCreditLimit(IBank bank) public view checkOwnerAndAccept { // Call remote contract function. bank.getCreditLimit(); } // A callback function to set the credit limit. function setCreditLimit(uint limit) public override { // Save the credit limit (received from another contract) in the state variable. creditLimit = limit; } //This function calls bank contract to ask for a loan. function askForALoan(IBank bank, uint amount) public checkOwnerAndAccept { balance = address(this).balance; bank.loan(amount); } // A callback function to receive requested loan. Function receives the total debt as an argument. function receiveLoan(uint n_totalDebt) public override { value = msg.value; uint n_balance = address(this).balance; require(n_balance > balance); balance = n_balance; totalDebt = n_totalDebt; } // A callback function to indicate refuse of the loan request. Function receives available limit as an argument. function refusalCallback(uint availableLimit) public override { creditLimit = availableLimit; } }
This function calls a remote IBank contract to get the credit limit. Call remote contract function.
function getMyCreditLimit(IBank bank) public view checkOwnerAndAccept { bank.getCreditLimit(); }
6,371,166
[ 1, 2503, 445, 4097, 279, 2632, 467, 16040, 6835, 358, 336, 326, 12896, 1800, 18, 3049, 2632, 6835, 445, 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 ]
[ 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, 202, 915, 2108, 93, 16520, 3039, 12, 13450, 2304, 11218, 13, 1071, 1476, 866, 5541, 1876, 5933, 288, 203, 202, 202, 10546, 18, 588, 16520, 3039, 5621, 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 ]
./full_match/5/0x9ccDD0Bb22aA073Be7f4021D9bfa89fdD7BfAbdF/sources/project_/_pancakeswap/v3-core/contracts/interfaces/pool/IPancakeV3PoolDerivedState.sol
@title Pool state that is not stored @notice Contains view functions to provide information about the pool that is computed rather than stored on the blockchain. The functions here may have variable gas costs.
interface IPancakeV3PoolDerivedState { function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); pragma solidity >=0.5.0; }
1,959,160
[ 1, 2864, 919, 716, 353, 486, 4041, 225, 8398, 1476, 4186, 358, 5615, 1779, 2973, 326, 2845, 716, 353, 8470, 9178, 2353, 4041, 603, 326, 16766, 18, 1021, 4186, 2674, 2026, 1240, 2190, 16189, 22793, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 2971, 19292, 911, 58, 23, 2864, 21007, 1119, 288, 203, 565, 445, 19389, 12, 11890, 1578, 8526, 745, 892, 3974, 2577, 538, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 474, 4313, 8526, 3778, 4024, 39, 5283, 8785, 16, 2254, 16874, 8526, 3778, 3974, 2173, 48, 18988, 24237, 39, 11276, 60, 10392, 87, 1769, 203, 203, 565, 445, 4439, 39, 5283, 8785, 18619, 12, 474, 3247, 4024, 4070, 16, 509, 3247, 4024, 5988, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 203, 5411, 509, 4313, 4024, 39, 11276, 18619, 16, 203, 5411, 2254, 16874, 3974, 2173, 48, 18988, 24237, 18619, 60, 10392, 16, 203, 5411, 2254, 1578, 3974, 18619, 203, 3639, 11272, 203, 683, 9454, 18035, 560, 1545, 20, 18, 25, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 Glofile * @author Jonathan Brown <[email protected]> */ contract Glofile { enum GlofileType { Anon, Person, Project, Organization, Proxy, Parody, Bot } enum SafetyLevel { Safe, NSFW, NSFL } struct Glofile { bool dontIndex; GlofileType glofileType; SafetyLevel safetyLevel; string fullName; string location; bytes3[] foregroundColors; bytes3[] backgroundColors; bytes3[] languages; bytes3[] bioLanguages; bytes[] avatars; bytes[] coverImages; bytes[] backgroundImages; string[] topics; string[] parents; string[] children; string[] uris; mapping (bytes3 => bytes) bioTranslations; } mapping (address => Glofile) glofiles; event Update(address indexed account); event Delete(address indexed account); /** * @notice Set your Glofile don't index flag to `dontIndex` * @dev Sets the "don't index" flag. Glofiles with this flag set should only be accessible directly and not be discoverable via search. * @param dontIndex flag to indicate that this Glofile should not be indexed */ function setDontIndex(bool dontIndex) { glofiles[msg.sender].dontIndex = dontIndex; Update(msg.sender); } /** * @notice Set your Glofile type to `glofileType` * @dev Sets the Glofile type. * @param glofileType Glofile type */ function setGlofileType(GlofileType glofileType) { glofiles[msg.sender].glofileType = glofileType; Update(msg.sender); } /** * @notice Set your Glofile safety level to `safetyLevel` * @dev Sets the safety level. The account may publish content that is less safe than this, so long as it is flagged as such. * @param safetyLevel safety level */ function setSafetyLevel(SafetyLevel safetyLevel) { glofiles[msg.sender].safetyLevel = safetyLevel; Update(msg.sender); } /** * @notice Set your Glofile full name to `fullName` * @dev Sets the full name. * @param fullName UTF-8 string of full name - max length 128 chars */ function setFullName(string fullName) { glofiles[msg.sender].fullName = fullName; Update(msg.sender); } /** * @notice Set your Glofile location * @dev Sets the location. A dedicated contract could be used for more sophisticated location functionality. * @param location UTF-8 string of location - max string length 128 chars */ function setLocation(string location) { glofiles[msg.sender].location = location; Update(msg.sender); } /** * @notice Set your Glofile foreground colors * @dev Sets all the foreground colors. * @param colors array of RGB triplets */ function setForegroundColors(bytes3[] colors) { glofiles[msg.sender].foregroundColors = colors; Update(msg.sender); } /** * @notice Set your Glofile background colors * @dev Sets all the background colors. * @param colors array of RGB triplets */ function setBackgroundColors(bytes3[] colors) { glofiles[msg.sender].backgroundColors = colors; Update(msg.sender); } /** * @notice Sets the Glofile langauges your account may publish in * @dev Sets all the languages the account may publish in. * @param languages array of 3 letter ISO 639-3 language codes */ function setLanguages(bytes3[] languages) { glofiles[msg.sender].languages = languages; Update(msg.sender); } /** * @notice Get Glofile basic info * @dev Gets all the info that can be retreived in a single call. * @param account Glofile to access * @return dontIndex flag to indicate that this Glofile should not be indexed * @return glofileType Glofile type * @return safetyLevel safety level * @return fullName UTF-8 string of full name * @return location UTF-8 string of location * @return foregroundColors array of RGB triplets of foreground colors * @return backgroundColors array of RGB triplets of background colors * @return languages array of 3 letter ISO 639-3 language codes */ function getBasicInfo(address account) constant returns (bool dontIndex, GlofileType glofileType, SafetyLevel safetyLevel, string fullName, string location, bytes3[] foregroundColors, bytes3[] backgroundColors, bytes3[] languages) { Glofile glofile = glofiles[account]; dontIndex = glofile.dontIndex; glofileType = glofile.glofileType; safetyLevel = glofile.safetyLevel; fullName = glofile.fullName; location = glofile.location; foregroundColors = glofile.foregroundColors; backgroundColors = glofile.backgroundColors; languages = glofile.languages; } /** * @notice Set your Glofile bio with langauge code `language` * @dev Sets the bio in a specific language. * @param language 3 letter ISO 639-3 language code * @param translation UTF-8 Markdown of bio compressed with DEFLATE - max Markdown length 256 chars */ function setBio(bytes3 language, bytes translation) { Glofile glofile = glofiles[msg.sender]; // Check if we already have the language code. for (uint i = 0; i < glofile.bioLanguages.length; i++) { if (glofile.bioLanguages[i] == language) { break; } } if (i == glofile.bioLanguages.length) { // We didn't find it. Try to find a free slot. for (i = 0; i < glofile.bioLanguages.length; i++) { if (glofile.bioLanguages[i] == 0) { break; } } if (i == glofile.bioLanguages.length) { // We didn't find a free slot. Make the array bigger. glofile.bioLanguages.length++; } glofile.bioLanguages[i] = language; } // Set translation. glofile.bioTranslations[language] = translation; Update(msg.sender); } /** * @notice Delete your Glofile bio with language code `language` * @dev Deletes a bio translation. * @param language 3 letter ISO 639-3 language code */ function deleteBio(bytes3 language) { Glofile glofile = glofiles[msg.sender]; for (uint i = 0; i < glofile.bioLanguages.length; i++) { if (glofile.bioLanguages[i] == language) { delete glofile.bioLanguages[i]; break; } } // Delete the actual mapping in case a client accesses without checking // language key. delete glofile.bioTranslations[language]; Update(msg.sender); } /** * @notice Delete all of your Glofile bio translations * @dev Deletes all of the bio translations. */ function deleteAllBioTranslations() { Glofile glofile = glofiles[msg.sender]; // Delete the actual mappings in case a client accesses without checking // language key. for (uint i = 0; i < glofile.bioLanguages.length; i++) { delete glofile.bioTranslations[glofile.bioLanguages[i]]; } delete glofile.bioLanguages; Update(msg.sender); } /** * @notice Get the list of language code a Glofile bio is available in * @dev Gets the list of language codes the bio is available in. * @param account Glofile to access * @return array of 3 letter ISO 639-3 language codes */ function getBioLanguages(address account) constant returns (bytes3[]) { return glofiles[account].bioLanguages; } /** * @notice Get the Glofile bio with language code `language` * @dev Gets the bio in a specific language. * @param account Glofile to access * @param language 3 letter ISO 639-3 language code * @return UTF-8 Markdown of bio compressed with DEFLATE */ function getBio(address account, bytes3 language) constant returns (bytes) { return glofiles[account].bioTranslations[language]; } /** * @notice Set your Glofile avatar with index `i` to `ipfsHash` * @dev Sets the avatar with a specific index to an IPFS hash. * @param i index of avatar to set * @param ipfsHash binary IPFS hash of image */ function setAvatar(uint i, bytes ipfsHash) { bytes[] avatars = glofiles[msg.sender].avatars; // Make sure the array is long enough. if (avatars.length <= i) { avatars.length = i + 1; } avatars[i] = ipfsHash; Update(msg.sender); } /** * @notice Delete your Glofile avatar with index `i` * @dev Deletes an avatar with a specific index. * @param i index of avatar to delete */ function deleteAvatar(uint i) { delete glofiles[msg.sender].avatars[i]; Update(msg.sender); } /** * @notice Delete all your Glofile avatars * @dev Deletes all avatars from the Glofile. */ function deleteAllAvatars() { delete glofiles[msg.sender].avatars; Update(msg.sender); } /** * @notice Get the number of Glofile avatars * @dev Gets the number of avatars. * @param account Glofile to access * @return number of avatars */ function getAvatarCount(address account) constant returns (uint) { return glofiles[account].avatars.length; } /** * @notice Get the Glofile avatar with index `i` * @dev Gets the avatar with a specific index. * @param account Glofile to access * @param i index of avatar to get * @return binary IPFS hash of image */ function getAvatar(address account, uint i) constant returns (bytes) { return glofiles[account].avatars[i]; } /** * @notice Set your Glofile cover image with index `i` to `ipfsHash` * @dev Sets the cover image with a specific index to an IPFS hash. * @param i index of cover image to set * @param ipfsHash binary IPFS hash of image */ function setCoverImage(uint i, bytes ipfsHash) { bytes[] coverImages = glofiles[msg.sender].coverImages; // Make sure the array is long enough. if (coverImages.length <= i) { coverImages.length = i + 1; } coverImages[i] = ipfsHash; Update(msg.sender); } /** * @notice Delete your Glofile cover image with index `i` * @dev Deletes the cover image with a specific index. * @param i index of cover image to delete */ function deleteCoverImage(uint i) { delete glofiles[msg.sender].coverImages[i]; Update(msg.sender); } /** * @notice Delete all your Glofile cover images * @dev Deletes all cover images from the Glofile. */ function deleteAllCoverImages() { delete glofiles[msg.sender].coverImages; Update(msg.sender); } /** * @notice Get the number of Glofile cover images * @dev Gets the number of cover images. * @param account Glofile to access * @return number of cover images */ function getCoverImageCount(address account) constant returns (uint) { return glofiles[account].coverImages.length; } /** * @notice Get the Glofile cover image with index `i` * @dev Gets the cover image with a specific index. * @param account Glofile to access * @param i index of cover image to get * @return binary IPFS hash of image */ function getCoverImage(address account, uint i) constant returns (bytes) { return glofiles[account].coverImages[i]; } /** * @notice Set your Glofile background image with index `i` to `ipfsHash` * @dev Sets the background image with a specific index to an IPFS hash. * @param i index of background image to set * @param ipfsHash binary IPFS hash of image */ function setBackgroundImage(uint i, bytes ipfsHash) { bytes[] backgroundImages = glofiles[msg.sender].backgroundImages; // Make sure the array is long enough. if (backgroundImages.length <= i) { backgroundImages.length = i + 1; } backgroundImages[i] = ipfsHash; Update(msg.sender); } /** * @notice Delete your Glofile background image with index `i` * @dev Deletes the background image with a specific index. * @param i index of background image to delete */ function deleteBackgroundImage(uint i) { delete glofiles[msg.sender].backgroundImages[i]; Update(msg.sender); } /** * @notice Delete all your Glofile background images * @dev Deletes all the background images. */ function deleteAllBackgroundImages() { delete glofiles[msg.sender].backgroundImages; Update(msg.sender); } /** * @notice Get the number of Glofile background images * @dev Gets the number of background images. * @param account Glofile to access * @return number of background images */ function getBackgroundImageCount(address account) constant returns (uint) { return glofiles[account].backgroundImages.length; } /** * @notice Get the Glofile background image with index `i` * @dev Gets the background image with a specific index. * @param i index of cover image to get * @param account Glofile to access * @return binary IPFS hash of image */ function getBackgroundImage(address account, uint i) constant returns (bytes) { return glofiles[account].backgroundImages[i]; } /** * @notice Set your Glofile topic with index `i` to `topic` * @dev Sets the topic with a specific index. * @param i index of topic to set * @param topic UTF-8 string of topic (no whitespace) */ function setTopic(uint i, string topic) { string[] topics = glofiles[msg.sender].topics; // Make sure the array is long enough. if (topics.length <= i) { topics.length = i + 1; } topics[i] = topic; Update(msg.sender); } /** * @notice Delete your Glofile topic with index `i` * @dev Deletes an topic with a specific index. * @param i index of topic to delete */ function deleteTopic(uint i) { delete glofiles[msg.sender].topics[i]; Update(msg.sender); } /** * @notice Delete all your Glofile topics * @dev Deletes all topics from the Glofile. */ function deleteAllTopics() { delete glofiles[msg.sender].topics; Update(msg.sender); } /** * @notice Get the number of Glofile topics * @dev Gets the number of topics. * @param account Glofile to access * @return number of topics */ function getTopicCount(address account) constant returns (uint) { return glofiles[account].topics.length; } /** * @notice Get the Glofile topic with index `i` * @dev Gets the topic with a specific index. * @param account Glofile to access * @param i index of topic to get * @return UTF-8 string of topic */ function getTopic(address account, uint i) constant returns (string) { return glofiles[account].topics[i]; } /** * @notice Set your Glofile parent with index `i` to `parent` * @dev Sets the parent with a specific index. * @param i index of parent to set * @param parent UTF-8 string of parent */ function setParent(uint i, string parent) { string[] parents = glofiles[msg.sender].parents; // Make sure the array is long enough. if (parents.length <= i) { parents.length = i + 1; } parents[i] = parent; Update(msg.sender); } /** * @notice Delete your Glofile parent with index `i` * @dev Deletes an parent with a specific index. * @param i index of parent to delete */ function deleteParent(uint i) { delete glofiles[msg.sender].parents[i]; Update(msg.sender); } /** * @notice Delete all your Glofile parents * @dev Deletes all parents from the Glofile. */ function deleteAllParents() { delete glofiles[msg.sender].parents; Update(msg.sender); } /** * @notice Get the number of Glofile parents * @dev Gets the number of parents. * @param account Glofile to access * @return number of parents */ function getParentCount(address account) constant returns (uint) { return glofiles[account].parents.length; } /** * @notice Get the Glofile parent with index `i` * @dev Gets the parent with a specific index. * @param account Glofile to access * @param i index of parent to get * @return UTF-8 string of parent */ function getParent(address account, uint i) constant returns (string) { return glofiles[account].parents[i]; } /** * @notice Set your Glofile child with index `i` to `child` * @dev Sets the child with a specific index. * @param i index of child to set * @param child UTF-8 string of child */ function setChild(uint i, string child) { string[] children = glofiles[msg.sender].children; // Make sure the array is long enough. if (children.length <= i) { children.length = i + 1; } children[i] = child; Update(msg.sender); } /** * @notice Delete your Glofile child with index `i` * @dev Deletes an child with a specific index. * @param i index of child to delete */ function deleteChild(uint i) { delete glofiles[msg.sender].children[i]; Update(msg.sender); } /** * @notice Delete all your Glofile children * @dev Deletes all children from the Glofile. */ function deleteAllChildren() { delete glofiles[msg.sender].children; Update(msg.sender); } /** * @notice Get the number of Glofile children * @dev Gets the number of children. * @param account Glofile to access * @return number of children */ function getChildCount(address account) constant returns (uint) { return glofiles[account].children.length; } /** * @notice Get the Glofile child with index `i` * @dev Gets the child with a specific index. * @param account Glofile to access * @param i index of child to get * @return UTF-8 string of child */ function getChild(address account, uint i) constant returns (string) { return glofiles[account].children[i]; } /** * @notice Set your Glofile uri with index `i` to `uri` * @dev Sets the uri with a specific index. * @param i index of uri to set * @param uri UTF-8 string of uri */ function setUri(uint i, string uri) { string[] uris = glofiles[msg.sender].uris; // Make sure the array is long enough. if (uris.length <= i) { uris.length = i + 1; } uris[i] = uri; Update(msg.sender); } /** * @notice Delete your Glofile uri with index `i` * @dev Deletes an uri with a specific index. * @param i index of uri to delete */ function deleteUri(uint i) { delete glofiles[msg.sender].uris[i]; Update(msg.sender); } /** * @notice Delete all your Glofile uris * @dev Deletes all uris from the Glofile. */ function deleteAllUris() { delete glofiles[msg.sender].uris; Update(msg.sender); } /** * @notice Get the number of Glofile uris * @dev Gets the number of uris. * @param account Glofile to access * @return number of uris */ function getUriCount(address account) constant returns (uint) { return glofiles[account].uris.length; } /** * @notice Get the Glofile uri with index `i` * @dev Gets the uri with a specific index. * @param account Glofile to access * @param i index of uri to get * @return UTF-8 string of uri */ function getUri(address account, uint i) constant returns (string) { return glofiles[account].uris[i]; } /** * @notice Copy entire Glofile from `source` * @dev Copies the Glofile from another account to this one. * @param source account of Glofile to copy from * TODO: check this works */ function copyEntireGlofile(address source) { glofiles[msg.sender] = glofiles[source]; Update(msg.sender); } /** * @notice Delete your entire Glofile * @dev Deletes the Glofile completely. * TODO: make sure this deletes everything */ function deleteEntireGlofile() { delete glofiles[msg.sender]; Delete(msg.sender); } }
* @notice Get the number of Glofile parents @dev Gets the number of parents. @param account Glofile to access @return number of parents/
function getParentCount(address account) constant returns (uint) { return glofiles[account].parents.length; }
12,551,903
[ 1, 967, 326, 1300, 434, 611, 383, 768, 6298, 225, 11881, 326, 1300, 434, 6298, 18, 225, 2236, 611, 383, 768, 358, 2006, 327, 1300, 434, 6298, 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 ]
[ 1, 1, 1, 1, 1, 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, 225, 445, 5089, 1380, 12, 2867, 2236, 13, 5381, 1135, 261, 11890, 13, 288, 203, 565, 327, 314, 383, 2354, 63, 4631, 8009, 12606, 18, 2469, 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 ]
pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "../lib/ReentrancyGuard.sol"; import "../lib/Utils.sol"; import "../lib/SafePeakToken.sol"; import "../interfaces/IPeakToken.sol"; import "../interfaces/IPeakDeFiFund.sol"; import "../interfaces/IUniswapOracle.sol"; import "../interfaces/IProtectionStaking.sol"; contract ProtectionStaking is IProtectionStaking, Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; using SafePeakToken for IPeakToken; address public sharesToken; IPeakDeFiFund public fund; IPeakToken public peakToken; IUniswapOracle public uniswapOracle; uint256 public mintedPeakTokens; uint256 public peakMintCap = 5000000 * PEAK_PRECISION; // default 5 million PEAK uint256 internal constant PEAK_PRECISION = 10**8; uint256 internal constant USDC_PRECISION = 10**6; uint256 internal constant PERCENTS_DECIMALS = 10**20; mapping(address => uint256) public peaks; mapping(address => uint256) public shares; mapping(address => uint256) public startProtectTimestamp; mapping(address => uint256) internal _lastClaimTimestamp; mapping(address => uint256) public lastClaimAmount; event ClaimCompensation( address investor, uint256 amount, uint256 timestamp ); event RequestProtection( address investor, uint256 amount, uint256 timestamp ); event Withdraw(address investor, uint256 amount, uint256 timestamp); event ProtectShares(address investor, uint256 amount, uint256 timestamp); event WithdrawShares(address investor, uint256 amount, uint256 timestamp); event ChangePeakMintCap(uint256 newAmmount); modifier during(IPeakDeFiFund.CyclePhase phase) { require(fund.cyclePhase() == phase, "wrong phase"); if (fund.cyclePhase() == IPeakDeFiFund.CyclePhase.Intermission) { require(fund.isInitialized(), "fund not initialized"); } _; } modifier ifNoCompensation() { uint256 peakPriceInUsdc = _getPeakPriceInUsdc(); uint256 compensationAmount = _calculateCompensating( msg.sender, peakPriceInUsdc ); require(compensationAmount == 0, "have compensation"); _; } constructor( address payable _fundAddr, address _peakTokenAddr, address _sharesTokenAddr, address _uniswapOracle ) public { __initReentrancyGuard(); require(_fundAddr != address(0)); require(_peakTokenAddr != address(0)); fund = IPeakDeFiFund(_fundAddr); peakToken = IPeakToken(_peakTokenAddr); uniswapOracle = IUniswapOracle(_uniswapOracle); sharesToken = _sharesTokenAddr; } function() external {} function _lostFundAmount(address _investor) internal view returns (uint256 lostFundAmount) { uint256 totalLostFundAmount = fund.totalLostFundAmount(); uint256 investorLostFundAmount = lastClaimAmount[_investor]; lostFundAmount = totalLostFundAmount.sub(investorLostFundAmount); } function _calculateCompensating(address _investor, uint256 _peakPriceInUsdc) internal view returns (uint256) { uint256 totalFundsAtManagePhaseStart = fund .totalFundsAtManagePhaseStart(); uint256 totalShares = fund.totalSharesAtLastManagePhaseStart(); uint256 managePhaseStartTime = fund.startTimeOfLastManagementPhase(); uint256 lostFundAmount = _lostFundAmount(_investor); uint256 sharesAmount = shares[_investor]; if ( fund.cyclePhase() != IPeakDeFiFund.CyclePhase.Intermission || managePhaseStartTime < _lastClaimTimestamp[_investor] || managePhaseStartTime < startProtectTimestamp[_investor] || mintedPeakTokens >= peakMintCap || peaks[_investor] == 0 || lostFundAmount == 0 || totalShares == 0 || _peakPriceInUsdc == 0 || sharesAmount == 0 ) { return 0; } uint256 sharesInUsdcAmount = sharesAmount .mul(totalFundsAtManagePhaseStart) .div(totalShares); uint256 peaksInUsdcAmount = peaks[_investor].mul(_peakPriceInUsdc).div( PEAK_PRECISION ); uint256 protectedPercent = PERCENTS_DECIMALS; if (peaksInUsdcAmount < sharesInUsdcAmount) { protectedPercent = peaksInUsdcAmount.mul(PERCENTS_DECIMALS).div( sharesInUsdcAmount ); } uint256 ownLostFundInUsd = lostFundAmount.mul(sharesAmount).div( totalShares ); uint256 compensationInUSDC = ownLostFundInUsd.mul(protectedPercent).div( PERCENTS_DECIMALS ); uint256 compensationInPeak = compensationInUSDC.mul(PEAK_PRECISION).div( _peakPriceInUsdc ); if (peakMintCap - mintedPeakTokens < compensationInPeak) { compensationInPeak = peakMintCap - mintedPeakTokens; } return compensationInPeak; } function calculateCompensating(address _investor, uint256 _peakPriceInUsdc) public view returns (uint256) { return _calculateCompensating(_investor, _peakPriceInUsdc); } function updateLastClaimAmount() internal { lastClaimAmount[msg.sender] = fund.totalLostFundAmount(); } function claimCompensation() external during(IPeakDeFiFund.CyclePhase.Intermission) nonReentrant { uint256 peakPriceInUsdc = _getPeakPriceInUsdc(); uint256 compensationAmount = _calculateCompensating( msg.sender, peakPriceInUsdc ); require(compensationAmount > 0, "not have compensation"); _lastClaimTimestamp[msg.sender] = block.timestamp; peakToken.mint(msg.sender, compensationAmount); mintedPeakTokens = mintedPeakTokens.add(compensationAmount); require( mintedPeakTokens <= peakMintCap, "ProtectionStaking: reached cap" ); updateLastClaimAmount(); emit ClaimCompensation(msg.sender, compensationAmount, block.timestamp); } function requestProtection(uint256 _amount) external during(IPeakDeFiFund.CyclePhase.Intermission) nonReentrant ifNoCompensation { require(_amount > 0, "amount is 0"); peakToken.safeTransferFrom(msg.sender, address(this), _amount); peaks[msg.sender] = peaks[msg.sender].add(_amount); startProtectTimestamp[msg.sender] = block.timestamp; updateLastClaimAmount(); emit RequestProtection(msg.sender, _amount, block.timestamp); } function withdraw(uint256 _amount) external ifNoCompensation { require( peaks[msg.sender] >= _amount, "insufficient fund in Peak Token" ); require(_amount > 0, "amount is 0"); peaks[msg.sender] = peaks[msg.sender].sub(_amount); peakToken.safeTransfer(msg.sender, _amount); updateLastClaimAmount(); emit Withdraw(msg.sender, _amount, block.timestamp); } function protectShares(uint256 _amount) external nonReentrant during(IPeakDeFiFund.CyclePhase.Intermission) ifNoCompensation { require(_amount > 0, "amount is 0"); IERC20(sharesToken).safeTransferFrom( msg.sender, address(this), _amount ); startProtectTimestamp[msg.sender] = block.timestamp; shares[msg.sender] = shares[msg.sender].add(_amount); updateLastClaimAmount(); emit ProtectShares(msg.sender, _amount, block.timestamp); } function withdrawShares(uint256 _amount) external nonReentrant ifNoCompensation { require( shares[msg.sender] >= _amount, "insufficient fund in Share Token" ); require(_amount > 0, "amount is 0"); shares[msg.sender] = shares[msg.sender].sub(_amount); IERC20(sharesToken).safeTransfer(msg.sender, _amount); emit WithdrawShares(msg.sender, _amount, block.timestamp); } function setPeakMintCap(uint256 _amount) external onlyOwner { require(mintedPeakTokens < _amount, "wrong amount"); peakMintCap = _amount; emit ChangePeakMintCap(_amount); } function _getPeakPriceInUsdc() internal returns (uint256) { uniswapOracle.update(); uint256 priceInUSDC = uniswapOracle.consult( address(peakToken), PEAK_PRECISION ); if (priceInUSDC == 0) { return USDC_PRECISION.mul(3).div(10); } return priceInUSDC; } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { 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; } } pragma solidity ^0.5.0; import "../GSN/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. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _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`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity 0.5.17; /** * @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 ReentrancyGuard { bool private _notEntered; function __initReentrancyGuard() 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; } } pragma solidity 0.5.17; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/IKyberNetwork.sol"; /** * @title The smart contract for useful utility functions and constants. * @author Zefram Lou (Zebang Liu) */ contract Utils { using SafeMath for uint256; using SafeERC20 for ERC20Detailed; /** * @notice Checks if `_token` is a valid token. * @param _token the token's address */ modifier isValidToken(address _token) { require(_token != address(0)); if (_token != address(ETH_TOKEN_ADDRESS)) { require(isContract(_token)); } _; } address public USDC_ADDR; address payable public KYBER_ADDR; address payable public ONEINCH_ADDR; bytes public constant PERM_HINT = "PERM"; // The address Kyber Network uses to represent Ether ERC20Detailed internal constant ETH_TOKEN_ADDRESS = ERC20Detailed(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee); ERC20Detailed internal usdc; IKyberNetwork internal kyber; uint256 internal constant PRECISION = (10**18); uint256 internal constant MAX_QTY = (10**28); // 10B tokens uint256 internal constant ETH_DECIMALS = 18; uint256 internal constant MAX_DECIMALS = 18; constructor( address _usdcAddr, address payable _kyberAddr, address payable _oneInchAddr ) public { USDC_ADDR = _usdcAddr; KYBER_ADDR = _kyberAddr; ONEINCH_ADDR = _oneInchAddr; usdc = ERC20Detailed(_usdcAddr); kyber = IKyberNetwork(_kyberAddr); } /** * @notice Get the number of decimals of a token * @param _token the token to be queried * @return number of decimals */ function getDecimals(ERC20Detailed _token) internal view returns (uint256) { if (address(_token) == address(ETH_TOKEN_ADDRESS)) { return uint256(ETH_DECIMALS); } return uint256(_token.decimals()); } /** * @notice Get the token balance of an account * @param _token the token to be queried * @param _addr the account whose balance will be returned * @return token balance of the account */ function getBalance(ERC20Detailed _token, address _addr) internal view returns (uint256) { if (address(_token) == address(ETH_TOKEN_ADDRESS)) { return uint256(_addr.balance); } return uint256(_token.balanceOf(_addr)); } /** * @notice Calculates the rate of a trade. The rate is the price of the source token in the dest token, in 18 decimals. * Note: the rate is on the token level, not the wei level, so for example if 1 Atoken = 10 Btoken, then the rate * from A to B is 10 * 10**18, regardless of how many decimals each token uses. * @param srcAmount amount of source token * @param destAmount amount of dest token * @param srcDecimals decimals used by source token * @param dstDecimals decimals used by dest token */ function calcRateFromQty( uint256 srcAmount, uint256 destAmount, uint256 srcDecimals, uint256 dstDecimals ) internal pure returns (uint256) { require(srcAmount <= MAX_QTY); require(destAmount <= MAX_QTY); if (dstDecimals >= srcDecimals) { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); return ((destAmount * PRECISION) / ((10**(dstDecimals - srcDecimals)) * srcAmount)); } else { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); return ((destAmount * PRECISION * (10**(srcDecimals - dstDecimals))) / srcAmount); } } /** * @notice Wrapper function for doing token conversion on Kyber Network * @param _srcToken the token to convert from * @param _srcAmount the amount of tokens to be converted * @param _destToken the destination token * @return _destPriceInSrc the price of the dest token, in terms of source tokens * _srcPriceInDest the price of the source token, in terms of dest tokens * _actualDestAmount actual amount of dest token traded * _actualSrcAmount actual amount of src token traded */ function __kyberTrade( ERC20Detailed _srcToken, uint256 _srcAmount, ERC20Detailed _destToken ) internal returns ( uint256 _destPriceInSrc, uint256 _srcPriceInDest, uint256 _actualDestAmount, uint256 _actualSrcAmount ) { require(_srcToken != _destToken); uint256 beforeSrcBalance = getBalance(_srcToken, address(this)); uint256 msgValue; if (_srcToken != ETH_TOKEN_ADDRESS) { msgValue = 0; _srcToken.safeApprove(KYBER_ADDR, 0); _srcToken.safeApprove(KYBER_ADDR, _srcAmount); } else { msgValue = _srcAmount; } _actualDestAmount = kyber.tradeWithHint.value(msgValue)( _srcToken, _srcAmount, _destToken, toPayableAddr(address(this)), MAX_QTY, 1, address(0), PERM_HINT ); _actualSrcAmount = beforeSrcBalance.sub( getBalance(_srcToken, address(this)) ); require(_actualDestAmount > 0 && _actualSrcAmount > 0); _destPriceInSrc = calcRateFromQty( _actualDestAmount, _actualSrcAmount, getDecimals(_destToken), getDecimals(_srcToken) ); _srcPriceInDest = calcRateFromQty( _actualSrcAmount, _actualDestAmount, getDecimals(_srcToken), getDecimals(_destToken) ); } /** * @notice Wrapper function for doing token conversion on 1inch * @param _srcToken the token to convert from * @param _srcAmount the amount of tokens to be converted * @param _destToken the destination token * @return _destPriceInSrc the price of the dest token, in terms of source tokens * _srcPriceInDest the price of the source token, in terms of dest tokens * _actualDestAmount actual amount of dest token traded * _actualSrcAmount actual amount of src token traded */ function __oneInchTrade( ERC20Detailed _srcToken, uint256 _srcAmount, ERC20Detailed _destToken, bytes memory _calldata ) internal returns ( uint256 _destPriceInSrc, uint256 _srcPriceInDest, uint256 _actualDestAmount, uint256 _actualSrcAmount ) { require(_srcToken != _destToken); uint256 beforeSrcBalance = getBalance(_srcToken, address(this)); uint256 beforeDestBalance = getBalance(_destToken, address(this)); // Note: _actualSrcAmount is being used as msgValue here, because otherwise we'd run into the stack too deep error if (_srcToken != ETH_TOKEN_ADDRESS) { _actualSrcAmount = 0; _srcToken.safeApprove(ONEINCH_ADDR, 0); _srcToken.safeApprove(ONEINCH_ADDR, _srcAmount); } else { _actualSrcAmount = _srcAmount; } // trade through 1inch proxy (bool success, ) = ONEINCH_ADDR.call.value(_actualSrcAmount)(_calldata); require(success); // calculate trade amounts and price _actualDestAmount = getBalance(_destToken, address(this)).sub( beforeDestBalance ); _actualSrcAmount = beforeSrcBalance.sub( getBalance(_srcToken, address(this)) ); require(_actualDestAmount > 0 && _actualSrcAmount > 0); _destPriceInSrc = calcRateFromQty( _actualDestAmount, _actualSrcAmount, getDecimals(_destToken), getDecimals(_srcToken) ); _srcPriceInDest = calcRateFromQty( _actualSrcAmount, _actualDestAmount, getDecimals(_srcToken), getDecimals(_destToken) ); } /** * @notice Checks if an Ethereum account is a smart contract * @param _addr the account to be checked * @return True if the account is a smart contract, false otherwise */ function isContract(address _addr) internal view returns (bool) { uint256 size; if (_addr == address(0)) return false; assembly { size := extcodesize(_addr) } return size > 0; } function toPayableAddr(address _addr) internal pure returns (address payable) { return address(uint160(_addr)); } } pragma solidity ^0.5.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../interfaces/IPeakToken.sol"; /** * @title SafePeakToken * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafePeakToken { using SafeMath for uint256; using Address for address; function safeTransfer(IPeakToken token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IPeakToken token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IPeakToken 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(IPeakToken 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(IPeakToken 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(IPeakToken token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity 0.5.17; interface IPeakToken { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function mint(address recipient, uint256 amount) external returns (bool); function burn(uint256 amount) external; function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); } pragma solidity 0.5.17; interface IPeakDeFiFund { enum CyclePhase { Intermission, Manage } enum VoteDirection { Empty, For, Against } enum Subchunk { Propose, Vote } function initParams( address payable _devFundingAccount, uint256[2] calldata _phaseLengths, uint256 _devFundingRate, address payable _previousVersion, address _usdcAddr, address payable _kyberAddr, address _compoundFactoryAddr, address _peakdefiLogic, address _peakdefiLogic2, address _peakdefiLogic3, uint256 _startCycleNumber, address payable _oneInchAddr, address _peakRewardAddr, address _peakStakingAddr ) external; function initOwner() external; function cyclePhase() external view returns (CyclePhase phase); function isInitialized() external view returns (bool); function devFundingAccount() external view returns (uint256); function previousVersion() external view returns (uint256); function cycleNumber() external view returns (uint256); function totalFundsInUSDC() external view returns (uint256); function totalFundsAtManagePhaseStart() external view returns (uint256); function totalLostFundAmount() external view returns (uint256); function totalFundsAtManagePhaseEnd() external view returns (uint256); function startTimeOfCyclePhase() external view returns (uint256); function startTimeOfLastManagementPhase() external view returns (uint256); function devFundingRate() external view returns (uint256); function totalCommissionLeft() external view returns (uint256); function totalSharesAtLastManagePhaseStart() external view returns (uint256); function peakReferralTotalCommissionLeft() external view returns (uint256); function peakManagerStakeRequired() external view returns (uint256); function peakReferralToken() external view returns (uint256); function peakReward() external view returns (address); function peakStaking() external view returns (address); function isPermissioned() external view returns (bool); function initInternalTokens( address _repAddr, address _sTokenAddr, address _peakReferralTokenAddr ) external; function initRegistration( uint256 _newManagerRepToken, uint256 _maxNewManagersPerCycle, uint256 _reptokenPrice, uint256 _peakManagerStakeRequired, bool _isPermissioned ) external; function initTokenListings( address[] calldata _acceptedTokens, address[] calldata _compoundTokens ) external; function setProxy(address payable proxyAddr) external; function developerInitiateUpgrade(address payable _candidate) external returns (bool _success); function migrateOwnedContractsToNextVersion() external; function transferAssetToNextVersion(address _assetAddress) external; function investmentsCount(address _userAddr) external view returns (uint256 _count); function nextVersion() external view returns (address payable); function transferOwnership(address newOwner) external; function compoundOrdersCount(address _userAddr) external view returns (uint256 _count); function getPhaseLengths() external view returns (uint256[2] memory _phaseLengths); function commissionBalanceOf(address _manager) external returns (uint256 _commission, uint256 _penalty); function commissionOfAt(address _manager, uint256 _cycle) external returns (uint256 _commission, uint256 _penalty); function changeDeveloperFeeAccount(address payable _newAddr) external; function changeDeveloperFeeRate(uint256 _newProp) external; function listKyberToken(address _token) external; function listCompoundToken(address _token) external; function nextPhase() external; function registerWithUSDC() external; function registerWithETH() external payable; function registerWithToken(address _token, uint256 _donationInTokens) external; function depositEther(address _referrer) external payable; function depositEtherAdvanced( bool _useKyber, bytes calldata _calldata, address _referrer ) external payable; function depositUSDC(uint256 _usdcAmount, address _referrer) external; function depositToken( address _tokenAddr, uint256 _tokenAmount, address _referrer ) external; function depositTokenAdvanced( address _tokenAddr, uint256 _tokenAmount, bool _useKyber, bytes calldata _calldata, address _referrer ) external; function withdrawEther(uint256 _amountInUSDC) external; function withdrawEtherAdvanced( uint256 _amountInUSDC, bool _useKyber, bytes calldata _calldata ) external; function withdrawUSDC(uint256 _amountInUSDC) external; function withdrawToken(address _tokenAddr, uint256 _amountInUSDC) external; function withdrawTokenAdvanced( address _tokenAddr, uint256 _amountInUSDC, bool _useKyber, bytes calldata _calldata ) external; function redeemCommission(bool _inShares) external; function redeemCommissionForCycle(bool _inShares, uint256 _cycle) external; function sellLeftoverToken(address _tokenAddr, bytes calldata _calldata) external; function sellLeftoverCompoundOrder(address payable _orderAddress) external; function burnDeadman(address _deadman) external; function createInvestment( address _tokenAddress, uint256 _stake, uint256 _maxPrice ) external; function createInvestmentV2( address _sender, address _tokenAddress, uint256 _stake, uint256 _maxPrice, bytes calldata _calldata, bool _useKyber ) external; function sellInvestmentAsset( uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice ) external; function sellInvestmentAssetV2( address _sender, uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice, bytes calldata _calldata, bool _useKyber ) external; function createCompoundOrder( address _sender, bool _orderType, address _tokenAddress, uint256 _stake, uint256 _minPrice, uint256 _maxPrice ) external; function sellCompoundOrder( address _sender, uint256 _orderId, uint256 _minPrice, uint256 _maxPrice ) external; function repayCompoundOrder( address _sender, uint256 _orderId, uint256 _repayAmountInUSDC ) external; function emergencyExitCompoundTokens( address _sender, uint256 _orderId, address _tokenAddr, address _receiver ) external; function peakReferralCommissionBalanceOf(address _referrer) external returns (uint256 _commission); function peakReferralCommissionOfAt(address _referrer, uint256 _cycle) external returns (uint256 _commission); function peakReferralRedeemCommission() external; function peakReferralRedeemCommissionForCycle(uint256 _cycle) external; function peakChangeManagerStakeRequired(uint256 _newValue) external; } pragma solidity 0.5.17; // interface for contract_v6/UniswapOracle.sol interface IUniswapOracle { function update() external returns (bool success); function consult(address token, uint256 amountIn) external view returns (uint256 amountOut); } pragma solidity 0.5.17; interface IProtectionStaking { function calculateCompensating(address _investor, uint256 _peakPriceInUsdc) external view returns (uint256); function claimCompensation() external; function requestProtection(uint256 _amount) external; function withdraw(uint256 _amount) external; function protectShares(uint256 _amount) external; function withdrawShares(uint256 _amount) external; function setPeakMintCap(uint256 _amount) external; } pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity ^0.5.0; import "./IERC20.sol"; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } pragma solidity ^0.5.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity 0.5.17; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; /** * @title The interface for the Kyber Network smart contract * @author Zefram Lou (Zebang Liu) */ interface IKyberNetwork { function getExpectedRate( ERC20Detailed src, ERC20Detailed dest, uint256 srcQty ) external view returns (uint256 expectedRate, uint256 slippageRate); function tradeWithHint( ERC20Detailed src, uint256 srcAmount, ERC20Detailed dest, address payable destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId, bytes calldata hint ) external payable returns (uint256); } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @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]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } }
* @notice Get the number of decimals of a token @param _token the token to be queried @return number of decimals/
function getDecimals(ERC20Detailed _token) internal view returns (uint256) { if (address(_token) == address(ETH_TOKEN_ADDRESS)) { return uint256(ETH_DECIMALS); } return uint256(_token.decimals()); }
1,591,072
[ 1, 967, 326, 1300, 434, 15105, 434, 279, 1147, 225, 389, 2316, 326, 1147, 358, 506, 23264, 327, 1300, 434, 15105, 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, 31809, 12, 654, 39, 3462, 40, 6372, 389, 2316, 13, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 2867, 24899, 2316, 13, 422, 1758, 12, 1584, 44, 67, 8412, 67, 15140, 3719, 288, 203, 5411, 327, 2254, 5034, 12, 1584, 44, 67, 23816, 55, 1769, 203, 3639, 289, 203, 3639, 327, 2254, 5034, 24899, 2316, 18, 31734, 10663, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.11; // for test import "./AnemoiToken.sol"; import "./SCRtoken.sol"; import "./SafeMath.sol"; import "./Ownable.sol"; import "./Pausable.sol"; contract AnemoiSaleContract is Ownable,SafeMath,Pausable { IndorseToken ind; // crowdsale parameters uint256 public fundingStartTime = 1502193600; uint256 public fundingEndTime = 1504785600; uint256 public totalSupply; address public ethFundDeposit = "###"; // deposit address for ETH for Anemoi Fund address public anmFundDeposit = "###"; // deposit address for Anemoi reserve address public anmAddress = "###"; bool public isFinalized; // switched to true in operational state uint256 public constant decimals = 18; // #dp in Indorse contract uint256 public tokenCreationCap; uint256 public constant tokenExchangeRate = 1000; // 1000 ANM tokens per 1 ETH uint256 public constant minContribution = 0.05 ether; uint256 public constant maxTokens = 1 * (10 ** 6) * 10**decimals; uint256 public constant MAX_GAS_PRICE = 50000000000 wei; // maximum gas price for contribution transactions function ANemoiSaleContract() { ind = AnemoiToken(anmAddress); tokenCreationCap = ind.balanceOf(anmFundDeposit); isFinalized = false; } event MintANM(address from, address to, uint256 val); event LogRefund(address indexed _to, uint256 _value); function CreateANM(address to, uint256 val) internal returns (bool success){ MintANM(anmFundDeposit,to,val); return anm.transferFrom(anmFundDeposit,to,val); } function () payable { createTokens(msg.sender,msg.value); } /// @dev Accepts ether and creates new ANM tokens. function createTokens(address _beneficiary, uint256 _value) internal whenNotPaused { require (tokenCreationCap > totalSupply); // CAP reached no more please require (now >= fundingStartTime); require (now <= fundingEndTime); require (_value >= minContribution); // To avoid spam transactions on the network require (!isFinalized); require (tx.gasprice <= MAX_GAS_PRICE); uint256 tokens = safeMult(_value, tokenExchangeRate); // check that we're not over totals uint256 checkedSupply = safeAdd(totalSupply, tokens); require (anm.balanceOf(msg.sender) + tokens <= maxTokens); // DA ... fairly allocate the last few tokens if (tokenCreationCap < checkedSupply) { uint256 tokensToAllocate = safeSubtract(tokenCreationCap,totalSupply); uint256 tokensToRefund = safeSubtract(tokens,tokensToAllocate); totalSupply = tokenCreationCap; uint256 etherToRefund = tokensToRefund / tokenExchangeRate; require(CreateIND(_beneficiary,tokensToAllocate)); // Create ANM msg.sender.transfer(etherToRefund); LogRefund(msg.sender,etherToRefund); ethFundDeposit.transfer(this.balance); return; } // DA ... end of fair allocation code totalSupply = checkedSupply; require(CreateIND(_beneficiary, tokens)); // logs token creation ethFundDeposit.transfer(this.balance); } /// @dev Ends the funding period and sends the ETH home function finalize() external onlyOwner { require (!isFinalized); // move to operational isFinalized = true; ethFundDeposit.transfer(this.balance); // send the eth to Anemoi multi-sig } }
switched to true in operational state
bool public isFinalized;
998,017
[ 1, 9610, 329, 358, 638, 316, 1674, 287, 919, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1426, 1071, 29200, 1235, 31, 4766, 11794, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xe6F4d9711121e5304b30aC2Aae57E3b085ad3c4d/sources/src/libraries/external/TakerActions.sol
[WAD] Borrower's t0 penalty - 7% from current debt if intial take, 0 otherwise.
uint256 t0DebtPenalty;
3,630,349
[ 1, 63, 59, 1880, 65, 605, 15318, 264, 1807, 268, 20, 23862, 300, 2371, 9, 628, 783, 18202, 88, 309, 509, 649, 4862, 16, 374, 3541, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 268, 20, 758, 23602, 24251, 15006, 31, 2398, 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 ]
pragma solidity ^0.4.8; import 'zeppelin/token/StandardToken.sol'; import 'zeppelin/token/ERC20.sol'; // This contract is a fund that can be owned by many different people/addresses. // Ownership is determined by how many of the "TokenOwnedFund" ERC20 tokens are held. // Any ERC20 tokens that are owned by this contract can be withdrawn based on the percentage of TokenOwnedFund tokens owned by the withdrawing account. contract TokenOwnedFund is StandardToken { string public name = "TokenOwnedFund"; string public symbol = "TF1"; uint public decimals = 18; uint public INITIAL_SUPPLY = 100000; mapping(ERC20 => mapping(address => uint)) public pendingWithdraws; // Create the TokenOwnedFund Token and assign all ownership to the creator function TokenOwnedFund() { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } // Allow a token owner to redeem their ownership in this contract so that they can withdraw the underlying asset tokens. // The caller's TokenOwnedFund balance will be set to 0 and the number of underlying Asset Tokens will be calculated. // The caller can then "pull" out their assigned asset tokens in a separate call. // The caller must know all Addresses for underlying asset tokens and include them in this call. If they do not include the full list, their ownership in the Asset Tokens will be lost. function Redeem(ERC20[] assetTokens) { // Verify the asssetToken list is valid if (!assetTokens || assetTokens.length == 0){ throw; } // Verify the caller actually owns a piece of this fund uint redeemAmount = balances[msg.sender]; if(redeemAmount == 0){ throw; } // Save off the original supply before the contract info gets updated uint originalTotalSupply = totalSupply; // Update the total supply of tokens and zero out the sender's balance totalSupply -= redeemAmount; balances[msg.sender] = 0; // Iterate over the asset tokens and calculate how much the redeemer should be credited with. for(uint i = 0; i < assetTokens.length; i++){ // Get a reference to the current Asset Token ERC20 currentAssetToken = assetTokens[i]; // First get the total ownership of this underlying asset token uint totalAssetTokenOwnership = currentAssetToken.balanceOf(this); // If there is no ownership, then bail out to inform the user they did something wrong if(totalAssetTokenOwnership == 0) { throw; } // Save off the amount that the caller should be allowed to withdraw for this asset token uint assetTokenOwned = totalAssetTokenOwnership * redeemAmount / originalTotalSupply; pendingWithdraws[currentAssetToken][msg.sender] += assetTokenOwned; } } // Allow a withdraw of an Asset Token that was assigned through a redemption function withdrawAssetToken(ERC20 assetToken) { // Get the amount to withdraw uint amountToWithdraw = pendingWithdraws[assetToken][msg.sender]; // Verify the amount to withdraw is valid if( amountToWithdraw == 0) { throw; } // Zero out the pending withdraw amount pendingWithdraws[assetToken][msg.sender] = 0; // Trigger the withdraw and bail if there is a problem if(!assetToken.transfer(msg.sender, amountToWithdraw)){ throw; } } }
Verify the caller actually owns a piece of this fund
uint redeemAmount = balances[msg.sender];
13,059,062
[ 1, 8097, 326, 4894, 6013, 29065, 279, 11151, 434, 333, 284, 1074, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 283, 24903, 6275, 273, 324, 26488, 63, 3576, 18, 15330, 15533, 7010, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/62320/0x6BC2ff220C1F18AfDd09aEb4966CB2D2c1b0902D/sources/lib/mento-core-2.2.0/contracts/oracles/BreakerBox.sol
* @notice Gets the updated breaker trading mode for a specific rateFeed. @param rateFeedID The address of the rateFeed. @param breaker The address of the breaker to update./
function updateBreaker(address rateFeedID, address breaker) internal returns (uint8) { if (rateFeedBreakerStatus[rateFeedID][breaker].tradingMode != 0) { return tryResetBreaker(rateFeedID, breaker); } return checkBreaker(rateFeedID, breaker); }
3,225,601
[ 1, 3002, 326, 3526, 898, 264, 1284, 7459, 1965, 364, 279, 2923, 4993, 8141, 18, 225, 4993, 8141, 734, 1021, 1758, 434, 326, 4993, 8141, 18, 225, 898, 264, 1021, 1758, 434, 326, 898, 264, 358, 1089, 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, 225, 445, 1089, 22660, 12, 2867, 4993, 8141, 734, 16, 1758, 898, 264, 13, 2713, 1135, 261, 11890, 28, 13, 288, 203, 565, 309, 261, 5141, 8141, 22660, 1482, 63, 5141, 8141, 734, 6362, 8820, 264, 8009, 313, 14968, 2309, 480, 374, 13, 288, 203, 1377, 327, 775, 7013, 22660, 12, 5141, 8141, 734, 16, 898, 264, 1769, 203, 565, 289, 203, 565, 327, 866, 22660, 12, 5141, 8141, 734, 16, 898, 264, 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 ]
./full_match/1/0x56102B469d7B0650E92426611Eb2Ea84C0cA9b2A/sources/contracts/QuestFactory.sol
Send the mint fee to the mint fee recipient
(bool mintSuccess, ) = getMintFeeRecipient().call{value: mintFee}("");
3,008,754
[ 1, 3826, 326, 312, 474, 14036, 358, 326, 312, 474, 14036, 8027, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 261, 6430, 312, 474, 4510, 16, 262, 273, 2108, 474, 14667, 18241, 7675, 1991, 95, 1132, 30, 312, 474, 14667, 97, 2932, 8863, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-04-28 */ // SPDX-License-Identifier: MIT // File: @openzeppelin\contracts-upgradeable\utils\introspection\IERC165Upgradeable.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 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); } // File: @openzeppelin\contracts-upgradeable\token\ERC721\IERC721Upgradeable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @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; } // File: @openzeppelin\contracts-upgradeable\token\ERC721\IERC721ReceiverUpgradeable.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 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); } // File: @openzeppelin\contracts-upgradeable\token\ERC721\extensions\IERC721MetadataUpgradeable.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 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); } // File: @openzeppelin\contracts-upgradeable\utils\AddressUpgradeable.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 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 * ==== * * [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 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-upgradeable\proxy\utils\Initializable.sol // OpenZeppelin Contracts (last updated v4.5.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 proxied contracts do not make use of 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() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // File: @openzeppelin\contracts-upgradeable\utils\ContextUpgradeable.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 ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // File: @openzeppelin\contracts-upgradeable\utils\StringsUpgradeable.sol // OpenZeppelin Contracts v4.4.1 (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); } } // File: @openzeppelin\contracts-upgradeable\utils\introspection\ERC165Upgradeable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // File: contracts\library\ERC721AUpgradeable.sol // Creator: Chiru Labs pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721AUpgradeable is ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; function __ERC721AUpgradeable_init(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(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 override returns (uint256) { require(owner != address(0), "BalanceQueryForZeroAddress"); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert("OwnerQueryForNonexistentToken"); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "URIQueryForNonexistentToken"); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ownerOf(tokenId); require(to != owner, "ApprovalToCurrentOwner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ApprovalCallerNotOwnerNorApproved"); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ApprovalQueryForNonexistentToken"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ApproveToCaller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert("TransferToNonERC721ReceiverImplementer"); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; require(to != address(0), "MintToZeroAddress"); require(quantity > 0, "MintZeroQuantity"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); require(_checkContractOnERC721Received(address(0), to, updatedIndex++, _data), "TransferToNonERC721ReceiverImplementer"); } while (updatedIndex != end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); require(prevOwnership.addr == from, "TransferFromIncorrectOwner"); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); require(isApprovedOrOwner, "TransferCallerNotOwnerNorApproved"); require(to != address(0), "TransferToZeroAddress"); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev This is equivalent to _burn(tokenId, false) */ function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); require(isApprovedOrOwner, "TransferCallerNotOwnerNorApproved"); } _beforeTokenTransfers(from, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try 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 ("TransferToNonERC721ReceiverImplementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: @openzeppelin\contracts-upgradeable\access\OwnableUpgradeable.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 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 onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _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); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // File: @openzeppelin\contracts-upgradeable\utils\structs\EnumerableSetUpgradeable.sol // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // File: contracts\library\AccessControlUpgradeable.sol pragma solidity ^0.8.0; abstract contract AccessControlUpgradeable is ContextUpgradeable, OwnableUpgradeable { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; /** * @dev Emitted when `account` is granted `role`. */ event RoleGranted(uint256 indexed role, address indexed account); /** * @dev Emitted when `account` is revoked `role`. */ event RoleRevoked(uint256 indexed role, address indexed account); mapping(uint256 => EnumerableSetUpgradeable.AddressSet) private _roles; function __AccessControlUpgradeable_init() public onlyInitializing { } modifier onlyRole(uint256 role) { require(hasRole(role, _msgSender()), "BEYOND THE PERMISSIONS"); _; } modifier onlyRoleOrOwner(uint256 role) { require(hasRole(role, _msgSender()) || (_msgSender() == owner()), "BEYOND THE PERMISSIONS"); _; } function hasRole(uint256 role, address account) public view returns (bool) { return _roles[role].contains(account); } function allAccountOfRole(uint256 role) public view returns (address[] memory) { return _roles[role].values(); } function grantRole(uint256 role, address account) public virtual onlyOwner{ _grantRole(role, account); } function revokeRole(uint256 role, address account) public virtual onlyOwner { _revokeRole(role, account); } function _grantRole(uint256 role, address account) internal { if (!hasRole(role, account)) { _roles[role].add(account); emit RoleGranted(role, account); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(uint256 role, address account) internal { if (hasRole(role, account)) { _roles[role].remove(account); emit RoleRevoked(role, account); } } } // 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\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\IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: contracts\YoloFox.sol pragma solidity ^0.8.4; contract YoloFox is AccessControlUpgradeable, ERC721AUpgradeable { uint16 public constant TOTAL_MAX_SUPPLY = 5555; using StringsUpgradeable for uint256; using AddressUpgradeable for address; enum UserRole{ NORMAL_USER, OG_USER, WL_USER, ADMIN_USER } string private _theBaseUrl; struct TimeInfoCollection { uint64 preSaleStartTime; uint64 preSaleEndTime; uint64 pubSaleEndTime; } TimeInfoCollection private _timeInfoCollection; struct CountInfoCollection { uint16 maxPreSaleCount; uint16 maxAirDropCount; uint16 airDropMintCount; uint16 preSaleMintCount; uint16 pubSaleMintCount; uint8 OGUserBuyLimit; uint8 WLUserBuyLimit; } CountInfoCollection private _countIntoCollection; struct PriceInfoCollection { uint80 OGUserBuyPrice; uint80 WLUserBuyPrice; uint80 pubSalePrice; } PriceInfoCollection private _priceInfoCollection; function initialize( string calldata tokenName, string calldata tokenSymbol ) public initializer { __ERC721AUpgradeable_init(tokenName, tokenSymbol); __Context_init(); __Ownable_init(); } //==========CONFIG SECTION============ function setBuyLimit(uint8 OGUserBuyLimit, uint8 WLUserBuyLimit) public onlyRoleOrOwner(uint256(UserRole.ADMIN_USER)) { _countIntoCollection.OGUserBuyLimit = OGUserBuyLimit; _countIntoCollection.WLUserBuyLimit = WLUserBuyLimit; } function getOGUserBuyLimit() public view returns(uint256) { return _countIntoCollection.OGUserBuyLimit; } function getWLUserBuyLimit() public view returns(uint256) { return _countIntoCollection.WLUserBuyLimit; } function setMaxCountLimit(uint16 maxPreSaleCount, uint16 maxAirDropCount) public onlyRoleOrOwner(uint256(UserRole.ADMIN_USER)) { require(maxPreSaleCount >= _countIntoCollection.preSaleMintCount, "NEW PRESALE MAX SHOULD BE MORE THAN SOLD COUNT"); require(maxAirDropCount >= _countIntoCollection.airDropMintCount, "NEW AIR DROP MAX SHOULD BE MORE THAN AIR DROPED COUNT"); _countIntoCollection.maxPreSaleCount = maxPreSaleCount; _countIntoCollection.maxAirDropCount = maxAirDropCount; } function getMaxPreSaleCount() public view returns(uint256) { return _countIntoCollection.maxPreSaleCount; } function getpreSaleMintCount() public view returns(uint256) { return _countIntoCollection.preSaleMintCount; } function getMaxAirDropCount() public view returns(uint256) { return _countIntoCollection.maxAirDropCount; } function getAirDropMintCount() public view returns(uint256) { return _countIntoCollection.airDropMintCount; } function setPrice(uint80 OGPrice, uint80 WLPrice, uint80 pubSalePrice) public onlyRoleOrOwner(uint256(UserRole.ADMIN_USER)) { _priceInfoCollection.OGUserBuyPrice = OGPrice; _priceInfoCollection.WLUserBuyPrice = WLPrice; _priceInfoCollection.pubSalePrice = pubSalePrice; } function getOGUserBuyPrice() public view returns(uint256) { return _priceInfoCollection.OGUserBuyPrice; } function getWLUserBuyPrice() public view returns(uint256) { return _priceInfoCollection.WLUserBuyPrice; } function getPubSalePrice() public view returns(uint256) { return _priceInfoCollection.pubSalePrice; } function setSaleTime( uint64 presaleStart, uint64 presaleEnd, uint64 publicSaleEnd ) external onlyRoleOrOwner(uint256(UserRole.ADMIN_USER)) { require((presaleStart < presaleEnd) && (presaleEnd < publicSaleEnd), "INVALID SALE TIME"); _timeInfoCollection.preSaleStartTime = presaleStart; _timeInfoCollection.preSaleEndTime = presaleEnd; _timeInfoCollection.pubSaleEndTime = publicSaleEnd; } function getPreSaleStartTime() public view returns(uint256) { return _timeInfoCollection.preSaleStartTime; } function getPreSaleEndTime() public view returns(uint256) { return _timeInfoCollection.preSaleEndTime; } function getPubSaleEndTime() public view returns(uint256) { return _timeInfoCollection.pubSaleEndTime; } function setBaseUrl(string calldata newBaseUrl) external onlyRoleOrOwner(uint256(UserRole.ADMIN_USER)) { _theBaseUrl = newBaseUrl; } //==========CONFIG SECTION============ //======= MINT SECTION ========== function airDropMint(address[] calldata toAddrs, uint16[] calldata quantities) external onlyRoleOrOwner(uint256(UserRole.ADMIN_USER)) { require(toAddrs.length == quantities.length, "THE INPUT ARRAY LENGTHS MUST BE EQUAL"); uint index; uint16 mintSum; do { mintSum += quantities[index++]; } while(index != quantities.length); require( (_countIntoCollection.airDropMintCount + mintSum) <= _countIntoCollection.maxAirDropCount, "AIR DROP COUNT EXCEEDED" ); unchecked { _countIntoCollection.airDropMintCount += mintSum; for(index=0; index<toAddrs.length; index++) { _safeMint(toAddrs[index], quantities[index]); } } } function _realLeftCount() internal view returns(uint16) { return TOTAL_MAX_SUPPLY - _countIntoCollection.maxAirDropCount - _countIntoCollection.preSaleMintCount - _countIntoCollection.pubSaleMintCount; } function buy(uint16 count) external payable { if (block.timestamp >= _timeInfoCollection.preSaleStartTime && block.timestamp < _timeInfoCollection.preSaleEndTime) { if (hasRole(uint256(UserRole.OG_USER), _msgSender())) { require(_numberMinted(_msgSender()) + count <= _countIntoCollection.OGUserBuyLimit, "Exceeded"); require(msg.value == _priceInfoCollection.OGUserBuyPrice * count, "InsufficientBalance"); } else if (hasRole(uint256(uint256(UserRole.WL_USER)), _msgSender())) { require(_numberMinted(_msgSender()) + count <= _countIntoCollection.WLUserBuyLimit, "Exceeded"); require(msg.value == _priceInfoCollection.WLUserBuyPrice * count, "InsufficientBalance"); } else { revert("PleaseWaitForPublicSale"); } require(_countIntoCollection.preSaleMintCount + count <= _countIntoCollection.maxPreSaleCount, "Exceeded"); unchecked { _countIntoCollection.preSaleMintCount += count; } _safeMint(_msgSender(), count); } else if (block.timestamp >= _timeInfoCollection.preSaleEndTime && block.timestamp < _timeInfoCollection.pubSaleEndTime) { require(count <= _realLeftCount(), "Exceeded"); require(msg.value == _priceInfoCollection.pubSalePrice * count, "InsufficientBalance"); unchecked { _countIntoCollection.pubSaleMintCount += count; } _safeMint(_msgSender(), count); } else { revert("NotInSale"); } } //======= MINT SECTION ENDS========== //======= ADMIN OP================= function addWhiteList(address[] calldata newWhiteList) external onlyRoleOrOwner(uint256(UserRole.ADMIN_USER)) { for (uint256 index = 0; index < newWhiteList.length; index++) { _grantRole(uint256(uint256(UserRole.WL_USER)), newWhiteList[index]); } } function removeWhiteList(address[] calldata removedWhiteList) external onlyRoleOrOwner(uint256(UserRole.ADMIN_USER)) { for (uint256 index = 0; index < removedWhiteList.length; index++) { _revokeRole(uint256(UserRole.WL_USER), removedWhiteList[index]); } } function addOGList(address[] calldata newOGList) external onlyRoleOrOwner(uint256(UserRole.ADMIN_USER)) { for (uint256 index = 0; index < newOGList.length; index++) { _grantRole(uint256(UserRole.OG_USER), newOGList[index]); } } function removeOGList(address[] calldata removedOGList) external onlyRoleOrOwner(uint256(UserRole.ADMIN_USER)) { for (uint256 index = 0; index < removedOGList.length; index++) { _revokeRole(uint256(UserRole.OG_USER), removedOGList[index]); } } function takeOutNativeToken(address payable to, uint256 amount) external onlyOwner { require(amount > 0, "AmountOfWithDrawDreaterThanZero"); require(address(this).balance >= amount, "InsufficientBalance"); to.transfer(amount); } //=======ADMIN OP ENDS================= //=======QUERY OP ================= function queryBuyableCount(address account) external view returns (uint256) { if (block.timestamp >= _timeInfoCollection.preSaleStartTime && block.timestamp < _timeInfoCollection.preSaleEndTime) { if (hasRole(uint256(UserRole.OG_USER), account)) { return _countIntoCollection.OGUserBuyLimit > _numberMinted(account) ? _countIntoCollection.OGUserBuyLimit - _numberMinted(account) : 0; } if (hasRole(uint256(UserRole.WL_USER), account)) { return _countIntoCollection.WLUserBuyLimit > _numberMinted(account) ? _countIntoCollection.WLUserBuyLimit - _numberMinted(account) : 0; } return 0; } if (block.timestamp >= _timeInfoCollection.preSaleEndTime && block.timestamp < _timeInfoCollection.pubSaleEndTime) { return _realLeftCount(); } return 0; } function queryUserType(address account) external view returns (UserRole) { if (hasRole(uint256(UserRole.OG_USER), account)) { return UserRole.OG_USER; } else if (hasRole(uint256(UserRole.WL_USER), account)) { return UserRole.WL_USER; } else { return UserRole.NORMAL_USER; } } function queryLeft() external view returns (uint256) { if (block.timestamp < _timeInfoCollection.preSaleStartTime) { return TOTAL_MAX_SUPPLY; } else if ((block.timestamp >= _timeInfoCollection.preSaleStartTime) && (block.timestamp < _timeInfoCollection.preSaleEndTime)) { return _countIntoCollection.maxPreSaleCount - _countIntoCollection.preSaleMintCount; } else if ((block.timestamp >= _timeInfoCollection.preSaleEndTime) && (block.timestamp < _timeInfoCollection.pubSaleEndTime)) { return _realLeftCount(); } return 0; } function queryPrice(address account, uint256 count) public view returns (uint256 finalPrice) { uint256 thePrice; if (block.timestamp <= _timeInfoCollection.preSaleEndTime) { if (hasRole(uint256(UserRole.OG_USER), account)) { thePrice = _priceInfoCollection.OGUserBuyPrice; } else if (hasRole(uint256(UserRole.WL_USER), account)) { thePrice = _priceInfoCollection.WLUserBuyPrice; } else { thePrice = _priceInfoCollection.pubSalePrice; } } else { thePrice = _priceInfoCollection.pubSalePrice; } finalPrice = thePrice * count; } function _baseURI() internal view override returns (string memory) { return _theBaseUrl; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner_, uint256 index) public view returns (uint256) { require(index < balanceOf(owner_), "OwnerIndexOutOfBounds"); uint256 count; address ownerOfCurrentToken; for (uint256 i = _startTokenId(); i < _currentIndex; ++i) { address user = _ownerships[i].addr; if (!_ownerships[i].burned) { if (user != address(0)) { ownerOfCurrentToken = user; } if (ownerOfCurrentToken == owner_) { if (index == count) return i; count++; } } } revert("ERROR"); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply(), "GlobalIndexOutOfBounds"); uint256 count; for (uint256 i = _startTokenId(); i < _currentIndex; ++i) { if (!_ownerships[i].burned) { if (index == count) return i; count++; } } revert("ERROR"); } //=======QUERY OP ENDS================= }
* @dev See {IERC721-balanceOf}./
function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "BalanceQueryForZeroAddress"); return uint256(_addressData[owner].balance); }
2,350,913
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 17, 12296, 951, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11013, 951, 12, 2867, 3410, 13, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 8443, 480, 1758, 12, 20, 3631, 315, 13937, 1138, 1290, 7170, 1887, 8863, 203, 203, 3639, 327, 2254, 5034, 24899, 2867, 751, 63, 8443, 8009, 12296, 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 ]
./full_match/11297108109/0x19D4F9A260AF1d7E0E99A32DBe418956af875c25/sources/contracts/NFTCollection/NFTAssetCollection.sol
register the supported interfaces to conform to ERC2981 via ERC165
{ name = _data.name; symbol = _data.symbol; collectionId = _data.collectionId; _registerInterface(_INTERFACE_ID_ERC2981); _registerInterface(type(IDATSNFTCollection).interfaceId); }
13,236,794
[ 1, 4861, 326, 3260, 7349, 358, 20156, 358, 4232, 39, 5540, 11861, 3970, 4232, 39, 28275, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 288, 203, 3639, 508, 273, 389, 892, 18, 529, 31, 203, 3639, 3273, 273, 389, 892, 18, 7175, 31, 203, 3639, 1849, 548, 273, 389, 892, 18, 5548, 548, 31, 203, 203, 3639, 389, 4861, 1358, 24899, 18865, 67, 734, 67, 654, 39, 5540, 11861, 1769, 203, 3639, 389, 4861, 1358, 12, 723, 12, 734, 789, 13653, 4464, 2532, 2934, 5831, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xD744Ef07d2e93179e54aF5017Bc190E4DD2a5478/sources/PropToken.sol
@notice retrieves ocean point contract address
function getOceanPointContract() public view returns (address) { return PropTokenHelpers(getDataAddress()).getOceanPointContract(); }
15,690,718
[ 1, 14580, 3324, 320, 31393, 1634, 6835, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 17971, 31393, 2148, 8924, 1435, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 10484, 1345, 13375, 12, 588, 751, 1887, 1435, 2934, 588, 51, 31393, 2148, 8924, 5621, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; // ---------------------------------------------------------------------------- // &#39;Virgin&#39; token contract // // Deployed to : 0x5bb274f87ecbccdcc0ec7a8b41ba457db2e03ada // Symbol : Hcoin // Name : Healthcoin // Total supply: 1000000000000000 // Decimals : 18 // // Enjoy. // Coding by Jarmo van de Seijp // (c) by Moritz Neto with BokkyPooBah / Bok Consulting Pty Ltd Au 2017. The MIT Licence. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // 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 // ---------------------------------------------------------------------------- contract ERC20Interface { 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); } // ---------------------------------------------------------------------------- // 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 data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public 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); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract Healthcoin 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 // ------------------------------------------------------------------------ function Healthcoin() public { symbol = "Hcoin"; name = "Healthcoin"; decimals = 18; _totalSupply = 1000000000000000000000000000; balances[0x5bb274f87ecbccdcc0ec7a8b41ba457db2e03ada] = _totalSupply; Transfer(address(0), 0x5bb274f87ecbccdcc0ec7a8b41ba457db2e03ada, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner&#39;s account to to account // - Owner&#39;s account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner&#39;s account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender&#39;s account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner&#39;s account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don&#39;t accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract Healthcoin 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; function Healthcoin() public { symbol = "Hcoin"; name = "Healthcoin"; decimals = 18; _totalSupply = 1000000000000000000000000000; balances[0x5bb274f87ecbccdcc0ec7a8b41ba457db2e03ada] = _totalSupply; Transfer(address(0), 0x5bb274f87ecbccdcc0ec7a8b41ba457db2e03ada, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public 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); Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
7,895,489
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 1551, 25444, 1147, 29375, 8879, 13849, 8879, 17082, 11417, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 11745, 12645, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 16, 14060, 10477, 288, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 225, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 1071, 389, 4963, 3088, 1283, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 203, 203, 565, 445, 11745, 12645, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 44, 12645, 14432, 203, 3639, 508, 273, 315, 7802, 12645, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 12648, 12648, 2787, 11706, 31, 203, 3639, 324, 26488, 63, 20, 92, 25, 9897, 5324, 24, 74, 11035, 557, 31345, 72, 952, 20, 557, 27, 69, 28, 70, 9803, 12124, 7950, 27, 1966, 22, 73, 4630, 16524, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 12279, 12, 2867, 12, 20, 3631, 374, 92, 25, 9897, 5324, 24, 74, 11035, 557, 31345, 72, 952, 20, 557, 27, 69, 28, 70, 9803, 12124, 7950, 27, 1966, 22, 73, 4630, 16524, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 5381, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 225, 300, 324, 26488, 63, 2867, 12, 20, 13, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 1071, 5381, 1135, 261, 11890, 11013, 13, 288, 2 ]
pragma solidity ^0.6.0; // Chainlink requires solidity 0.4. This is a working solution if willing to drop to older Solidity. /* import "../../node_modules/chainlink/contracts/ChainlinkClient.sol"; contract ConvertLib is ChainlinkClient { address public owner; uint256 public minLinkBalance; uint256 public currentPrice; // Stores the answer from the Chainlink oracle uint256 private payment; // Current payment for price request jobs constructor(address _link, address _oracle) public { // Set the address for the LINK token for the network. if(_link == address(0)) { // Useful for deploying to public networks. setPublicChainlinkToken(); } else { // Useful if you're deploying to a local network. setChainlinkToken(_link); } setChainlinkOracle(_oracle); } function setPayment(uint256 amount) public onlyOwner { payment = amount; } // Converts the amount in one token to another, danger: Web3 BigNumber function convert(uint256 amount, string inputSymbol, string outputSymbol) public pure returns (uint256 convertedAmount) { // TODO Wait for data to be available from request (wait for Event fire?) requestPriceInETH(inputSymbol); uint256 priceInputETH = currentPrice; requestPriceInETH(outputSymbol); uint256 priceOutputETH = currentPrice; return (priceInputETH / priceOutputETH) * amount; } // Returns the number of tokens for a given USD input in 10^-18 of a token, danger: Web3 BigNumber function usdToTokens(uint256 amountInCents, string symbol) public pure returns (uint256 price) { requestUSDtoTokens(symbol); uint256 dollarValInGigaSD = currentPrice; uint256 numberOfTokens = (amountInCents * dollarValInGigaSD) / 100; return numberOfTokens; } // Creates a Chainlink request with the uint256 multiplier job function requestPriceInETH(string symbol) public onlyOwner { // Check LINK balance is sufficient require(Interface(address("0x514910771af9ca656af840dff83e8264ecf986ca")).balanceOf(address(this)) >= minLinkBalance, "LINK balance of conversion contract is insufficient"); bytes32 jobId = keccak256(block.number, msg.data, nonce++); // newRequest takes a JobID, a callback address, and callback function as input Chainlink.Request memory req = buildChainlinkRequest(jobId, this, this.fulfill.selector); // Adds a URL with the key "get" to the request parameters req.add("get", "https://min-api.cryptocompare.com/data/price?fsym=" + symbol + "&tsyms=ETH"); // Uses input param (dot-delimited string) as the "path" in the request parameters req.add("path", "ETH"); // Request integer value in wei - may cause issues with web3 BigNumber req.addInt("times", 1000000000000000000); // Sends the request with the amount of payment specified to the oracle sendChainlinkRequest(req, payment); } // Creates a Chainlink request with the uint256 multiplier job function requestUSDtoTokens(string symbol) public onlyOwner { // Check LINK balance is sufficient require(Interface(address("0x514910771af9ca656af840dff83e8264ecf986ca")).balanceOf(address(this)) >= minLinkBalance, "LINK balance of conversion contract is insufficient"); bytes32 jobId = keccak256(block.number, msg.data, nonce++); // newRequest takes a JobID, a callback address, and callback function as input Chainlink.Request memory req = buildChainlinkRequest(jobId, this, this.fulfill.selector); // Adds a URL with the key "get" to the request parameters req.add("get", "https://min-api.cryptocompare.com/data/price?fsym=USD&tsyms=" + symbol); // Uses input param (dot-delimited string) as the "path" in the request parameters req.add("path", symbol); // Request integer value in smallest denomination - may cause issues with web3 BigNumber req.addInt("times", 1000000000000000000); // Sends the request with the amount of payment specified to the oracle sendChainlinkRequest(req, payment); } // Use recordChainlinkFulfillment to ensure only the requesting oracle can fulfill. Outputs uint256. function fulfill(bytes32 _requestId, uint256 _price) public recordChainlinkFulfillment(_requestId) { currentPrice = _price; } // withdrawLink allows the owner to withdraw any extra LINK on the contract function withdrawLink() public onlyOwner { LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress()); require(link.transfer(msg.sender, link.balanceOf(address(this))), "Unable to transfer"); } // Set the minimumLinkBalance of the contract to cover jobs. function setMinLinkBalance(uint256 amount) public onlyOwner { minLinkBalance = amount; } modifier onlyOwner() { require(msg.sender == owner, "Message sender must be contract owner"); _; } } */
Set the address for the LINK token for the network. Useful for deploying to public networks. Useful if you're deploying to a local network.
constructor(address _link, address _oracle) public { if(_link == address(0)) { setPublicChainlinkToken(); setChainlinkToken(_link); } setChainlinkOracle(_oracle); }
15,814,205
[ 1, 694, 326, 1758, 364, 326, 22926, 1147, 364, 326, 2483, 18, 19256, 364, 7286, 310, 358, 1071, 13884, 18, 19256, 309, 1846, 4565, 7286, 310, 358, 279, 1191, 2483, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 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, 202, 12316, 12, 2867, 389, 1232, 16, 1758, 389, 280, 16066, 13, 1071, 288, 203, 202, 202, 430, 24899, 1232, 422, 1758, 12, 20, 3719, 288, 203, 1082, 202, 542, 4782, 3893, 1232, 1345, 5621, 203, 1082, 202, 542, 3893, 1232, 1345, 24899, 1232, 1769, 203, 202, 202, 97, 203, 202, 202, 542, 3893, 1232, 23601, 24899, 280, 16066, 1769, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-09-07 */ // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Part: AddressUpgradeable /** * @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 in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: IController interface IController { function withdraw(address, uint256) external; function strategies(address) external view returns (address); function balanceOf(address) external view returns (uint256); function earn(address, uint256) external; function want(address) external view returns (address); function rewards() external view returns (address); function vaults(address) external view returns (address); } // Part: ICurvePool interface ICurvePool { function exchange( int128 i, int128 j, uint256 _dx, uint256 _min_dy ) external returns (uint256); } // Part: ICvxLocker interface ICvxLocker { function notifyRewardAmount(address _rewardsToken, uint256 reward) external; function maximumBoostPayment() external returns (uint256); function lock( address _account, uint256 _amount, uint256 _spendRatio ) external; function getReward(address _account, bool _stake) external; //BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch function balanceOf(address _user) external view returns (uint256 amount); // total token balance of an account, including unlocked but not withdrawn tokens function lockedBalanceOf(address _user) external view returns (uint256 amount); // Withdraw/relock all currently locked tokens where the unlock time has passed function processExpiredLocks( bool _relock, uint256 _spendRatio, address _withdrawTo ) external; // Withdraw/relock all currently locked tokens where the unlock time has passed function processExpiredLocks(bool _relock) external; } // Part: IDelegateRegistry ///@dev Snapshot Delegate registry so we can delegate voting to XYZ interface IDelegateRegistry { function setDelegate(bytes32 id, address delegate) external; function delegation(address, bytes32) external returns (address); } // Part: IERC20Upgradeable /** * @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 ); } // Part: ISettV3 interface ISettV3 { function deposit(uint256 _amount) external; function withdraw(uint256 _amount) external; function getPricePerFullShare() external view returns (uint256); function balanceOf(address) external view returns (uint256); } // Part: IUniswapRouterV2 interface IUniswapRouterV2 { function factory() external view returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } // Part: Initializable /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require( _initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized" ); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // Part: MathUpgradeable /** * @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); } } // Part: SafeMathUpgradeable /** * @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 { /** * @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; } } // Part: ContextUpgradeable /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer {} function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // Part: SafeERC20Upgradeable /** * @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 SafeMathUpgradeable for uint256; 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' // 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( IERC20Upgradeable 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( IERC20Upgradeable 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(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 // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // Part: SettAccessControl /* Common base for permissioned roles throughout Sett ecosystem */ contract SettAccessControl is Initializable { address public governance; address public strategist; address public keeper; // ===== MODIFIERS ===== function _onlyGovernance() internal view { require(msg.sender == governance, "onlyGovernance"); } function _onlyGovernanceOrStrategist() internal view { require( msg.sender == strategist || msg.sender == governance, "onlyGovernanceOrStrategist" ); } function _onlyAuthorizedActors() internal view { require( msg.sender == keeper || msg.sender == governance, "onlyAuthorizedActors" ); } // ===== PERMISSIONED ACTIONS ===== /// @notice Change strategist address /// @notice Can only be changed by governance itself function setStrategist(address _strategist) external { _onlyGovernance(); strategist = _strategist; } /// @notice Change keeper address /// @notice Can only be changed by governance itself function setKeeper(address _keeper) external { _onlyGovernance(); keeper = _keeper; } /// @notice Change governance address /// @notice Can only be changed by governance itself function setGovernance(address _governance) public { _onlyGovernance(); governance = _governance; } uint256[50] private __gap; } // Part: PausableUpgradeable /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // Part: BaseStrategy /* ===== Badger Base Strategy ===== Common base class for all Sett strategies Changelog V1.1 - Verify amount unrolled from strategy positions on withdraw() is within a threshold relative to the requested amount as a sanity check - Add version number which is displayed with baseStrategyVersion(). If a strategy does not implement this function, it can be assumed to be 1.0 V1.2 - Remove idle want handling from base withdraw() function. This should be handled as the strategy sees fit in _withdrawSome() */ abstract contract BaseStrategy is PausableUpgradeable, SettAccessControl { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; event Withdraw(uint256 amount); event WithdrawAll(uint256 balance); event WithdrawOther(address token, uint256 amount); event SetStrategist(address strategist); event SetGovernance(address governance); event SetController(address controller); event SetWithdrawalFee(uint256 withdrawalFee); event SetPerformanceFeeStrategist(uint256 performanceFeeStrategist); event SetPerformanceFeeGovernance(uint256 performanceFeeGovernance); event Harvest(uint256 harvested, uint256 indexed blockNumber); event Tend(uint256 tended); address public want; // Want: Curve.fi renBTC/wBTC (crvRenWBTC) LP token uint256 public performanceFeeGovernance; uint256 public performanceFeeStrategist; uint256 public withdrawalFee; uint256 public constant MAX_FEE = 10000; address public constant uniswap = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Uniswap Dex address public controller; address public guardian; uint256 public withdrawalMaxDeviationThreshold; function __BaseStrategy_init( address _governance, address _strategist, address _controller, address _keeper, address _guardian ) public initializer whenNotPaused { __Pausable_init(); governance = _governance; strategist = _strategist; keeper = _keeper; controller = _controller; guardian = _guardian; withdrawalMaxDeviationThreshold = 50; } // ===== Modifiers ===== function _onlyController() internal view { require(msg.sender == controller, "onlyController"); } function _onlyAuthorizedActorsOrController() internal view { require( msg.sender == keeper || msg.sender == governance || msg.sender == controller, "onlyAuthorizedActorsOrController" ); } function _onlyAuthorizedPausers() internal view { require( msg.sender == guardian || msg.sender == governance, "onlyPausers" ); } /// ===== View Functions ===== function baseStrategyVersion() public view returns (string memory) { return "1.2"; } /// @notice Get the balance of want held idle in the Strategy function balanceOfWant() public view returns (uint256) { return IERC20Upgradeable(want).balanceOf(address(this)); } /// @notice Get the total balance of want realized in the strategy, whether idle or active in Strategy positions. function balanceOf() public view virtual returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function isTendable() public view virtual returns (bool) { return false; } /// ===== Permissioned Actions: Governance ===== function setGuardian(address _guardian) external { _onlyGovernance(); guardian = _guardian; } function setWithdrawalFee(uint256 _withdrawalFee) external { _onlyGovernance(); require( _withdrawalFee <= MAX_FEE, "base-strategy/excessive-withdrawal-fee" ); withdrawalFee = _withdrawalFee; } function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external { _onlyGovernance(); require( _performanceFeeStrategist <= MAX_FEE, "base-strategy/excessive-strategist-performance-fee" ); performanceFeeStrategist = _performanceFeeStrategist; } function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external { _onlyGovernance(); require( _performanceFeeGovernance <= MAX_FEE, "base-strategy/excessive-governance-performance-fee" ); performanceFeeGovernance = _performanceFeeGovernance; } function setController(address _controller) external { _onlyGovernance(); controller = _controller; } function setWithdrawalMaxDeviationThreshold(uint256 _threshold) external { _onlyGovernance(); require( _threshold <= MAX_FEE, "base-strategy/excessive-max-deviation-threshold" ); withdrawalMaxDeviationThreshold = _threshold; } function deposit() public virtual whenNotPaused { _onlyAuthorizedActorsOrController(); uint256 _want = IERC20Upgradeable(want).balanceOf(address(this)); if (_want > 0) { _deposit(_want); } _postDeposit(); } // ===== Permissioned Actions: Controller ===== /// @notice Controller-only function to Withdraw partial funds, normally used with a vault withdrawal function withdrawAll() external virtual whenNotPaused returns (uint256 balance) { _onlyController(); _withdrawAll(); _transferToVault(IERC20Upgradeable(want).balanceOf(address(this))); } /// @notice Withdraw partial funds from the strategy, unrolling from strategy positions as necessary /// @notice Processes withdrawal fee if present /// @dev If it fails to recover sufficient funds (defined by withdrawalMaxDeviationThreshold), the withdrawal should fail so that this unexpected behavior can be investigated function withdraw(uint256 _amount) external virtual whenNotPaused { _onlyController(); // Withdraw from strategy positions, typically taking from any idle want first. _withdrawSome(_amount); uint256 _postWithdraw = IERC20Upgradeable(want).balanceOf(address(this)); // Sanity check: Ensure we were able to retrieve sufficent want from strategy positions // If we end up with less than the amount requested, make sure it does not deviate beyond a maximum threshold if (_postWithdraw < _amount) { uint256 diff = _diff(_amount, _postWithdraw); // Require that difference between expected and actual values is less than the deviation threshold percentage require( diff <= _amount.mul(withdrawalMaxDeviationThreshold).div(MAX_FEE), "base-strategy/withdraw-exceed-max-deviation-threshold" ); } // Return the amount actually withdrawn if less than amount requested uint256 _toWithdraw = MathUpgradeable.min(_postWithdraw, _amount); // Process withdrawal fee uint256 _fee = _processWithdrawalFee(_toWithdraw); // Transfer remaining to Vault to handle withdrawal _transferToVault(_toWithdraw.sub(_fee)); } // NOTE: must exclude any tokens used in the yield // Controller role - withdraw should return to Controller function withdrawOther(address _asset) external virtual whenNotPaused returns (uint256 balance) { _onlyController(); _onlyNotProtectedTokens(_asset); balance = IERC20Upgradeable(_asset).balanceOf(address(this)); IERC20Upgradeable(_asset).safeTransfer(controller, balance); } /// ===== Permissioned Actions: Authoized Contract Pausers ===== function pause() external { _onlyAuthorizedPausers(); _pause(); } function unpause() external { _onlyGovernance(); _unpause(); } /// ===== Internal Helper Functions ===== /// @notice If withdrawal fee is active, take the appropriate amount from the given value and transfer to rewards recipient /// @return The withdrawal fee that was taken function _processWithdrawalFee(uint256 _amount) internal returns (uint256) { if (withdrawalFee == 0) { return 0; } uint256 fee = _amount.mul(withdrawalFee).div(MAX_FEE); IERC20Upgradeable(want).safeTransfer( IController(controller).rewards(), fee ); return fee; } /// @dev Helper function to process an arbitrary fee /// @dev If the fee is active, transfers a given portion in basis points of the specified value to the recipient /// @return The fee that was taken function _processFee( address token, uint256 amount, uint256 feeBps, address recipient ) internal returns (uint256) { if (feeBps == 0) { return 0; } uint256 fee = amount.mul(feeBps).div(MAX_FEE); IERC20Upgradeable(token).safeTransfer(recipient, fee); return fee; } /// @dev Reset approval and approve exact amount function _safeApproveHelper( address token, address recipient, uint256 amount ) internal { IERC20Upgradeable(token).safeApprove(recipient, 0); IERC20Upgradeable(token).safeApprove(recipient, amount); } function _transferToVault(uint256 _amount) internal { address _vault = IController(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20Upgradeable(want).safeTransfer(_vault, _amount); } /// @notice Swap specified balance of given token on Uniswap with given path function _swap( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForTokens( balance, 0, path, address(this), now ); } function _swapEthIn(uint256 balance, address[] memory path) internal { IUniswapRouterV2(uniswap).swapExactETHForTokens{value: balance}( 0, path, address(this), now ); } function _swapEthOut( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForETH( balance, 0, path, address(this), now ); } /// @notice Add liquidity to uniswap for specified token pair, utilizing the maximum balance possible function _add_max_liquidity_uniswap(address token0, address token1) internal virtual { uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this)); uint256 _token1Balance = IERC20Upgradeable(token1).balanceOf(address(this)); _safeApproveHelper(token0, uniswap, _token0Balance); _safeApproveHelper(token1, uniswap, _token1Balance); IUniswapRouterV2(uniswap).addLiquidity( token0, token1, _token0Balance, _token1Balance, 0, 0, address(this), block.timestamp ); } /// @notice Utility function to diff two numbers, expects higher value in first position function _diff(uint256 a, uint256 b) internal pure returns (uint256) { require(a >= b, "diff/expected-higher-number-in-first-position"); return a.sub(b); } // ===== Abstract Functions: To be implemented by specific Strategies ===== /// @dev Internal deposit logic to be implemented by Stratgies function _deposit(uint256 _amount) internal virtual; function _postDeposit() internal virtual { //no-op by default } /// @notice Specify tokens used in yield process, should not be available to withdraw via withdrawOther() function _onlyNotProtectedTokens(address _asset) internal virtual; function getProtectedTokens() external view virtual returns (address[] memory); /// @dev Internal logic for strategy migration. Should exit positions as efficiently as possible function _withdrawAll() internal virtual; /// @dev Internal logic for partial withdrawals. Should exit positions as efficiently as possible. /// @dev The withdraw() function shell automatically uses idle want in the strategy before attempting to withdraw more using this function _withdrawSome(uint256 _amount) internal virtual returns (uint256); /// @dev Realize returns from positions /// @dev Returns can be reinvested into positions, or distributed in another fashion /// @dev Performance fees should also be implemented in this function /// @dev Override function stub is removed as each strategy can have it's own return signature for STATICCALL // function harvest() external virtual; /// @dev User-friendly name for this strategy for purposes of convenient reading function getName() external pure virtual returns (string memory); /// @dev Balance of want currently held in strategy positions function balanceOfPool() public view virtual returns (uint256); uint256[49] private __gap; } // File: MyStrategy.sol contract MyStrategy is BaseStrategy { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; uint256 MAX_BPS = 10_000; // address public want // Inherited from BaseStrategy, the token the strategy wants, swaps into and tries to grow address public lpComponent; // Token we provide liquidity with address public reward; // Token we farm and swap to want / lpComponent address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant CVX = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B; address public constant CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant SUSHI_ROUTER = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; IDelegateRegistry public constant SNAPSHOT = IDelegateRegistry(0x469788fE6E9E9681C6ebF3bF78e7Fd26Fc015446); // The initial DELEGATE for the strategy // NOTE we can change it by using manualSetDelegate below address public constant DELEGATE = 0x14F83fF95D4Ec5E8812DDf42DA1232b0ba1015e6; bytes32 public constant DELEGATED_SPACE = 0x6376782e65746800000000000000000000000000000000000000000000000000; ISettV3 public constant CVX_VAULT = ISettV3(0x53C8E199eb2Cb7c01543C137078a038937a68E40); // NOTE: At time of publishing, this contract is under audit ICvxLocker public constant LOCKER = ICvxLocker(0xD18140b4B819b895A3dba5442F959fA44994AF50); // Curve Pool to swap between cvxCRV and CRV ICurvePool public constant CURVE_POOL = ICurvePool(0x9D0464996170c6B9e75eED71c68B99dDEDf279e8); bool public withdrawalSafetyCheck = true; bool public harvestOnRebalance = true; // If nothing is unlocked, processExpiredLocks will revert bool public processLocksOnReinvest = true; bool public processLocksOnRebalance = true; event Debug(string name, uint256 value); // Used to signal to the Badger Tree that rewards where sent to it event TreeDistribution( address indexed token, uint256 amount, uint256 indexed blockNumber, uint256 timestamp ); function initialize( address _governance, address _strategist, address _controller, address _keeper, address _guardian, address[3] memory _wantConfig, uint256[3] memory _feeConfig ) public initializer { __BaseStrategy_init( _governance, _strategist, _controller, _keeper, _guardian ); /// @dev Add config here want = _wantConfig[0]; lpComponent = _wantConfig[1]; reward = _wantConfig[2]; performanceFeeGovernance = _feeConfig[0]; performanceFeeStrategist = _feeConfig[1]; withdrawalFee = _feeConfig[2]; /// @dev do one off approvals here // Sushi to swap CRV -> CVX IERC20Upgradeable(CRV).safeApprove(SUSHI_ROUTER, type(uint256).max); // Curve to swap cvxCRV -> CRV IERC20Upgradeable(reward).safeApprove(address(CURVE_POOL), type(uint256).max); // Permissions for Locker IERC20Upgradeable(CVX).safeApprove(address(LOCKER), type(uint256).max); IERC20Upgradeable(CVX).safeApprove( address(CVX_VAULT), type(uint256).max ); // Delegate voting to DELEGATE SNAPSHOT.setDelegate(DELEGATED_SPACE, DELEGATE); } /// ===== Extra Functions ===== /// @dev Change Delegation to another address function manualSetDelegate(address delegate) public { _onlyGovernance(); // Set delegate is enough as it will clear previous delegate automatically SNAPSHOT.setDelegate(DELEGATED_SPACE, delegate); } ///@dev Should we check if the amount requested is more than what we can return on withdrawal? function setWithdrawalSafetyCheck(bool newWithdrawalSafetyCheck) public { _onlyGovernance(); withdrawalSafetyCheck = newWithdrawalSafetyCheck; } ///@dev Should we harvest before doing manual rebalancing ///@notice you most likely want to skip harvest if everything is unlocked, or there's something wrong and you just want out function setHarvestOnRebalance(bool newHarvestOnRebalance) public { _onlyGovernance(); harvestOnRebalance = newHarvestOnRebalance; } ///@dev Should we processExpiredLocks during reinvest? function setProcessLocksOnReinvest(bool newProcessLocksOnReinvest) public { _onlyGovernance(); processLocksOnReinvest = newProcessLocksOnReinvest; } ///@dev Should we processExpiredLocks during manualRebalance? function setProcessLocksOnRebalance(bool newProcessLocksOnRebalance) public { _onlyGovernance(); processLocksOnRebalance = newProcessLocksOnRebalance; } /// ===== View Functions ===== /// @dev Specify the name of the strategy function getName() external pure override returns (string memory) { return "veCVX Voting Strategy"; } /// @dev Specify the version of the Strategy, for upgrades function version() external pure returns (string memory) { return "1.0"; } /// @dev From CVX Token to Helper Vault Token function CVXToWant(uint256 cvx) public view returns (uint256) { uint256 bCVXToCVX = CVX_VAULT.getPricePerFullShare(); return cvx.mul(10**18).div(bCVXToCVX); } /// @dev From Helper Vault Token to CVX Token function wantToCVX(uint256 want) public view returns (uint256) { uint256 bCVXToCVX = CVX_VAULT.getPricePerFullShare(); return want.mul(bCVXToCVX).div(10**18); } /// @dev Balance of want currently held in strategy positions function balanceOfPool() public view override returns (uint256) { if (withdrawalSafetyCheck) { uint256 bCVXToCVX = CVX_VAULT.getPricePerFullShare(); // 18 decimals require(bCVXToCVX > 10**18, "Loss Of Peg"); // Avoid trying to redeem for less / loss of peg } // Return the balance in locker + unlocked but not withdrawn, better estimate to allow some withdrawals // then multiply it by the price per share as we need to convert CVX to bCVX uint256 valueInLocker = CVXToWant(LOCKER.lockedBalanceOf(address(this))).add( CVXToWant(IERC20Upgradeable(CVX).balanceOf(address(this))) ); return (valueInLocker); } /// @dev Returns true if this strategy requires tending function isTendable() public view override returns (bool) { return false; } // @dev These are the tokens that cannot be moved except by the vault function getProtectedTokens() public view override returns (address[] memory) { address[] memory protectedTokens = new address[](4); protectedTokens[0] = want; protectedTokens[1] = lpComponent; protectedTokens[2] = reward; protectedTokens[3] = CVX; return protectedTokens; } /// ===== Permissioned Actions: Governance ===== /// @notice Delete if you don't need! function setKeepReward(uint256 _setKeepReward) external { _onlyGovernance(); } /// ===== Internal Core Implementations ===== /// @dev security check to avoid moving tokens that would cause a rugpull, edit based on strat function _onlyNotProtectedTokens(address _asset) internal override { address[] memory protectedTokens = getProtectedTokens(); for (uint256 x = 0; x < protectedTokens.length; x++) { require( address(protectedTokens[x]) != _asset, "Asset is protected" ); } } /// @dev invest the amount of want /// @notice When this function is called, the controller has already sent want to this /// @notice Just get the current balance and then invest accordingly function _deposit(uint256 _amount) internal override { // We receive bCVX -> Convert to CVX CVX_VAULT.withdraw(_amount); uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this)); // Lock tokens for 16 weeks, send credit to strat, always use max boost cause why not? LOCKER.lock(address(this), toDeposit, LOCKER.maximumBoostPayment()); } /// @dev utility function to convert all we can to bCVX /// @notice You may want to harvest before calling this to maximize the amount of bCVX you'll have function prepareWithdrawAll() external { _onlyGovernance(); LOCKER.processExpiredLocks(false); uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this)); if (toDeposit > 0) { CVX_VAULT.deposit(toDeposit); } } /// @dev utility function to withdraw everything for migration /// @dev NOTE: You cannot call this unless you have rebalanced to have only bCVX left in the vault function _withdrawAll() internal override { //NOTE: This probably will always fail unless we have all tokens expired require( LOCKER.lockedBalanceOf(address(this)) == 0 && LOCKER.balanceOf(address(this)) == 0, "You have to wait for unlock and have to manually rebalance out of it" ); // NO-OP because you can't deposit AND transfer with bCVX // See prepareWithdrawAll above } /// @dev withdraw the specified amount of want, liquidate from lpComponent to want, paying off any necessary debt for the conversion function _withdrawSome(uint256 _amount) internal override returns (uint256) { uint256 max = IERC20Upgradeable(want).balanceOf(address(this)); if (withdrawalSafetyCheck) { uint256 bCVXToCVX = CVX_VAULT.getPricePerFullShare(); // 18 decimals require(bCVXToCVX > 10**18, "Loss Of Peg"); // Avoid trying to redeem for less / loss of peg require( max >= _amount.mul(9_980).div(MAX_BPS), "Withdrawal Safety Check" ); // 20 BP of slippage } if (max < _amount) { return max; } return _amount; } /// @dev Harvest from strategy mechanics, realizing increase in underlying position function harvest() public whenNotPaused returns (uint256 harvested) { _onlyAuthorizedActors(); uint256 _before = IERC20Upgradeable(want).balanceOf(address(this)); uint256 _beforeCVX = IERC20Upgradeable(reward).balanceOf(address(this)); // Get cvxCRV LOCKER.getReward(address(this), false); // Rewards Math uint256 earnedReward = IERC20Upgradeable(reward).balanceOf(address(this)).sub(_beforeCVX); // Because we are using bCVX we take fees in reward //NOTE: This will probably revert because we deposit and transfer on same block (uint256 governancePerformanceFee, uint256 strategistPerformanceFee) = _processRewardsFees(earnedReward, reward); // Swap cvxCRV for want (bCVX) _swapcvxCRVToWant(); uint256 earned = IERC20Upgradeable(want).balanceOf(address(this)).sub(_before); /// @dev Harvest event that every strategy MUST have, see BaseStrategy emit Harvest(earned, block.number); /// @dev Harvest must return the amount of want increased return earned; } /// @dev Rebalance, Compound or Pay off debt here function tend() external whenNotPaused { _onlyAuthorizedActors(); revert(); // NOTE: For now tend is replaced by manualRebalance } /// @dev Swap from reward to CVX, then deposit into bCVX vault function _swapcvxCRVToWant() internal { uint256 cvxCRVToSwap = IERC20Upgradeable(reward).balanceOf(address(this)); if (cvxCRVToSwap == 0) { return; } // From cvxCRV to CRV CURVE_POOL.exchange( 1, // cvxCRV 0, // CRV cvxCRVToSwap, cvxCRVToSwap.mul(90).div(100) //10% slippage // cvxCRV -> CVX is 97.5% at time of writing ); // From CRV to CVX // TODO: SET UP CRV uint256 toSwap = IERC20Upgradeable(CRV).balanceOf(address(this)); // Sushi reward to WETH to want address[] memory path = new address[](3); path[0] = CRV; path[1] = WETH; path[2] = CVX; IUniswapRouterV2(SUSHI_ROUTER).swapExactTokensForTokens( toSwap, 0, path, address(this), now ); // Deposit into vault uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this)); if (toDeposit > 0) { CVX_VAULT.deposit(toDeposit); } } /// ===== Internal Helper Functions ===== /// @dev used to manage the governance and strategist fee, make sure to use it to get paid! function _processPerformanceFees(uint256 _amount) internal returns ( uint256 governancePerformanceFee, uint256 strategistPerformanceFee ) { governancePerformanceFee = _processFee( want, _amount, performanceFeeGovernance, IController(controller).rewards() ); strategistPerformanceFee = _processFee( want, _amount, performanceFeeStrategist, strategist ); } /// @dev used to manage the governance and strategist fee on earned rewards, make sure to use it to get paid! function _processRewardsFees(uint256 _amount, address _token) internal returns (uint256 governanceRewardsFee, uint256 strategistRewardsFee) { governanceRewardsFee = _processFee( _token, _amount, performanceFeeGovernance, IController(controller).rewards() ); strategistRewardsFee = _processFee( _token, _amount, performanceFeeStrategist, strategist ); } /// MANUAL FUNCTIONS /// /// @dev manual function to reinvest all CVX that was locked function reinvest() external whenNotPaused returns (uint256 reinvested) { _onlyGovernance(); if (processLocksOnReinvest) { // Withdraw all we can LOCKER.processExpiredLocks(false); } // Redeposit all into veCVX uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this)); // Redeposit into veCVX LOCKER.lock(address(this), toDeposit, LOCKER.maximumBoostPayment()); } /// @dev process all locks, to redeem function manualProcessExpiredLocks() external whenNotPaused { _onlyGovernance(); LOCKER.processExpiredLocks(false); // Unlock veCVX that is expired and redeem CVX back to this strat // Processed in the next harvest or during prepareMigrateAll } /// @dev Take all CVX and deposits in the CVX_VAULT function manualDepositCVXIntoVault() external whenNotPaused { _onlyGovernance(); uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this)); if (toDeposit > 0) { CVX_VAULT.deposit(toDeposit); } } /// @dev Send all available bCVX to the Vault /// @notice you can do this so you can earn again (re-lock), or just to add to the redemption pool function manualSendbCVXToVault() external whenNotPaused { _onlyGovernance(); uint256 bCvxAmount = IERC20Upgradeable(want).balanceOf(address(this)); _transferToVault(bCvxAmount); } /// @dev use the currently available CVX to either lock or add to bCVX /// @notice toLock = 0, lock nothing, deposit in bCVX as much as you can /// @notice toLock = 10_000, lock everything (CVX) you have function manualRebalance(uint256 toLock) external whenNotPaused { _onlyGovernance(); require(toLock <= MAX_BPS, "Max is 100%"); if (processLocksOnRebalance) { // manualRebalance will revert if you have no expired locks LOCKER.processExpiredLocks(false); } if (harvestOnRebalance) { harvest(); } // Token that is highly liquid uint256 balanceOfWant = IERC20Upgradeable(want).balanceOf(address(this)); // CVX uninvested we got from harvest and unlocks uint256 balanceOfCVX = IERC20Upgradeable(CVX).balanceOf(address(this)); // Locked CVX in the locker uint256 balanceInLock = LOCKER.balanceOf(address(this)); uint256 totalCVXBalance = balanceOfCVX.add(balanceInLock).add(wantToCVX(balanceOfWant)); //Ratios uint256 currentLockRatio = balanceInLock.mul(10**18).div(totalCVXBalance); // Amount we want to have in lock uint256 newLockRatio = totalCVXBalance.mul(toLock).div(MAX_BPS); // Amount we want to have in bCVX uint256 toWantRatio = totalCVXBalance.mul(MAX_BPS.sub(toLock)).div(MAX_BPS); // We can't unlock enough, just deposit rest into bCVX if (newLockRatio <= currentLockRatio) { // Deposit into vault uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this)); if (toDeposit > 0) { CVX_VAULT.deposit(toDeposit); } return; } // If we're continuing, then we are going to lock something (unless it's zero) uint256 cvxToLock = newLockRatio.sub(currentLockRatio); // NOTE: We only lock the CVX we have and not the bCVX // bCVX should be sent back to vault and then go through earn // We do this because bCVX has "blockLock" and we can't both deposit and withdraw on the same block uint256 maxCVX = IERC20Upgradeable(CVX).balanceOf(address(this)); if (cvxToLock > maxCVX) { // Just lock what we can LOCKER.lock(address(this), maxCVX, LOCKER.maximumBoostPayment()); } else { // Lock proper LOCKER.lock(address(this), cvxToLock, LOCKER.maximumBoostPayment()); } // If anything else is left, deposit into vault uint256 cvxLeft = IERC20Upgradeable(CVX).balanceOf(address(this)); if (cvxLeft > 0) { CVX_VAULT.deposit(cvxLeft); } // At the end of the rebalance, there won't be any balanceOfCVX as that token is not considered by our strat } }
===== Extra Functions ===== @dev Change Delegation to another address Set delegate is enough as it will clear previous delegate automatically
function manualSetDelegate(address delegate) public { _onlyGovernance(); SNAPSHOT.setDelegate(DELEGATED_SPACE, delegate); }
2,221,952
[ 1, 894, 33, 13592, 15486, 422, 12275, 225, 7576, 24117, 367, 358, 4042, 1758, 1000, 7152, 353, 7304, 487, 518, 903, 2424, 2416, 7152, 6635, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11297, 694, 9586, 12, 2867, 7152, 13, 1071, 288, 203, 3639, 389, 3700, 43, 1643, 82, 1359, 5621, 203, 3639, 14204, 31667, 18, 542, 9586, 12, 1639, 19384, 6344, 67, 6616, 16, 7152, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.26; // Bancor-Protocol import "./bancor-protocol/utility/ContractRegistry.sol"; // Step #1: Initial Setup //import "./bancor-protocol/utility/ContractRegistryClient.sol"; import "./bancor-protocol/token/SmartToken.sol"; // Step #2: Smart Relay Token Deployment import "./bancor-protocol/token/SmartTokenController.sol"; // Step #7: Converters Registry Listing import "./bancor-protocol/token/interfaces/ISmartToken.sol"; // Step #7: Converters Registry Listing import "./bancor-protocol/converter/BancorConverter.sol"; // Step #3: Converter Deployment import "./bancor-protocol/converter/BancorConverterFactory.sol"; // Step #5: Activation and Step #6: Multisig Ownership import "./bancor-protocol/converter/interfaces/IBancorConverter.sol"; import "./bancor-protocol/converter/interfaces/IBancorConverterFactory.sol"; import "./bancor-protocol/converter/BancorConverterRegistry.sol"; // Step #7: Converters Registry Listing import "./bancor-protocol/converter/BancorConverterRegistryData.sol"; //import "./bancor-protocol/token/ERC20Token.sol"; import './bancor-protocol/token/interfaces/IERC20Token.sol'; import './bancor-protocol/utility/Managed.sol'; import './bancor-protocol/converter/BancorFormula.sol'; // Storage import "./storage/BnStorage.sol"; import "./storage/BnConstants.sol"; contract NewBancorPool is BnStorage, BnConstants, Managed { ContractRegistry public contractRegistry; //ContractRegistryClient public contractRegistryClient; SmartToken public smartToken; BancorConverter public bancorConverter; BancorConverterFactory public bancorConverterFactory; BancorConverterRegistry public bancorConverterRegistry; BancorConverterRegistryData public bancorConverterRegistryData; BancorFormula public bancorFormula; IERC20Token public token; address contractRegistryAddr; address BNTtokenAddr; address ERC20tokenAddr; address cDAItokenAddr; // cToken from compound pool address smartTokenAddr; address bancorConverterAddr; address BANCOR_CONVERTER_REGISTRY_DATA; address BANCOR_FORMULA; // ContractAddress of BancorFormula.sol constructor( address _contractRegistry, //address _contractRegistryClient, address _BNTtokenAddr, address _ERC20tokenAddr, address _cDAItokenAddr, address _smartToken, address _bancorConverter, //address _bancorConverterFactory, address _bancorConverterRegistry, address _bancorConverterRegistryData, address _bancorFormula ) public { // Step #1: Initial Setup contractRegistry = ContractRegistry(_contractRegistry); //contractRegistryClient = ContractRegistryClient(_contractRegistryClient); contractRegistryAddr = _contractRegistry; BNTtokenAddr = _BNTtokenAddr; ERC20tokenAddr = _ERC20tokenAddr; cDAItokenAddr = _cDAItokenAddr; // cToken from compound pool smartTokenAddr = _smartToken; bancorConverterAddr = _bancorConverter; BANCOR_CONVERTER_REGISTRY_DATA = _bancorConverterRegistryData; BANCOR_FORMULA = _bancorFormula; token = IERC20Token(ERC20tokenAddr); // Step #2: Smart Relay Token Deployment smartToken = SmartToken(_smartToken); // Step #3: Converter Deployment bancorConverter = BancorConverter(_bancorConverter); // Step #5: Activation and Step #6: Multisig Ownership //bancorConverterFactory = BancorConverterFactory(_bancorConverterFactory); // Step #7: Converters Registry Listing bancorConverterRegistry = BancorConverterRegistry(_bancorConverterRegistry); } function testFunc() public returns (uint256 _hundredPercent) { return BnConstants.hundredPercent; } function testFuncCallBancorNetworkContractAddr() public view returns (address _bancorNetwork) { address bancorNetwork; bancorNetwork = contractRegistry.addressOf('BancorNetwork'); return bancorNetwork; } // function testFuncCallBancorConverterFactoryContractAddr() public view returns (IBancorConverterFactory) { // address bancorConverterFactory; // //IBancorConverterFactory bancorConverterFactory = IBancorConverterFactory(addressOf(BANCOR_CONVERTER_FACTORY)); // bancorConverterFactory = contractRegistry.addressOf('BancorConverterFactory'); // return bancorConverterFactory; // } function testFuncCallBancorConverterUpgraderContractAddr() public view returns (address _bancorConverterUpgrader) { address bancorConverterUpgrader; bancorConverterUpgrader = contractRegistry.addressOf('BancorConverterUpgrader'); return bancorConverterUpgrader; } function _addConverter() public { bancorConverterRegistry.addConverter(IBancorConverter(bancorConverterAddr)); } /*** * @notice - Integrate pools with lending protocols (e.g., lend pool tokens to Compound) to hedge risk for stakers * https://docs.bancor.network/user-guides/token-integration/how-to-create-a-bancor-liquidity-pool **/ function integratePoolWithLendingProtocol( bytes32 _contractName1, //string _contractName2, address receiverAddr, uint256 amountOfSmartToken ) public returns (bool) { // [In progress]: Integrate with lending pool of compound (cToken) // Step #1: Initial Setup address token1; //address token2; token1 = contractRegistry.addressOf(_contractName1); //token2 = contractRegistry.addressOf(_contractName2); // Step #2: Smart Relay Token Deployment smartToken.issue(msg.sender, amountOfSmartToken); smartToken.transfer(receiverAddr, amountOfSmartToken); // Step #3: Converter Deployment //uint index = 0; uint32 reserveRatio = 10; // The case of this, I specify 10% as percentage of ratio. (After I need to divide by 100) //uint32 _conversionFee = 1000; // Fee: 1,000 (0.1%) addConnector(IERC20Token(ERC20tokenAddr), reserveRatio, true); //bancorConverter.addConnector(IERC20Token(ERC20tokenAddr), reserveRatio, true); //bancorConverter.setConversionFee(_conversionFee); // Step #4: Funding & Initial Supply uint256 fundedAmount = 100; fund(fundedAmount); //bancorConverter.fund(fundedAmount); // Step #5: Activation // Step #6: Multisig Ownership address _converterAddress; // @notice - This variable is for receiving return value of createConverter() below uint32 _maxConversionFee = 1; // _converterAddress = bancorConverterFactory.createConverter(smartToken, // contractRegistry, // _maxConversionFee, // token, // reserveRatio); // Step #7: Converters Registry Listing bancorConverterRegistry.addConverter(IBancorConverter(_converterAddress)); } /*********************************************************** * @notice - Internal function from BancorConverter.sol ***********************************************************/ uint32 private constant RATIO_RESOLUTION = 1000000; uint64 private constant CONVERSION_FEE_RESOLUTION = 1000000; /** * @dev version number */ uint16 public version = 25; IWhitelist public conversionWhitelist; // whitelist contract with list of addresses that are allowed to use the converter IERC20Token[] public reserveTokens; // ERC20 standard token addresses (prior version 17, use 'connectorTokens' instead) struct Reserve { uint256 virtualBalance; // reserve virtual balance uint32 ratio; // reserve ratio, represented in ppm, 1-1000000 bool isVirtualBalanceEnabled; // true if virtual balance is enabled, false if not bool isSaleEnabled; // is sale of the reserve token enabled, can be set by the owner bool isSet; // used to tell if the mapping element is defined } mapping (address => Reserve) public reserves; // reserve token addresses -> reserve data (prior version 17, use 'connectors' instead) uint32 private totalReserveRatio = 0; // used to efficiently prevent increasing the total reserve ratio above 100% uint32 public maxConversionFee = 0; // maximum conversion fee for the lifetime of the contract, // represented in ppm, 0...1000000 (0 = no fee, 100 = 0.01%, 1000000 = 100%) uint32 public conversionFee = 0; // current conversion fee, represented in ppm, 0...maxConversionFee bool public conversionsEnabled = true; // deprecated, backward compatibility // event Conversion( // address indexed _fromToken, // address indexed _toToken, // address indexed _trader, // uint256 _amount, // uint256 _return, // int256 _conversionFee // ); event PriceDataUpdate( address indexed _connectorToken, uint256 _tokenSupply, uint256 _connectorBalance, uint32 _connectorWeight ); event SmartTokenAdded(address indexed _smartToken); event LiquidityPoolAdded(address indexed _liquidityPool); event ConvertibleTokenAdded(address indexed _convertibleToken, address indexed _smartToken); // validates reserve ratio modifier validReserveRatio(uint32 _ratio) { require(_ratio > 0 && _ratio <= RATIO_RESOLUTION); _; } // allows execution only on a multiple-reserve converter modifier multipleReservesOnly { require(reserveTokens.length > 1); _; } function addConnector(IERC20Token _token, uint32 _weight, bool /*_enableVirtualBalance*/) public { addReserve(_token, _weight); } function addReserve(IERC20Token _token, uint32 _ratio) public ownerOnly //inactive //validAddress(_token) //notThis(_token) validReserveRatio(_ratio) { //require(_token != token && !reserves[_token].isSet && totalReserveRatio + _ratio <= RATIO_RESOLUTION); // validate input reserves[_token].ratio = _ratio; reserves[_token].isVirtualBalanceEnabled = false; reserves[_token].virtualBalance = 0; reserves[_token].isSaleEnabled = true; reserves[_token].isSet = true; reserveTokens.push(_token); totalReserveRatio += _ratio; } /** * @dev updates the current conversion fee * can only be called by the manager * * @param _conversionFee new conversion fee, represented in ppm */ // event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee); // function setConversionFee(uint32 _conversionFee) // public // ownerOrManagerOnly // { // require(_conversionFee >= 0 && _conversionFee <= maxConversionFee); // emit ConversionFeeUpdate(conversionFee, _conversionFee); // conversionFee = _conversionFee; // } /** * @dev buys the token with all reserve tokens using the same percentage * for example, if the caller increases the supply by 10%, * then it will cost an amount equal to 10% of each reserve token balance * note that the function can be called only when conversions are enabled * * @param _amount amount to increase the supply by (in the smart token) */ function fund(uint256 _amount) public multipleReservesOnly { uint256 supply = smartToken.totalSupply(); IBancorFormula formula = IBancorFormula(BANCOR_FORMULA); // iterate through the reserve tokens and transfer a percentage equal to the ratio between _amount // and the total supply in each reserve from the caller to the converter IERC20Token reserveToken; uint256 reserveBalance; uint256 reserveAmount; for (uint16 i = 0; i < reserveTokens.length; i++) { reserveToken = reserveTokens[i]; reserveBalance = reserveToken.balanceOf(this); reserveAmount = formula.calculateFundCost(supply, reserveBalance, totalReserveRatio, _amount); Reserve storage reserve = reserves[reserveToken]; // transfer funds from the caller in the reserve token ensureTransferFrom(reserveToken, msg.sender, this, reserveAmount); // dispatch price data update for the smart token/reserve emit PriceDataUpdate(reserveToken, supply + _amount, reserveBalance + reserveAmount, reserve.ratio); } // issue new funds to the caller in the smart token smartToken.issue(msg.sender, _amount); } function ensureTransferFrom(IERC20Token _token, address _from, address _to, uint256 _amount) private { // We must assume that functions `transfer` and `transferFrom` do not return anything, // because not all tokens abide the requirement of the ERC20 standard to return success or failure. // This is because in the current compiler version, the calling contract can handle more returned data than expected but not less. // This may change in the future, so that the calling contract will revert if the size of the data is not exactly what it expects. uint256 prevBalance = _token.balanceOf(_to); if (_from == address(this)) INonStandardERC20(_token).transfer(_to, _amount); else INonStandardERC20(_token).transferFrom(_from, _to, _amount); uint256 postBalance = _token.balanceOf(_to); require(postBalance > prevBalance); } function addConverter() external { // validate input //require(isConverterValid(_converter)); BancorConverterRegistryData converterRegistryData = BancorConverterRegistryData(BANCOR_CONVERTER_REGISTRY_DATA); uint reserveTokenCount = connectorTokenCount(); // add the smart token addSmartToken(converterRegistryData, smartTokenAddr); if (reserveTokenCount > 1) addLiquidityPool(converterRegistryData, smartTokenAddr); else addConvertibleToken(converterRegistryData, smartTokenAddr, smartTokenAddr); // add all reserve tokens for (uint i = 0; i < reserveTokenCount; i++) addConvertibleToken(converterRegistryData, reserveTokens[i], token); } function connectorTokenCount() public view returns (uint16) { return reserveTokenCount(); } function reserveTokenCount() public view returns (uint16) { return uint16(reserveTokens.length); } function addSmartToken(IBancorConverterRegistryData _converterRegistryData, address _smartToken) internal { _converterRegistryData.addSmartToken(_smartToken); emit SmartTokenAdded(_smartToken); } function addLiquidityPool(IBancorConverterRegistryData _converterRegistryData, address _liquidityPool) internal { _converterRegistryData.addLiquidityPool(_liquidityPool); emit LiquidityPoolAdded(_liquidityPool); } function addConvertibleToken(IBancorConverterRegistryData _converterRegistryData, address _convertibleToken, address _smartToken) internal { _converterRegistryData.addConvertibleToken(_convertibleToken, _smartToken); emit ConvertibleTokenAdded(_convertibleToken, _smartToken); } }
inactivevalidAddress(_token)notThis(_token)require(_token != token && !reserves[_token].isSet && totalReserveRatio + _ratio <= RATIO_RESOLUTION); validate input
function addReserve(IERC20Token _token, uint32 _ratio) public ownerOnly validReserveRatio(_ratio) { reserves[_token].ratio = _ratio; reserves[_token].isVirtualBalanceEnabled = false; reserves[_token].virtualBalance = 0; reserves[_token].isSaleEnabled = true; reserves[_token].isSet = true; reserveTokens.push(_token); totalReserveRatio += _ratio; }
15,871,541
[ 1, 27366, 877, 1887, 24899, 2316, 13, 902, 2503, 24899, 2316, 13, 6528, 24899, 2316, 480, 1147, 597, 401, 455, 264, 3324, 63, 67, 2316, 8009, 291, 694, 597, 2078, 607, 6527, 8541, 397, 389, 9847, 1648, 534, 789, 4294, 67, 17978, 13269, 1769, 225, 1954, 810, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 527, 607, 6527, 12, 45, 654, 39, 3462, 1345, 389, 2316, 16, 2254, 1578, 389, 9847, 13, 203, 3639, 1071, 203, 3639, 3410, 3386, 203, 3639, 923, 607, 6527, 8541, 24899, 9847, 13, 203, 565, 288, 203, 203, 3639, 400, 264, 3324, 63, 67, 2316, 8009, 9847, 273, 389, 9847, 31, 203, 3639, 400, 264, 3324, 63, 67, 2316, 8009, 291, 6466, 13937, 1526, 273, 629, 31, 203, 3639, 400, 264, 3324, 63, 67, 2316, 8009, 12384, 13937, 273, 374, 31, 203, 3639, 400, 264, 3324, 63, 67, 2316, 8009, 291, 30746, 1526, 273, 638, 31, 203, 3639, 400, 264, 3324, 63, 67, 2316, 8009, 291, 694, 273, 638, 31, 203, 3639, 20501, 5157, 18, 6206, 24899, 2316, 1769, 203, 3639, 2078, 607, 6527, 8541, 1011, 389, 9847, 31, 203, 565, 289, 377, 203, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-05-17 */ // Sources flattened with hardhat v2.3.0 https://hardhat.org // File contracts/OpenZeppelin/utils/ReentrancyGuard.sol pragma solidity 0.6.12; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File contracts/OpenZeppelin/utils/EnumerableSet.sol pragma solidity 0.6.12; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File contracts/OpenZeppelin/utils/Address.sol pragma solidity 0.6.12; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File contracts/OpenZeppelin/utils/Context.sol pragma solidity 0.6.12; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File contracts/OpenZeppelin/access/AccessControl.sol pragma solidity 0.6.12; /** * @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()); } } } // File contracts/Access/MISOAdminAccess.sol pragma solidity 0.6.12; contract MISOAdminAccess is AccessControl { /// @dev Whether access is initialised. bool private initAccess; /// @notice Events for adding and removing various roles. event AdminRoleGranted( address indexed beneficiary, address indexed caller ); event AdminRoleRemoved( address indexed beneficiary, address indexed caller ); /// @notice The deployer is automatically given the admin role which will allow them to then grant roles to other addresses. constructor() public { } /** * @notice Initializes access controls. * @param _admin Admins address. */ function initAccessControls(address _admin) public { require(!initAccess, "Already initialised"); _setupRole(DEFAULT_ADMIN_ROLE, _admin); initAccess = true; } ///////////// // Lookups // ///////////// /** * @notice Used to check whether an address has the admin role. * @param _address EOA or contract being checked. * @return bool True if the account has the role or false if it does not. */ function hasAdminRole(address _address) public view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _address); } /////////////// // Modifiers // /////////////// /** * @notice Grants the admin role to an address. * @dev The sender must have the admin role. * @param _address EOA or contract receiving the new role. */ function addAdminRole(address _address) external { grantRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleGranted(_address, _msgSender()); } /** * @notice Removes the admin role from an address. * @dev The sender must have the admin role. * @param _address EOA or contract affected. */ function removeAdminRole(address _address) external { revokeRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleRemoved(_address, _msgSender()); } } // File contracts/Access/MISOAccessControls.sol pragma solidity 0.6.12; /** * @notice Access Controls * @author Attr: BlockRocket.tech */ contract MISOAccessControls is MISOAdminAccess { /// @notice Role definitions bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant SMART_CONTRACT_ROLE = keccak256("SMART_CONTRACT_ROLE"); bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); /// @notice Events for adding and removing various roles event MinterRoleGranted( address indexed beneficiary, address indexed caller ); event MinterRoleRemoved( address indexed beneficiary, address indexed caller ); event OperatorRoleGranted( address indexed beneficiary, address indexed caller ); event OperatorRoleRemoved( address indexed beneficiary, address indexed caller ); event SmartContractRoleGranted( address indexed beneficiary, address indexed caller ); event SmartContractRoleRemoved( address indexed beneficiary, address indexed caller ); /** * @notice The deployer is automatically given the admin role which will allow them to then grant roles to other addresses */ constructor() public { } ///////////// // Lookups // ///////////// /** * @notice Used to check whether an address has the minter role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasMinterRole(address _address) public view returns (bool) { return hasRole(MINTER_ROLE, _address); } /** * @notice Used to check whether an address has the smart contract role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasSmartContractRole(address _address) public view returns (bool) { return hasRole(SMART_CONTRACT_ROLE, _address); } /** * @notice Used to check whether an address has the operator role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasOperatorRole(address _address) public view returns (bool) { return hasRole(OPERATOR_ROLE, _address); } /////////////// // Modifiers // /////////////// /** * @notice Grants the minter role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addMinterRole(address _address) external { grantRole(MINTER_ROLE, _address); emit MinterRoleGranted(_address, _msgSender()); } /** * @notice Removes the minter role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeMinterRole(address _address) external { revokeRole(MINTER_ROLE, _address); emit MinterRoleRemoved(_address, _msgSender()); } /** * @notice Grants the smart contract role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addSmartContractRole(address _address) external { grantRole(SMART_CONTRACT_ROLE, _address); emit SmartContractRoleGranted(_address, _msgSender()); } /** * @notice Removes the smart contract role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeSmartContractRole(address _address) external { revokeRole(SMART_CONTRACT_ROLE, _address); emit SmartContractRoleRemoved(_address, _msgSender()); } /** * @notice Grants the operator role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addOperatorRole(address _address) external { grantRole(OPERATOR_ROLE, _address); emit OperatorRoleGranted(_address, _msgSender()); } /** * @notice Removes the operator role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeOperatorRole(address _address) external { revokeRole(OPERATOR_ROLE, _address); emit OperatorRoleRemoved(_address, _msgSender()); } } // File contracts/Utils/SafeTransfer.sol pragma solidity 0.6.12; contract SafeTransfer { address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @dev Helper function to handle both ETH and ERC20 payments function _safeTokenPayment( address _token, address payable _to, uint256 _amount ) internal { if (address(_token) == ETH_ADDRESS) { _safeTransferETH(_to,_amount ); } else { _safeTransfer(_token, _to, _amount); } } /// @dev Helper function to handle both ETH and ERC20 payments function _tokenPayment( address _token, address payable _to, uint256 _amount ) internal { if (address(_token) == ETH_ADDRESS) { _to.transfer(_amount); } else { _safeTransfer(_token, _to, _amount); } } /// @dev Transfer helper from UniswapV2 Router function _safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } /** * There are many non-compliant ERC20 tokens... this can handle most, adapted from UniSwap V2 * Im trying to make it a habit to put external calls last (reentrancy) * You can put this in an internal function if you like. */ function _safeTransfer( address token, address to, uint256 amount ) internal virtual { // solium-disable-next-line security/no-low-level-calls (bool success, bytes memory data) = token.call( // 0xa9059cbb = bytes4(keccak256("transfer(address,uint256)")) abi.encodeWithSelector(0xa9059cbb, to, amount) ); require(success && (data.length == 0 || abi.decode(data, (bool)))); // ERC20 Transfer failed } function _safeTransferFrom( address token, address from, uint256 amount ) internal virtual { // solium-disable-next-line security/no-low-level-calls (bool success, bytes memory data) = token.call( // 0x23b872dd = bytes4(keccak256("transferFrom(address,address,uint256)")) abi.encodeWithSelector(0x23b872dd, from, address(this), amount) ); require(success && (data.length == 0 || abi.decode(data, (bool)))); // ERC20 TransferFrom failed } function _safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function _safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File contracts/interfaces/IERC20.sol pragma solidity 0.6.12; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // File contracts/Utils/BoringERC20.sol pragma solidity 0.6.12; // solhint-disable avoid-low-level-calls library BoringERC20 { bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol() bytes4 private constant SIG_NAME = 0x06fdde03; // name() bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals() bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256) bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256) /// @notice Provides a safe ERC20.symbol version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token symbol. function safeSymbol(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_SYMBOL)); return success && data.length > 0 ? abi.decode(data, (string)) : "???"; } /// @notice Provides a safe ERC20.name version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token name. function safeName(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_NAME)); return success && data.length > 0 ? abi.decode(data, (string)) : "???"; } /// @notice Provides a safe ERC20.decimals version which returns '18' as fallback value. /// @param token The address of the ERC-20 token contract. /// @return (uint8) Token decimals. function safeDecimals(IERC20 token) internal view returns (uint8) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_DECIMALS)); return success && data.length == 32 ? abi.decode(data, (uint8)) : 18; } /// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransfer( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Transfer failed"); } /// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param from Transfer tokens from. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransferFrom( IERC20 token, address from, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: TransferFrom failed"); } } // File contracts/Utils/BoringBatchable.sol pragma solidity 0.6.12; // solhint-disable avoid-low-level-calls // solhint-disable no-inline-assembly // Audit on 5-Jan-2021 by Keno and BoringCrypto contract BaseBoringBatchable { /// @dev Helper function to extract a useful revert message from a failed call. /// If the returned data is malformed or not correctly abi encoded then this call can fail itself. function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } /// @notice Allows batched call to self (this contract). /// @param calls An array of inputs for each call. /// @param revertOnFail If True then reverts after a failed call and stops doing further calls. /// @return successes An array indicating the success of a call, mapped one-to-one to `calls`. /// @return results An array with the returned data of each function call, mapped one-to-one to `calls`. // F1: External is ok here because this is the batch function, adding it to a batch makes no sense // F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value // C3: The length of the loop is fully under user control, so can't be exploited // C7: Delegatecall is only used on the same contract, so it's safe function batch(bytes[] calldata calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results) { successes = new bool[](calls.length); results = new bytes[](calls.length); for (uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(calls[i]); require(success || !revertOnFail, _getRevertMsg(result)); successes[i] = success; results[i] = result; } } } contract BoringBatchable is BaseBoringBatchable { /// @notice Call wrapper that performs `ERC20.permit` on `token`. /// Lookup `IERC20.permit`. // F6: Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert) // if part of a batch this could be used to grief once as the second call would not need the permit function permitToken( IERC20 token, address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { token.permit(from, to, amount, deadline, v, r, s); } } // File contracts/Utils/BoringMath.sol pragma solidity 0.6.12; /// @notice A library for performing overflow-/underflow-safe math, /// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math). library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b > 0, "BoringMath: Div zero"); c = a / b; } function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "BoringMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= uint64(-1), "BoringMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= uint32(-1), "BoringMath: uint32 Overflow"); c = uint32(a); } function to16(uint256 a) internal pure returns (uint16 c) { require(a <= uint16(-1), "BoringMath: uint16 Overflow"); c = uint16(a); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128. library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64. library BoringMath64 { function add(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32. library BoringMath32 { function add(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32. library BoringMath16 { function add(uint16 a, uint16 b) internal pure returns (uint16 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint16 a, uint16 b) internal pure returns (uint16 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } // File contracts/Utils/Documents.sol pragma solidity 0.6.12; /** * @title Standard implementation of ERC1643 Document management */ contract Documents { struct Document { uint32 docIndex; // Store the document name indexes uint64 lastModified; // Timestamp at which document details was last modified string data; // data of the document that exist off-chain } // mapping to store the documents details in the document mapping(string => Document) internal _documents; // mapping to store the document name indexes mapping(string => uint32) internal _docIndexes; // Array use to store all the document name present in the contracts string[] _docNames; // Document Events event DocumentRemoved(string indexed _name, string _data); event DocumentUpdated(string indexed _name, string _data); /** * @notice Used to attach a new document to the contract, or update the data or hash of an existing attached document * @dev Can only be executed by the owner of the contract. * @param _name Name of the document. It should be unique always * @param _data Off-chain data of the document from where it is accessible to investors/advisors to read. */ function _setDocument(string calldata _name, string calldata _data) internal { require(bytes(_name).length > 0, "Zero name is not allowed"); require(bytes(_data).length > 0, "Should not be a empty data"); // Document storage document = _documents[_name]; if (_documents[_name].lastModified == uint64(0)) { _docNames.push(_name); _documents[_name].docIndex = uint32(_docNames.length); } _documents[_name] = Document(_documents[_name].docIndex, uint64(now), _data); emit DocumentUpdated(_name, _data); } /** * @notice Used to remove an existing document from the contract by giving the name of the document. * @dev Can only be executed by the owner of the contract. * @param _name Name of the document. It should be unique always */ function _removeDocument(string calldata _name) internal { require(_documents[_name].lastModified != uint64(0), "Document should exist"); uint32 index = _documents[_name].docIndex - 1; if (index != _docNames.length - 1) { _docNames[index] = _docNames[_docNames.length - 1]; _documents[_docNames[index]].docIndex = index + 1; } _docNames.pop(); emit DocumentRemoved(_name, _documents[_name].data); delete _documents[_name]; } /** * @notice Used to return the details of a document with a known name (`string`). * @param _name Name of the document * @return string The data associated with the document. * @return uint256 the timestamp at which the document was last modified. */ function getDocument(string calldata _name) external view returns (string memory, uint256) { return ( _documents[_name].data, uint256(_documents[_name].lastModified) ); } /** * @notice Used to retrieve a full list of documents attached to the smart contract. * @return string List of all documents names present in the contract. */ function getAllDocuments() external view returns (string[] memory) { return _docNames; } /** * @notice Used to retrieve the total documents in the smart contract. * @return uint256 Count of the document names present in the contract. */ function getDocumentCount() external view returns (uint256) { return _docNames.length; } /** * @notice Used to retrieve the document name from index in the smart contract. * @return string Name of the document name. */ function getDocumentName(uint256 _index) external view returns (string memory) { require(_index < _docNames.length, "Index out of bounds"); return _docNames[_index]; } } // File contracts/interfaces/IPointList.sol pragma solidity 0.6.12; // ---------------------------------------------------------------------------- // White List interface // ---------------------------------------------------------------------------- interface IPointList { function isInList(address account) external view returns (bool); function hasPoints(address account, uint256 amount) external view returns (bool); function setPoints( address[] memory accounts, uint256[] memory amounts ) external; function initPointList(address accessControl) external ; } // File contracts/interfaces/IMisoMarket.sol pragma solidity 0.6.12; interface IMisoMarket { function init(bytes calldata data) external payable; function initMarket( bytes calldata data ) external; function marketTemplate() external view returns (uint256); } // File contracts/Auctions/DutchAuction.sol pragma solidity 0.6.12; pragma experimental ABIEncoderV2; //---------------------------------------------------------------------------------- // I n s t a n t // // .:mmm. .:mmm:. .ii. .:SSSSSSSSSSSSS. .oOOOOOOOOOOOo. // .mMM'':Mm. .:MM'':Mm:. .II: :SSs.......... .oOO'''''''''''OOo. // .:Mm' ':Mm. .:Mm' 'MM:. .II: 'sSSSSSSSSSSSSS:. :OO. .OO: // .'mMm' ':MM:.:MMm' ':MM:. .II: .:...........:SS. 'OOo:.........:oOO' // 'mMm' ':MMmm' 'mMm: II: 'sSSSSSSSSSSSSS' 'oOOOOOOOOOOOO' // //---------------------------------------------------------------------------------- // // Chef Gonpachi's Dutch Auction // // A declining price auction with fair price discovery. // // Inspired by DutchSwap's Dutch Auctions // https://github.com/deepyr/DutchSwap // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // Made for Sushi.com // // Enjoy. (c) Chef Gonpachi, Kusatoshi, SSMikazu 2021 // <https://github.com/chefgonpachi/MISO/> // // --------------------------------------------------------------------- // SPDX-License-Identifier: GPL-3.0 // --------------------------------------------------------------------- /// @notice Attribution to delta.financial /// @notice Attribution to dutchswap.com contract DutchAuction is IMisoMarket, MISOAccessControls, BoringBatchable, SafeTransfer, Documents , ReentrancyGuard { using BoringMath for uint256; using BoringMath128 for uint128; using BoringMath64 for uint64; using BoringERC20 for IERC20; /// @notice MISOMarket template id for the factory contract. /// @dev For different marketplace types, this must be incremented. uint256 public constant override marketTemplate = 2; /// @dev The placeholder ETH address. address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Main market variables. struct MarketInfo { uint64 startTime; uint64 endTime; uint128 totalTokens; } MarketInfo public marketInfo; /// @notice Market price variables. struct MarketPrice { uint128 startPrice; uint128 minimumPrice; } MarketPrice public marketPrice; /// @notice Market dynamic variables. struct MarketStatus { uint128 commitmentsTotal; bool finalized; bool usePointList; } MarketStatus public marketStatus; /// @notice The token being sold. address public auctionToken; /// @notice The currency the auction accepts for payment. Can be ETH or token address. address public paymentCurrency; /// @notice Where the auction funds will get paid. address payable public wallet; /// @notice Address that manages auction approvals. address public pointList; /// @notice The commited amount of accounts. mapping(address => uint256) public commitments; /// @notice Amount of tokens to claim per address. mapping(address => uint256) public claimed; /// @notice Event for updating auction times. Needs to be before auction starts. event AuctionTimeUpdated(uint256 startTime, uint256 endTime); /// @notice Event for updating auction prices. Needs to be before auction starts. event AuctionPriceUpdated(uint256 startPrice, uint256 minimumPrice); /// @notice Event for updating auction wallet. Needs to be before auction starts. event AuctionWalletUpdated(address wallet); /// @notice Event for adding a commitment. event AddedCommitment(address addr, uint256 commitment); /// @notice Event for finalization of the auction. event AuctionFinalized(); /// @notice Event for cancellation of the auction. event AuctionCancelled(); /** * @notice Initializes main contract variables and transfers funds for the auction. * @dev Init function. * @param _funder The address that funds the token for crowdsale. * @param _token Address of the token being sold. * @param _totalTokens The total number of tokens to sell in auction. * @param _startTime Auction start time. * @param _endTime Auction end time. * @param _paymentCurrency The currency the crowdsale accepts for payment. Can be ETH or token address. * @param _startPrice Starting price of the auction. * @param _minimumPrice The minimum auction price. * @param _admin Address that can finalize auction. * @param _pointList Address that will manage auction approvals. * @param _wallet Address where collected funds will be forwarded to. */ function initAuction( address _funder, address _token, uint256 _totalTokens, uint256 _startTime, uint256 _endTime, address _paymentCurrency, uint256 _startPrice, uint256 _minimumPrice, address _admin, address _pointList, address payable _wallet ) public { require(_startTime < 10000000000, "DutchAuction: enter an unix timestamp in seconds, not miliseconds"); require(_endTime < 10000000000, "DutchAuction: enter an unix timestamp in seconds, not miliseconds"); require(_startTime >= block.timestamp, "DutchAuction: start time is before current time"); require(_endTime > _startTime, "DutchAuction: end time must be older than start price"); require(_totalTokens > 0,"DutchAuction: total tokens must be greater than zero"); require(_startPrice > _minimumPrice, "DutchAuction: start price must be higher than minimum price"); require(_minimumPrice > 0, "DutchAuction: minimum price must be greater than 0"); require(_admin != address(0), "DutchAuction: admin is the zero address"); require(_wallet != address(0), "DutchAuction: wallet is the zero address"); require(IERC20(_token).decimals() == 18, "DutchAuction: Token does not have 18 decimals"); if (_paymentCurrency != ETH_ADDRESS) { require(IERC20(_paymentCurrency).decimals() > 0, "DutchAuction: Payment currency is not ERC20"); } marketInfo.startTime = BoringMath.to64(_startTime); marketInfo.endTime = BoringMath.to64(_endTime); marketInfo.totalTokens = BoringMath.to128(_totalTokens); marketPrice.startPrice = BoringMath.to128(_startPrice); marketPrice.minimumPrice = BoringMath.to128(_minimumPrice); auctionToken = _token; paymentCurrency = _paymentCurrency; wallet = _wallet; initAccessControls(_admin); _setList(_pointList); _safeTransferFrom(_token, _funder, _totalTokens); } /** Dutch Auction Price Function ============================ Start Price ----- \ \ \ \ ------------ Clearing Price / \ = AmountRaised/TokenSupply Token Price -- \ / \ -- ----------- Minimum Price Amount raised / End Time */ /** * @notice Calculates the average price of each token from all commitments. * @return Average token price. */ function tokenPrice() public view returns (uint256) { return uint256(marketStatus.commitmentsTotal).mul(1e18).div(uint256(marketInfo.totalTokens)); } /** * @notice Returns auction price in any time. * @return Fixed start price or minimum price if outside of auction time, otherwise calculated current price. */ function priceFunction() public view returns (uint256) { /// @dev Return Auction Price if (block.timestamp <= uint256(marketInfo.startTime)) { return uint256(marketPrice.startPrice); } if (block.timestamp >= uint256(marketInfo.endTime)) { return uint256(marketPrice.minimumPrice); } return _currentPrice(); } /** * @notice The current clearing price of the Dutch auction. * @return The bigger from tokenPrice and priceFunction. */ function clearingPrice() public view returns (uint256) { /// @dev If auction successful, return tokenPrice if (tokenPrice() > priceFunction()) { return tokenPrice(); } return priceFunction(); } ///-------------------------------------------------------- /// Commit to buying tokens! ///-------------------------------------------------------- receive() external payable { revertBecauseUserDidNotProvideAgreement(); } /** * @dev Attribution to the awesome delta.financial contracts */ function marketParticipationAgreement() public pure returns (string memory) { return "I understand that I'm interacting with a smart contract. I understand that tokens commited are subject to the token issuer and local laws where applicable. I reviewed code of the smart contract and understand it fully. I agree to not hold developers or other people associated with the project liable for any losses or misunderstandings"; } /** * @dev Not using modifiers is a purposeful choice for code readability. */ function revertBecauseUserDidNotProvideAgreement() internal pure { revert("No agreement provided, please review the smart contract before interacting with it"); } /** * @notice Checks the amount of ETH to commit and adds the commitment. Refunds the buyer if commit is too high. * @param _beneficiary Auction participant ETH address. */ function commitEth( address payable _beneficiary, bool readAndAgreedToMarketParticipationAgreement ) public payable { require(paymentCurrency == ETH_ADDRESS, "DutchAuction: payment currency is not ETH address"); if(readAndAgreedToMarketParticipationAgreement == false) { revertBecauseUserDidNotProvideAgreement(); } // Get ETH able to be committed uint256 ethToTransfer = calculateCommitment(msg.value); /// @notice Accept ETH Payments. uint256 ethToRefund = msg.value.sub(ethToTransfer); if (ethToTransfer > 0) { _addCommitment(_beneficiary, ethToTransfer); } /// @notice Return any ETH to be refunded. if (ethToRefund > 0) { _beneficiary.transfer(ethToRefund); } } /** * @notice Buy Tokens by commiting approved ERC20 tokens to this contract address. * @param _amount Amount of tokens to commit. */ function commitTokens(uint256 _amount, bool readAndAgreedToMarketParticipationAgreement) public { commitTokensFrom(msg.sender, _amount, readAndAgreedToMarketParticipationAgreement); } /** * @notice Checks how much is user able to commit and processes that commitment. * @dev Users must approve contract prior to committing tokens to auction. * @param _from User ERC20 address. * @param _amount Amount of approved ERC20 tokens. */ function commitTokensFrom( address _from, uint256 _amount, bool readAndAgreedToMarketParticipationAgreement ) public nonReentrant { require(address(paymentCurrency) != ETH_ADDRESS, "DutchAuction: Payment currency is not a token"); if(readAndAgreedToMarketParticipationAgreement == false) { revertBecauseUserDidNotProvideAgreement(); } uint256 tokensToTransfer = calculateCommitment(_amount); if (tokensToTransfer > 0) { _safeTransferFrom(paymentCurrency, msg.sender, tokensToTransfer); _addCommitment(_from, tokensToTransfer); } } /** * @notice Calculates the pricedrop factor. * @return Value calculated from auction start and end price difference divided the auction duration. */ function priceDrop() public view returns (uint256) { MarketInfo memory _marketInfo = marketInfo; MarketPrice memory _marketPrice = marketPrice; uint256 numerator = uint256(_marketPrice.startPrice.sub(_marketPrice.minimumPrice)); uint256 denominator = uint256(_marketInfo.endTime.sub(_marketInfo.startTime)); return numerator / denominator; } /** * @notice How many tokens the user is able to claim. * @param _user Auction participant address. * @return User commitments reduced by already claimed tokens. */ function tokensClaimable(address _user) public view returns (uint256) { uint256 tokensAvailable = commitments[_user].mul(1e18).div(clearingPrice()); return tokensAvailable.sub(claimed[_user]); } /** * @notice Calculates total amount of tokens committed at current auction price. * @return Number of tokens commited. */ function totalTokensCommitted() public view returns (uint256) { return uint256(marketStatus.commitmentsTotal).mul(1e18).div(clearingPrice()); } /** * @notice Calculates the amout able to be committed during an auction. * @param _commitment Commitment user would like to make. * @return committed Amount allowed to commit. */ function calculateCommitment(uint256 _commitment) public view returns (uint256 committed) { uint256 maxCommitment = uint256(marketInfo.totalTokens).mul(clearingPrice()).div(1e18); if (uint256(marketStatus.commitmentsTotal).add(_commitment) > maxCommitment) { return maxCommitment.sub(uint256(marketStatus.commitmentsTotal)); } return _commitment; } /** * @notice Checks if the auction is open. * @return True if current time is greater than startTime and less than endTime. */ function isOpen() public view returns (bool) { return block.timestamp >= uint256(marketInfo.startTime) && block.timestamp <= uint256(marketInfo.endTime); } /** * @notice Successful if tokens sold equals totalTokens. * @return True if tokenPrice is bigger or equal clearingPrice. */ function auctionSuccessful() public view returns (bool) { return tokenPrice() >= clearingPrice(); } /** * @notice Checks if the auction has ended. * @return True if auction is successful or time has ended. */ function auctionEnded() public view returns (bool) { return auctionSuccessful() || block.timestamp > uint256(marketInfo.endTime); } /** * @return Returns true if market has been finalized */ function finalized() public view returns (bool) { return marketStatus.finalized; } /** * @return Returns true if 14 days have passed since the end of the auction */ function finalizeTimeExpired() public view returns (bool) { return uint256(marketInfo.endTime) + 7 days < block.timestamp; } /** * @notice Calculates price during the auction. * @return Current auction price. */ function _currentPrice() private view returns (uint256) { uint256 priceDiff = block.timestamp.sub(uint256(marketInfo.startTime)).mul(priceDrop()); return uint256(marketPrice.startPrice).sub(priceDiff); } /** * @notice Updates commitment for this address and total commitment of the auction. * @param _addr Bidders address. * @param _commitment The amount to commit. */ function _addCommitment(address _addr, uint256 _commitment) internal { require(block.timestamp >= uint256(marketInfo.startTime) && block.timestamp <= uint256(marketInfo.endTime), "DutchAuction: outside auction hours"); MarketStatus storage status = marketStatus; uint256 newCommitment = commitments[_addr].add(_commitment); if (status.usePointList) { require(IPointList(pointList).hasPoints(_addr, newCommitment)); } commitments[_addr] = newCommitment; status.commitmentsTotal = BoringMath.to128(uint256(status.commitmentsTotal).add(_commitment)); emit AddedCommitment(_addr, _commitment); } //-------------------------------------------------------- // Finalize Auction //-------------------------------------------------------- /** * @notice Cancel Auction * @dev Admin can cancel the auction before it starts */ function cancelAuction() public nonReentrant { require(hasAdminRole(msg.sender)); MarketStatus storage status = marketStatus; require(!status.finalized, "DutchAuction: auction already finalized"); require( uint256(status.commitmentsTotal) == 0, "DutchAuction: auction already committed" ); _safeTokenPayment(auctionToken, wallet, uint256(marketInfo.totalTokens)); status.finalized = true; emit AuctionCancelled(); } /** * @notice Auction finishes successfully above the reserve. * @dev Transfer contract funds to initialized wallet. */ function finalize() public nonReentrant { require(hasAdminRole(msg.sender) || hasSmartContractRole(msg.sender) || wallet == msg.sender || finalizeTimeExpired(), "DutchAuction: sender must be an admin"); MarketStatus storage status = marketStatus; require(!status.finalized, "DutchAuction: auction already finalized"); if (auctionSuccessful()) { /// @dev Successful auction /// @dev Transfer contributed tokens to wallet. _safeTokenPayment(paymentCurrency, wallet, uint256(status.commitmentsTotal)); } else { /// @dev Failed auction /// @dev Return auction tokens back to wallet. require(block.timestamp > uint256(marketInfo.endTime), "DutchAuction: auction has not finished yet"); _safeTokenPayment(auctionToken, wallet, uint256(marketInfo.totalTokens)); } status.finalized = true; emit AuctionFinalized(); } /// @notice Withdraws bought tokens, or returns commitment if the sale is unsuccessful. function withdrawTokens() public { withdrawTokens(msg.sender); } /** * @notice Withdraws bought tokens, or returns commitment if the sale is unsuccessful. * @dev Withdraw tokens only after auction ends. * @param beneficiary Whose tokens will be withdrawn. */ function withdrawTokens(address payable beneficiary) public nonReentrant { if (auctionSuccessful()) { require(marketStatus.finalized, "DutchAuction: not finalized"); /// @dev Successful auction! Transfer claimed tokens. uint256 tokensToClaim = tokensClaimable(beneficiary); require(tokensToClaim > 0, "DutchAuction: No tokens to claim"); claimed[beneficiary] = claimed[beneficiary].add(tokensToClaim); _safeTokenPayment(auctionToken, beneficiary, tokensToClaim); } else { /// @dev Auction did not meet reserve price. /// @dev Return committed funds back to user. require(block.timestamp > uint256(marketInfo.endTime), "DutchAuction: auction has not finished yet"); uint256 fundsCommitted = commitments[beneficiary]; commitments[beneficiary] = 0; // Stop multiple withdrawals and free some gas _safeTokenPayment(paymentCurrency, beneficiary, fundsCommitted); } } //-------------------------------------------------------- // Documents //-------------------------------------------------------- function setDocument(string calldata _name, string calldata _data) external { require(hasAdminRole(msg.sender) ); _setDocument( _name, _data); } function setDocuments(string[] calldata _name, string[] calldata _data) external { require(hasAdminRole(msg.sender) ); uint256 numDocs = _name.length; for (uint256 i = 0; i < numDocs; i++) { _setDocument( _name[i], _data[i]); } } function removeDocument(string calldata _name) external { require(hasAdminRole(msg.sender)); _removeDocument(_name); } //-------------------------------------------------------- // Point Lists //-------------------------------------------------------- function setList(address _list) external { require(hasAdminRole(msg.sender)); _setList(_list); } function enableList(bool _status) external { require(hasAdminRole(msg.sender)); marketStatus.usePointList = _status; } function _setList(address _pointList) private { if (_pointList != address(0)) { pointList = _pointList; marketStatus.usePointList = true; } } //-------------------------------------------------------- // Setter Functions //-------------------------------------------------------- /** * @notice Admin can set start and end time through this function. * @param _startTime Auction start time. * @param _endTime Auction end time. */ function setAuctionTime(uint256 _startTime, uint256 _endTime) external { require(hasAdminRole(msg.sender)); require(_startTime < 10000000000, "DutchAuction: enter an unix timestamp in seconds, not miliseconds"); require(_endTime < 10000000000, "DutchAuction: enter an unix timestamp in seconds, not miliseconds"); require(_startTime >= block.timestamp, "DutchAuction: start time is before current time"); require(_endTime > _startTime, "DutchAuction: end time must be older than start time"); require(marketStatus.commitmentsTotal == 0, "DutchAuction: auction cannot have already started"); marketInfo.startTime = BoringMath.to64(_startTime); marketInfo.endTime = BoringMath.to64(_endTime); emit AuctionTimeUpdated(_startTime,_endTime); } /** * @notice Admin can set start and min price through this function. * @param _startPrice Auction start price. * @param _minimumPrice Auction minimum price. */ function setAuctionPrice(uint256 _startPrice, uint256 _minimumPrice) external { require(hasAdminRole(msg.sender)); require(_startPrice > _minimumPrice, "DutchAuction: start price must be higher than minimum price"); require(_minimumPrice > 0, "DutchAuction: minimum price must be greater than 0"); require(marketStatus.commitmentsTotal == 0, "DutchAuction: auction cannot have already started"); marketPrice.startPrice = BoringMath.to128(_startPrice); marketPrice.minimumPrice = BoringMath.to128(_minimumPrice); emit AuctionPriceUpdated(_startPrice,_minimumPrice); } /** * @notice Admin can set the auction wallet through this function. * @param _wallet Auction wallet is where funds will be sent. */ function setAuctionWallet(address payable _wallet) external { require(hasAdminRole(msg.sender)); require(_wallet != address(0), "DutchAuction: wallet is the zero address"); wallet = _wallet; emit AuctionWalletUpdated(_wallet); } //-------------------------------------------------------- // Market Launchers //-------------------------------------------------------- /** * @notice Decodes and hands auction data to the initAuction function. * @param _data Encoded data for initialization. */ function init(bytes calldata _data) external override payable { } function initMarket( bytes calldata _data ) public override { ( address _funder, address _token, uint256 _totalTokens, uint256 _startTime, uint256 _endTime, address _paymentCurrency, uint256 _startPrice, uint256 _minimumPrice, address _admin, address _pointList, address payable _wallet ) = abi.decode(_data, ( address, address, uint256, uint256, uint256, address, uint256, uint256, address, address, address )); initAuction(_funder, _token, _totalTokens, _startTime, _endTime, _paymentCurrency, _startPrice, _minimumPrice, _admin, _pointList, _wallet); } /** * @notice Collects data to initialize the auction and encodes them. * @param _funder The address that funds the token for crowdsale. * @param _token Address of the token being sold. * @param _totalTokens The total number of tokens to sell in auction. * @param _startTime Auction start time. * @param _endTime Auction end time. * @param _paymentCurrency The currency the crowdsale accepts for payment. Can be ETH or token address. * @param _startPrice Starting price of the auction. * @param _minimumPrice The minimum auction price. * @param _admin Address that can finalize auction. * @param _pointList Address that will manage auction approvals. * @param _wallet Address where collected funds will be forwarded to. * @return _data All the data in bytes format. */ function getAuctionInitData( address _funder, address _token, uint256 _totalTokens, uint256 _startTime, uint256 _endTime, address _paymentCurrency, uint256 _startPrice, uint256 _minimumPrice, address _admin, address _pointList, address payable _wallet ) external pure returns (bytes memory _data) { return abi.encode( _funder, _token, _totalTokens, _startTime, _endTime, _paymentCurrency, _startPrice, _minimumPrice, _admin, _pointList, _wallet ); } function getBaseInformation() external view returns( address, uint64, uint64, bool ) { return (auctionToken, marketInfo.startTime, marketInfo.endTime, marketStatus.finalized); } function getTotalTokens() external view returns(uint256) { return uint256(marketInfo.totalTokens); } }
* @notice How many tokens the user is able to claim. @param _user Auction participant address. @return User commitments reduced by already claimed tokens./
function tokensClaimable(address _user) public view returns (uint256) { uint256 tokensAvailable = commitments[_user].mul(1e18).div(clearingPrice()); return tokensAvailable.sub(claimed[_user]); }
8,023,979
[ 1, 44, 543, 4906, 2430, 326, 729, 353, 7752, 358, 7516, 18, 225, 389, 1355, 432, 4062, 14188, 1758, 18, 327, 2177, 3294, 1346, 13162, 635, 1818, 7516, 329, 2430, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 2430, 9762, 429, 12, 2867, 389, 1355, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 2430, 5268, 273, 3294, 1346, 63, 67, 1355, 8009, 16411, 12, 21, 73, 2643, 2934, 2892, 12, 2131, 5968, 5147, 10663, 203, 3639, 327, 2430, 5268, 18, 1717, 12, 14784, 329, 63, 67, 1355, 19226, 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 ]
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.10; import "./IVault.sol"; import "./IWeightedPool.sol"; import "../../external/gyro/ExtendedMath.sol"; import "../IPCVDepositBalances.sol"; import "../../oracle/IOracle.sol"; import "../../Constants.sol"; /// @title BalancerPool2Lens /// @author Fei Protocol /// @notice a contract to read tokens & fei out of a contract that reports balance in Balancer LP tokens. /// Limited to BPTs that have 2 underlying tokens. /// @notice this contract use code similar to BPTLens (that reads a whole pool). contract BalancerPool2Lens is IPCVDepositBalances { using ExtendedMath for uint256; /// @notice FEI token address address private constant FEI = 0x956F47F50A910163D8BF957Cf5846D573E7f87CA; /// @notice the deposit inspected address public immutable depositAddress; /// @notice the token the lens reports balances in address public immutable override balanceReportedIn; /// @notice the balancer pool to look at IWeightedPool public immutable pool; /// @notice the Balancer V2 Vault IVault public immutable balancerVault; // the pool id on balancer bytes32 internal immutable id; // the index of balanceReportedIn on the pool uint256 internal immutable index; /// @notice true if FEI is in the pair bool public immutable feiInPair; /// @notice true if FEI is the reported balance bool public immutable feiIsReportedIn; /// @notice the oracle for balanceReportedIn token IOracle public immutable reportedOracle; /// @notice the oracle for the other token in the pair (not balanceReportedIn) IOracle public immutable otherOracle; constructor( address _depositAddress, address _token, IWeightedPool _pool, IOracle _reportedOracle, IOracle _otherOracle, bool _feiIsReportedIn, bool _feiIsOther ) { depositAddress = _depositAddress; pool = _pool; IVault _vault = _pool.getVault(); balancerVault = _vault; bytes32 _id = _pool.getPoolId(); id = _id; (IERC20[] memory tokens, , ) = _vault.getPoolTokens(_id); // Check the token is in the BPT and its only a 2 token pool require(address(tokens[0]) == _token || address(tokens[1]) == _token); require(tokens.length == 2); balanceReportedIn = _token; index = address(tokens[0]) == _token ? 0 : 1; feiIsReportedIn = _feiIsReportedIn; feiInPair = _feiIsReportedIn || _feiIsOther; reportedOracle = _reportedOracle; otherOracle = _otherOracle; } function balance() public view override returns (uint256) { (, uint256[] memory balances, ) = balancerVault.getPoolTokens(id); uint256 bptsOwned = IPCVDepositBalances(depositAddress).balance(); uint256 totalSupply = pool.totalSupply(); return (balances[index] * bptsOwned) / totalSupply; } function resistantBalanceAndFei() public view override returns (uint256, uint256) { uint256[] memory prices = new uint256[](2); uint256 j = index == 0 ? 1 : 0; // Check oracles and fill in prices (Decimal.D256 memory reportedPrice, bool reportedValid) = reportedOracle .read(); prices[index] = reportedPrice.value; (Decimal.D256 memory otherPrice, bool otherValid) = otherOracle.read(); prices[j] = otherPrice.value; require(reportedValid && otherValid, "BPTLens: Invalid Oracle"); (, uint256[] memory balances, ) = balancerVault.getPoolTokens(id); uint256 bptsOwned = IPCVDepositBalances(depositAddress).balance(); uint256 totalSupply = pool.totalSupply(); uint256[] memory weights = pool.getNormalizedWeights(); // uses balances, weights, and prices to calculate manipulation resistant reserves uint256 reserves = _getIdealReserves(balances, prices, weights, index); // if the deposit owns x% of the pool, only keep x% of the reserves reserves = (reserves * bptsOwned) / totalSupply; if (feiIsReportedIn) { return (reserves, reserves); } if (feiInPair) { uint256 otherReserves = _getIdealReserves( balances, prices, weights, j ); return (reserves, otherReserves); } return (reserves, 0); } /* let r represent reserves and r' be ideal reserves (derived from manipulation resistant variables) p are resistant oracle prices of the tokens w are the balancer weights k is the balancer invariant BPTPrice = (p0/w0)^w0 * (p1/w1)^w1 * k r0' = BPTPrice * w0/p0 r0' = ((w0*p1)/(p0*w1))^w1 * k Now including k allows for further simplification k = r0^w0 * r1^w1 r0' = r0^w0 * r1^w1 * ((w0*p1)/(p0*w1))^w1 r0' = r0^w0 * ((w0*p1*r1)/(p0*w1))^w1 */ function _getIdealReserves( uint256[] memory balances, uint256[] memory prices, uint256[] memory weights, uint256 i ) internal pure returns (uint256 reserves) { uint256 j = i == 0 ? 1 : 0; uint256 one = Constants.ETH_GRANULARITY; uint256 reservesScaled = one.mulPow( balances[i], weights[i], Constants.ETH_DECIMALS ); uint256 multiplier = (weights[i] * prices[j] * balances[j]) / (prices[i] * weights[j]); reserves = reservesScaled.mulPow( multiplier, weights[j], Constants.ETH_DECIMALS ); } } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; pragma solidity ^0.8.0; interface IAsset {} // interface with required methods from Balancer V2 IVault // https://github.com/balancer-labs/balancer-v2-monorepo/blob/389b52f1fc9e468de854810ce9dc3251d2d5b212/pkg/vault/contracts/interfaces/IVault.sol /** * @dev Full external interface for the Vault core contract - no external or public methods exist in the contract that * don't override one of these declarations. */ interface IVault { // Generalities about the Vault: // // - Whenever documentation refers to 'tokens', it strictly refers to ERC20-compliant token contracts. Tokens are // transferred out of the Vault by calling the `IERC20.transfer` function, and transferred in by calling // `IERC20.transferFrom`. In these cases, the sender must have previously allowed the Vault to use their tokens by // calling `IERC20.approve`. The only deviation from the ERC20 standard that is supported is functions not returning // a boolean value: in these scenarios, a non-reverting call is assumed to be successful. // // - All non-view functions in the Vault are non-reentrant: calling them while another one is mid-execution (e.g. // while execution control is transferred to a token contract during a swap) will result in a revert. View // functions can be called in a re-reentrant way, but doing so might cause them to return inconsistent results. // Contracts calling view functions in the Vault must make sure the Vault has not already been entered. // // - View functions revert if referring to either unregistered Pools, or unregistered tokens for registered Pools. // Authorizer // // Some system actions are permissioned, like setting and collecting protocol fees. This permissioning system exists // outside of the Vault in the Authorizer contract: the Vault simply calls the Authorizer to check if the caller // can perform a given action. // Relayers // // Additionally, it is possible for an account to perform certain actions on behalf of another one, using their // Vault ERC20 allowance and Internal Balance. These accounts are said to be 'relayers' for these Vault functions, // and are expected to be smart contracts with sound authentication mechanisms. For an account to be able to wield // this power, two things must occur: // - The Authorizer must grant the account the permission to be a relayer for the relevant Vault function. This // means that Balancer governance must approve each individual contract to act as a relayer for the intended // functions. // - Each user must approve the relayer to act on their behalf. // This double protection means users cannot be tricked into approving malicious relayers (because they will not // have been allowed by the Authorizer via governance), nor can malicious relayers approved by a compromised // Authorizer or governance drain user funds, since they would also need to be approved by each individual user. /** * @dev Returns true if `user` has approved `relayer` to act as a relayer for them. */ function hasApprovedRelayer(address user, address relayer) external view returns (bool); /** * @dev Allows `relayer` to act as a relayer for `sender` if `approved` is true, and disallows it otherwise. * * Emits a `RelayerApprovalChanged` event. */ function setRelayerApproval( address sender, address relayer, bool approved ) external; /** * @dev Emitted every time a relayer is approved or disapproved by `setRelayerApproval`. */ event RelayerApprovalChanged( address indexed relayer, address indexed sender, bool approved ); // Internal Balance // // Users can deposit tokens into the Vault, where they are allocated to their Internal Balance, and later // transferred or withdrawn. It can also be used as a source of tokens when joining Pools, as a destination // when exiting them, and as either when performing swaps. This usage of Internal Balance results in greatly reduced // gas costs when compared to relying on plain ERC20 transfers, leading to large savings for frequent users. // // Internal Balance management features batching, which means a single contract call can be used to perform multiple // operations of different kinds, with different senders and recipients, at once. /** * @dev Returns `user`'s Internal Balance for a set of tokens. */ function getInternalBalance(address user, IERC20[] memory tokens) external view returns (uint256[] memory); /** * @dev Performs a set of user balance operations, which involve Internal Balance (deposit, withdraw or transfer) * and plain ERC20 transfers using the Vault's allowance. This last feature is particularly useful for relayers, as * it lets integrators reuse a user's Vault allowance. * * For each operation, if the caller is not `sender`, it must be an authorized relayer for them. */ function manageUserBalance(UserBalanceOp[] memory ops) external payable; /** * @dev Data for `manageUserBalance` operations, which include the possibility for ETH to be sent and received without manual WETH wrapping or unwrapping. */ struct UserBalanceOp { UserBalanceOpKind kind; IAsset asset; uint256 amount; address sender; address payable recipient; } // There are four possible operations in `manageUserBalance`: // // - DEPOSIT_INTERNAL // Increases the Internal Balance of the `recipient` account by transferring tokens from the corresponding // `sender`. The sender must have allowed the Vault to use their tokens via `IERC20.approve()`. // // ETH can be used by passing the ETH sentinel value as the asset and forwarding ETH in the call: it will be wrapped // and deposited as WETH. Any ETH amount remaining will be sent back to the caller (not the sender, which is // relevant for relayers). // // Emits an `InternalBalanceChanged` event. // // // - WITHDRAW_INTERNAL // Decreases the Internal Balance of the `sender` account by transferring tokens to the `recipient`. // // ETH can be used by passing the ETH sentinel value as the asset. This will deduct WETH instead, unwrap it and send // it to the recipient as ETH. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_INTERNAL // Transfers tokens from the Internal Balance of the `sender` account to the Internal Balance of `recipient`. // // Reverts if the ETH sentinel value is passed. // // Emits an `InternalBalanceChanged` event. // // // - TRANSFER_EXTERNAL // Transfers tokens from `sender` to `recipient`, using the Vault's ERC20 allowance. This is typically used by // relayers, as it lets them reuse a user's Vault allowance. // // Reverts if the ETH sentinel value is passed. // // Emits an `ExternalBalanceTransfer` event. enum UserBalanceOpKind { DEPOSIT_INTERNAL, WITHDRAW_INTERNAL, TRANSFER_INTERNAL, TRANSFER_EXTERNAL } /** * @dev Emitted when a user's Internal Balance changes, either from calls to `manageUserBalance`, or through * interacting with Pools using Internal Balance. * * Because Internal Balance works exclusively with ERC20 tokens, ETH deposits and withdrawals will use the WETH * address. */ event InternalBalanceChanged( address indexed user, IERC20 indexed token, int256 delta ); /** * @dev Emitted when a user's Vault ERC20 allowance is used by the Vault to transfer tokens to an external account. */ event ExternalBalanceTransfer( IERC20 indexed token, address indexed sender, address recipient, uint256 amount ); // Pools // // There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced // functionality: // // - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the // balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads), // which increase with the number of registered tokens. // // - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the // balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted // constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are // independent of the number of registered tokens. // // - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like // minimal swap info Pools, these are called via IMinimalSwapInfoPool. enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN } /** * @dev Registers the caller account as a Pool with a given specialization setting. Returns the Pool's ID, which * is used in all Pool-related functions. Pools cannot be deregistered, nor can the Pool's specialization be * changed. * * The caller is expected to be a smart contract that implements either `IGeneralPool` or `IMinimalSwapInfoPool`, * depending on the chosen specialization setting. This contract is known as the Pool's contract. * * Note that the same contract may register itself as multiple Pools with unique Pool IDs, or in other words, * multiple Pools may share the same contract. * * Emits a `PoolRegistered` event. */ function registerPool(PoolSpecialization specialization) external returns (bytes32); /** * @dev Emitted when a Pool is registered by calling `registerPool`. */ event PoolRegistered( bytes32 indexed poolId, address indexed poolAddress, PoolSpecialization specialization ); /** * @dev Returns a Pool's contract address and specialization setting. */ function getPool(bytes32 poolId) external view returns (address, PoolSpecialization); /** * @dev Registers `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Pools can only interact with tokens they have registered. Users join a Pool by transferring registered tokens, * exit by receiving registered tokens, and can only swap registered tokens. * * Each token can only be registered once. For Pools with the Two Token specialization, `tokens` must have a length * of two, that is, both tokens must be registered in the same `registerTokens` call, and they must be sorted in * ascending order. * * The `tokens` and `assetManagers` arrays must have the same length, and each entry in these indicates the Asset * Manager for the corresponding token. Asset Managers can manage a Pool's tokens via `managePoolBalance`, * depositing and withdrawing them directly, and can even set their balance to arbitrary amounts. They are therefore * expected to be highly secured smart contracts with sound design principles, and the decision to register an * Asset Manager should not be made lightly. * * Pools can choose not to assign an Asset Manager to a given token by passing in the zero address. Once an Asset * Manager is set, it cannot be changed except by deregistering the associated token and registering again with a * different Asset Manager. * * Emits a `TokensRegistered` event. */ function registerTokens( bytes32 poolId, IERC20[] memory tokens, address[] memory assetManagers ) external; /** * @dev Emitted when a Pool registers tokens by calling `registerTokens`. */ event TokensRegistered( bytes32 indexed poolId, IERC20[] tokens, address[] assetManagers ); /** * @dev Deregisters `tokens` for the `poolId` Pool. Must be called by the Pool's contract. * * Only registered tokens (via `registerTokens`) can be deregistered. Additionally, they must have zero total * balance. For Pools with the Two Token specialization, `tokens` must have a length of two, that is, both tokens * must be deregistered in the same `deregisterTokens` call. * * A deregistered token can be re-registered later on, possibly with a different Asset Manager. * * Emits a `TokensDeregistered` event. */ function deregisterTokens(bytes32 poolId, IERC20[] memory tokens) external; /** * @dev Emitted when a Pool deregisters tokens by calling `deregisterTokens`. */ event TokensDeregistered(bytes32 indexed poolId, IERC20[] tokens); /** * @dev Returns detailed information for a Pool's registered token. * * `cash` is the number of tokens the Vault currently holds for the Pool. `managed` is the number of tokens * withdrawn and held outside the Vault by the Pool's token Asset Manager. The Pool's total balance for `token` * equals the sum of `cash` and `managed`. * * Internally, `cash` and `managed` are stored using 112 bits. No action can ever cause a Pool's token `cash`, * `managed` or `total` balance to be greater than 2^112 - 1. * * `lastChangeBlock` is the number of the block in which `token`'s total balance was last modified (via either a * join, exit, swap, or Asset Manager update). This value is useful to avoid so-called 'sandwich attacks', for * example when developing price oracles. A change of zero (e.g. caused by a swap with amount zero) is considered a * change for this purpose, and will update `lastChangeBlock`. * * `assetManager` is the Pool's token Asset Manager. */ function getPoolTokenInfo(bytes32 poolId, IERC20 token) external view returns ( uint256 cash, uint256 managed, uint256 lastChangeBlock, address assetManager ); /** * @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of * the tokens' `balances` changed. * * The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all * Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order. * * If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same * order as passed to `registerTokens`. * * Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are * the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo` * instead. */ function getPoolTokens(bytes32 poolId) external view returns ( IERC20[] memory tokens, uint256[] memory balances, uint256 lastChangeBlock ); /** * @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will * trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized * Pool shares. * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount * to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces * these maximums. * * If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable * this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the * WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent * back to the caller (not the sender, which is important for relayers). * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be * sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final * `assets` array might not be sorted. Pools with no registered tokens cannot be joined. * * If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only * be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be * withdrawn from Internal Balance: attempting to do so will trigger a revert. * * This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed * directly to the Pool's contract, as is `recipient`. * * Emits a `PoolBalanceChanged` event. */ function joinPool( bytes32 poolId, address sender, address recipient, JoinPoolRequest memory request ) external payable; struct JoinPoolRequest { IAsset[] assets; uint256[] maxAmountsIn; bytes userData; bool fromInternalBalance; } /** * @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will * trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized * Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see * `getPoolTokenInfo`). * * If the caller is not `sender`, it must be an authorized relayer for them. * * The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum * token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault: * it just enforces these minimums. * * If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To * enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead * of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit. * * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when * interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must * be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the * final `assets` array might not be sorted. Pools with no registered tokens cannot be exited. * * If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise, * an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to * do so will trigger a revert. * * `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the * `tokens` array. This array must match the Pool's registered tokens. * * This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement * their own custom logic. This typically requires additional information from the user (such as the expected number * of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and * passed directly to the Pool's contract. * * Emits a `PoolBalanceChanged` event. */ function exitPool( bytes32 poolId, address sender, address payable recipient, ExitPoolRequest memory request ) external; struct ExitPoolRequest { IAsset[] assets; uint256[] minAmountsOut; bytes userData; bool toInternalBalance; } /** * @dev Emitted when a user joins or exits a Pool by calling `joinPool` or `exitPool`, respectively. */ event PoolBalanceChanged( bytes32 indexed poolId, address indexed liquidityProvider, IERC20[] tokens, int256[] deltas, uint256[] protocolFeeAmounts ); enum PoolBalanceChangeKind { JOIN, EXIT } // Swaps // // Users can swap tokens with Pools by calling the `swap` and `batchSwap` functions. To do this, // they need not trust Pool contracts in any way: all security checks are made by the Vault. They must however be // aware of the Pools' pricing algorithms in order to estimate the prices Pools will quote. // // The `swap` function executes a single swap, while `batchSwap` can perform multiple swaps in sequence. // In each individual swap, tokens of one kind are sent from the sender to the Pool (this is the 'token in'), // and tokens of another kind are sent from the Pool to the recipient in exchange (this is the 'token out'). // More complex swaps, such as one token in to multiple tokens out can be achieved by batching together // individual swaps. // // There are two swap kinds: // - 'given in' swaps, where the amount of tokens in (sent to the Pool) is known, and the Pool determines (via the // `onSwap` hook) the amount of tokens out (to send to the recipient). // - 'given out' swaps, where the amount of tokens out (received from the Pool) is known, and the Pool determines // (via the `onSwap` hook) the amount of tokens in (to receive from the sender). // // Additionally, it is possible to chain swaps using a placeholder input amount, which the Vault replaces with // the calculated output of the previous swap. If the previous swap was 'given in', this will be the calculated // tokenOut amount. If the previous swap was 'given out', it will use the calculated tokenIn amount. These extended // swaps are known as 'multihop' swaps, since they 'hop' through a number of intermediate tokens before arriving at // the final intended token. // // In all cases, tokens are only transferred in and out of the Vault (or withdrawn from and deposited into Internal // Balance) after all individual swaps have been completed, and the net token balance change computed. This makes // certain swap patterns, such as multihops, or swaps that interact with the same token pair in multiple Pools, cost // much less gas than they would otherwise. // // It also means that under certain conditions it is possible to perform arbitrage by swapping with multiple // Pools in a way that results in net token movement out of the Vault (profit), with no tokens being sent in (only // updating the Pool's internal accounting). // // To protect users from front-running or the market changing rapidly, they supply a list of 'limits' for each token // involved in the swap, where either the maximum number of tokens to send (by passing a positive value) or the // minimum amount of tokens to receive (by passing a negative value) is specified. // // Additionally, a 'deadline' timestamp can also be provided, forcing the swap to fail if it occurs after // this point in time (e.g. if the transaction failed to be included in a block promptly). // // If interacting with Pools that hold WETH, it is possible to both send and receive ETH directly: the Vault will do // the wrapping and unwrapping. To enable this mechanism, the IAsset sentinel value (the zero address) must be // passed in the `assets` array instead of the WETH address. Note that it is possible to combine ETH and WETH in the // same swap. Any excess ETH will be sent back to the caller (not the sender, which is relevant for relayers). // // Finally, Internal Balance can be used when either sending or receiving tokens. enum SwapKind { GIVEN_IN, GIVEN_OUT } /** * @dev Performs a swap with a single Pool. * * If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens * taken from the Pool, which must be greater than or equal to `limit`. * * If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens * sent to the Pool, which must be less than or equal to `limit`. * * Internal Balance usage and the recipient are determined by the `funds` struct. * * Emits a `Swap` event. */ function swap( SingleSwap memory singleSwap, FundManagement memory funds, uint256 limit, uint256 deadline ) external payable returns (uint256); /** * @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on * the `kind` value. * * `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address). * Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct SingleSwap { bytes32 poolId; SwapKind kind; IAsset assetIn; IAsset assetOut; uint256 amount; bytes userData; } /** * @dev Performs a series of swaps with one or multiple Pools. In each individual swap, the caller determines either * the amount of tokens sent to or received from the Pool, depending on the `kind` value. * * Returns an array with the net Vault asset balance deltas. Positive amounts represent tokens (or ETH) sent to the * Vault, and negative amounts represent tokens (or ETH) sent by the Vault. Each delta corresponds to the asset at * the same index in the `assets` array. * * Swaps are executed sequentially, in the order specified by the `swaps` array. Each array element describes a * Pool, the token to be sent to this Pool, the token to receive from it, and an amount that is either `amountIn` or * `amountOut` depending on the swap kind. * * Multihop swaps can be executed by passing an `amount` value of zero for a swap. This will cause the amount in/out * of the previous swap to be used as the amount in for the current one. In a 'given in' swap, 'tokenIn' must equal * the previous swap's `tokenOut`. For a 'given out' swap, `tokenOut` must equal the previous swap's `tokenIn`. * * The `assets` array contains the addresses of all assets involved in the swaps. These are either token addresses, * or the IAsset sentinel value for ETH (the zero address). Each entry in the `swaps` array specifies tokens in and * out by referencing an index in `assets`. Note that Pools never interact with ETH directly: it will be wrapped to * or unwrapped from WETH by the Vault. * * Internal Balance usage, sender, and recipient are determined by the `funds` struct. The `limits` array specifies * the minimum or maximum amount of each token the vault is allowed to transfer. * * `batchSwap` can be used to make a single swap, like `swap` does, but doing so requires more gas than the * equivalent `swap` call. * * Emits `Swap` events. */ function batchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds, int256[] memory limits, uint256 deadline ) external payable returns (int256[] memory); /** * @dev Data for each individual swap executed by `batchSwap`. The asset in and out fields are indexes into the * `assets` array passed to that function, and ETH assets are converted to WETH. * * If `amount` is zero, the multihop mechanism is used to determine the actual amount based on the amount in/out * from the previous swap, depending on the swap kind. * * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be * used to extend swap behavior. */ struct BatchSwapStep { bytes32 poolId; uint256 assetInIndex; uint256 assetOutIndex; uint256 amount; bytes userData; } /** * @dev Emitted for each individual swap performed by `swap` or `batchSwap`. */ event Swap( bytes32 indexed poolId, IERC20 indexed tokenIn, IERC20 indexed tokenOut, uint256 amountIn, uint256 amountOut ); /** * @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the * `recipient` account. * * If the caller is not `sender`, it must be an authorized relayer for them. * * If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20 * transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender` * must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of * `joinPool`. * * If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of * transferred. This matches the behavior of `exitPool`. * * Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a * revert. */ struct FundManagement { address sender; bool fromInternalBalance; address payable recipient; bool toInternalBalance; } /** * @dev Simulates a call to `batchSwap`, returning an array of Vault asset deltas. Calls to `swap` cannot be * simulated directly, but an equivalent `batchSwap` call can and will yield the exact same result. * * Each element in the array corresponds to the asset at the same index, and indicates the number of tokens (or ETH) * the Vault would take from the sender (if positive) or send to the recipient (if negative). The arguments it * receives are the same that an equivalent `batchSwap` call would receive. * * Unlike `batchSwap`, this function performs no checks on the sender or recipient field in the `funds` struct. * This makes it suitable to be called by off-chain applications via eth_call without needing to hold tokens, * approve them for the Vault, or even know a user's address. * * Note that this function is not 'view' (due to implementation details): the client code must explicitly execute * eth_call instead of eth_sendTransaction. */ function queryBatchSwap( SwapKind kind, BatchSwapStep[] memory swaps, IAsset[] memory assets, FundManagement memory funds ) external returns (int256[] memory assetDeltas); // Asset Management // // Each token registered for a Pool can be assigned an Asset Manager, which is able to freely withdraw the Pool's // tokens from the Vault, deposit them, or assign arbitrary values to its `managed` balance (see // `getPoolTokenInfo`). This makes them extremely powerful and dangerous. Even if an Asset Manager only directly // controls one of the tokens in a Pool, a malicious manager could set that token's balance to manipulate the // prices of the other tokens, and then drain the Pool with swaps. The risk of using Asset Managers is therefore // not constrained to the tokens they are managing, but extends to the entire Pool's holdings. // // However, a properly designed Asset Manager smart contract can be safely used for the Pool's benefit, // for example by lending unused tokens out for interest, or using them to participate in voting protocols. // // This concept is unrelated to the IAsset interface. /** * @dev Performs a set of Pool balance operations, which may be either withdrawals, deposits or updates. * * Pool Balance management features batching, which means a single contract call can be used to perform multiple * operations of different kinds, with different Pools and tokens, at once. * * For each operation, the caller must be registered as the Asset Manager for `token` in `poolId`. */ function managePoolBalance(PoolBalanceOp[] memory ops) external; struct PoolBalanceOp { PoolBalanceOpKind kind; bytes32 poolId; IERC20 token; uint256 amount; } /** * Withdrawals decrease the Pool's cash, but increase its managed balance, leaving the total balance unchanged. * * Deposits increase the Pool's cash, but decrease its managed balance, leaving the total balance unchanged. * * Updates don't affect the Pool's cash balance, but because the managed balance changes, it does alter the total. * The external amount can be either increased or decreased by this call (i.e., reporting a gain or a loss). */ enum PoolBalanceOpKind { WITHDRAW, DEPOSIT, UPDATE } /** * @dev Emitted when a Pool's token Asset Manager alters its balance via `managePoolBalance`. */ event PoolBalanceManaged( bytes32 indexed poolId, address indexed assetManager, IERC20 indexed token, int256 cashDelta, int256 managedDelta ); /** * @dev Safety mechanism to pause most Vault operations in the event of an emergency - typically detection of an * error in some part of the system. * * The Vault can only be paused during an initial time period, after which pausing is forever disabled. * * While the contract is paused, the following features are disabled: * - depositing and transferring internal balance * - transferring external balance (using the Vault's allowance) * - swaps * - joining Pools * - Asset Manager interactions * * Internal Balance can still be withdrawn, and Pools exited. */ function setPaused(bool paused) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "./IBasePool.sol"; // interface with required methods from Balancer V2 WeightedPool // https://github.com/balancer-labs/balancer-v2-monorepo/blob/389b52f1fc9e468de854810ce9dc3251d2d5b212/pkg/pool-weighted/contracts/WeightedPool.sol interface IWeightedPool is IBasePool { function getSwapEnabled() external view returns (bool); function getNormalizedWeights() external view returns (uint256[] memory); function getGradualWeightUpdateParams() external view returns ( uint256 startTime, uint256 endTime, uint256[] memory endWeights ); function setSwapEnabled(bool swapEnabled) external; function updateWeightsGradually( uint256 startTime, uint256 endTime, uint256[] memory endWeights ) external; function withdrawCollectedManagementFees(address recipient) external; enum JoinKind { INIT, EXACT_TOKENS_IN_FOR_BPT_OUT, TOKEN_IN_FOR_EXACT_BPT_OUT } enum ExitKind { EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, EXACT_BPT_IN_FOR_TOKENS_OUT, BPT_IN_FOR_EXACT_TOKENS_OUT } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "./IAssetManager.sol"; import "./IVault.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // interface with required methods from Balancer V2 IBasePool // https://github.com/balancer-labs/balancer-v2-monorepo/blob/389b52f1fc9e468de854810ce9dc3251d2d5b212/pkg/pool-utils/contracts/BasePool.sol interface IBasePool is IERC20 { function getSwapFeePercentage() external view returns (uint256); function setSwapFeePercentage(uint256 swapFeePercentage) external; function setAssetManagerPoolConfig( IERC20 token, IAssetManager.PoolConfig memory poolConfig ) external; function setPaused(bool paused) external; function getVault() external view returns (IVault); function getPoolId() external view returns (bytes32); function getOwner() external view returns (address); } // SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.8.0; // interface with required methods from Balancer V2 IBasePool // https://github.com/balancer-labs/balancer-v2-monorepo/blob/389b52f1fc9e468de854810ce9dc3251d2d5b212/pkg/asset-manager-utils/contracts/IAssetManager.sol interface IAssetManager { struct PoolConfig { uint64 targetPercentage; uint64 criticalPercentage; uint64 feePercentage; } function setPoolConfig(bytes32 poolId, PoolConfig calldata config) external; } //SPDX-License-Identifier: Unlicense pragma solidity ^0.8.4; import "./abdk/ABDKMath64x64.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @notice This contract contains math related utilities that allows to * compute fixed-point exponentiation or perform scaled arithmetic operations */ library ExtendedMath { using ABDKMath64x64 for int128; using ABDKMath64x64 for uint256; using SafeMath for uint256; uint256 constant decimals = 18; uint256 constant decimalScale = 10**decimals; /** * @notice Computes x**y where both `x` and `y` are fixed-point numbers */ function powf(int128 _x, int128 _y) internal pure returns (int128 _xExpy) { // 2^(y * log2(x)) return _y.mul(_x.log_2()).exp_2(); } /** * @notice Computes `value * base ** exponent` where all of the parameters * are fixed point numbers scaled with `decimal` */ function mulPow( uint256 value, uint256 base, uint256 exponent, uint256 decimal ) internal pure returns (uint256) { int128 basef = base.fromScaled(decimal); int128 expf = exponent.fromScaled(decimal); return powf(basef, expf).mulu(value); } /** * @notice Multiplies `a` and `b` scaling the result down by `_decimals` * `scaledMul(a, b, 18)` with an initial scale of 18 decimals for `a` and `b` * would keep the result to 18 decimals * The result of the computation is floored */ function scaledMul( uint256 a, uint256 b, uint256 _decimals ) internal pure returns (uint256) { return a.mul(b).div(10**_decimals); } function scaledMul(uint256 a, uint256 b) internal pure returns (uint256) { return scaledMul(a, b, decimals); } /** * @notice Divides `a` and `b` scaling the result up by `_decimals` * `scaledDiv(a, b, 18)` with an initial scale of 18 decimals for `a` and `b` * would keep the result to 18 decimals * The result of the computation is floored */ function scaledDiv( uint256 a, uint256 b, uint256 _decimals ) internal pure returns (uint256) { return a.mul(10**_decimals).div(b); } /** * @notice See `scaledDiv(uint256 a, uint256 b, uint256 _decimals)` */ function scaledDiv(uint256 a, uint256 b) internal pure returns (uint256) { return scaledDiv(a, b, decimals); } /** * @notice Computes a**b where a is a scaled fixed-point number and b is an integer * This keeps a scale of `_decimals` for `a` * The computation is performed in O(log n) */ function scaledPow( uint256 base, uint256 exp, uint256 _decimals ) internal pure returns (uint256) { uint256 result = 10**_decimals; while (exp > 0) { if (exp % 2 == 1) { result = scaledMul(result, base, _decimals); } exp /= 2; base = scaledMul(base, base, _decimals); } return result; } /** * @notice See `scaledPow(uint256 base, uint256 exp, uint256 _decimals)` */ function scaledPow(uint256 base, uint256 exp) internal pure returns (uint256) { return scaledPow(base, exp, decimals); } } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.8.4; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; function uint256toInt128(uint256 input) internal pure returns (int128) { return int128(int256(input)); } function int128toUint256(int128 input) internal pure returns (uint256) { return uint256(int256(input)); } function int128toUint64(int128 input) internal pure returns (uint64) { return uint64(uint256(int256(input))); } /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt(int256 x) internal pure returns (int128) { require(x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128(x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt(int128 x) internal pure returns (int64) { return int64(x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt(uint256 x) internal pure returns (int128) { require( x <= 0x7FFFFFFFFFFFFFFF, "value is too high to be transformed in a 64.64-bit number" ); return uint256toInt128(x << 64); } /** * Convert unsigned 256-bit integer number scaled with 10^decimals into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @param decimal scale of the number * @return signed 64.64-bit fixed point number */ function fromScaled(uint256 x, uint256 decimal) internal pure returns (int128) { uint256 scale = 10**decimal; int128 wholeNumber = fromUInt(x / scale); int128 decimalNumber = div(fromUInt(x % scale), fromUInt(scale)); return add(wholeNumber, decimalNumber); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt(int128 x) internal pure returns (uint64) { require(x >= 0); return int128toUint64(x >> 64); } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128(int256 x) internal pure returns (int128) { int256 result = x >> 64; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128(int128 x) internal pure returns (int256) { return int256(x) << 64; } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add(int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub(int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul(int128 x, int128 y) internal pure returns (int128) { int256 result = (int256(x) * y) >> 64; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli(int128 x, int256 y) internal pure returns (int256) { if (x == MIN_64x64) { require( y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000 ); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu(x, uint256(y)); if (negativeResult) { require( absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000 ); return -int256(absoluteResult); // We rely on overflow behavior here } else { require( absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF ); return int256(absoluteResult); } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu(int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require(x >= 0); uint256 lo = (int128toUint256(x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = int128toUint256(x) * (y >> 128); require(hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require( hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo ); return hi + lo; } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div(int128 x, int128 y) internal pure returns (int128) { require(y != 0); int256 result = (int256(x) << 64) / y; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi(int256 x, int256 y) internal pure returns (int128) { require(y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu(uint256(x), uint256(y)); if (negativeResult) { require(absoluteResult <= 0x80000000000000000000000000000000); return -int128(absoluteResult); // We rely on overflow behavior here } else { require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128(absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu(uint256 x, uint256 y) internal pure returns (int128) { require(y != 0); uint128 result = divuu(x, y); require(result <= uint128(MAX_64x64)); return int128(result); } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg(int128 x) internal pure returns (int128) { require(x != MIN_64x64); return -x; } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs(int128 x) internal pure returns (int128) { require(x != MIN_64x64); return x < 0 ? -x : x; } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv(int128 x) internal pure returns (int128) { require(x != 0); int256 result = int256(0x100000000000000000000000000000000) / x; require(result >= MIN_64x64 && result <= MAX_64x64); return int128(result); } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg(int128 x, int128 y) internal pure returns (int128) { return int128((int256(x) + int256(y)) >> 1); } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg(int128 x, int128 y) internal pure returns (int128) { int256 m = int256(x) * int256(y); require(m >= 0); require( m < 0x4000000000000000000000000000000000000000000000000000000000000000 ); return int128(sqrtu(uint256(m))); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow(int128 x, uint256 y) internal pure returns (int128) { uint256 absoluteResult; bool negativeResult = false; if (x >= 0) { absoluteResult = powu(int128toUint256(x) << 63, y); } else { // We rely on overflow behavior here absoluteResult = powu(uint256(uint128(-x)) << 63, y); negativeResult = y & 1 > 0; } absoluteResult >>= 63; if (negativeResult) { require(absoluteResult <= 0x80000000000000000000000000000000); return -uint256toInt128(absoluteResult); // We rely on overflow behavior here } else { require(absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint256toInt128(absoluteResult); // We rely on overflow behavior here } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt(int128 x) internal pure returns (int128) { require(x >= 0); return int128(sqrtu(int128toUint256(x) << 64)); } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2(int128 x) internal pure returns (int128) { require(x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = (msb - 64) << 64; uint256 ux = int128toUint256(x) << uint256(127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256(b); } return int128(result); } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln(int128 x) internal pure returns (int128) { require(x > 0); return uint256toInt128( (int128toUint256(log_2(x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF) >> 128 ); } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2(int128 x) internal pure returns (int128) { require(x < 0x400000000000000000, "exponent too large"); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = (result * 0x16A09E667F3BCC908B2FB1366EA957D3E) >> 128; if (x & 0x4000000000000000 > 0) result = (result * 0x1306FE0A31B7152DE8D5A46305C85EDEC) >> 128; if (x & 0x2000000000000000 > 0) result = (result * 0x1172B83C7D517ADCDF7C8C50EB14A791F) >> 128; if (x & 0x1000000000000000 > 0) result = (result * 0x10B5586CF9890F6298B92B71842A98363) >> 128; if (x & 0x800000000000000 > 0) result = (result * 0x1059B0D31585743AE7C548EB68CA417FD) >> 128; if (x & 0x400000000000000 > 0) result = (result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8) >> 128; if (x & 0x200000000000000 > 0) result = (result * 0x10163DA9FB33356D84A66AE336DCDFA3F) >> 128; if (x & 0x100000000000000 > 0) result = (result * 0x100B1AFA5ABCBED6129AB13EC11DC9543) >> 128; if (x & 0x80000000000000 > 0) result = (result * 0x10058C86DA1C09EA1FF19D294CF2F679B) >> 128; if (x & 0x40000000000000 > 0) result = (result * 0x1002C605E2E8CEC506D21BFC89A23A00F) >> 128; if (x & 0x20000000000000 > 0) result = (result * 0x100162F3904051FA128BCA9C55C31E5DF) >> 128; if (x & 0x10000000000000 > 0) result = (result * 0x1000B175EFFDC76BA38E31671CA939725) >> 128; if (x & 0x8000000000000 > 0) result = (result * 0x100058BA01FB9F96D6CACD4B180917C3D) >> 128; if (x & 0x4000000000000 > 0) result = (result * 0x10002C5CC37DA9491D0985C348C68E7B3) >> 128; if (x & 0x2000000000000 > 0) result = (result * 0x1000162E525EE054754457D5995292026) >> 128; if (x & 0x1000000000000 > 0) result = (result * 0x10000B17255775C040618BF4A4ADE83FC) >> 128; if (x & 0x800000000000 > 0) result = (result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB) >> 128; if (x & 0x400000000000 > 0) result = (result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9) >> 128; if (x & 0x200000000000 > 0) result = (result * 0x10000162E43F4F831060E02D839A9D16D) >> 128; if (x & 0x100000000000 > 0) result = (result * 0x100000B1721BCFC99D9F890EA06911763) >> 128; if (x & 0x80000000000 > 0) result = (result * 0x10000058B90CF1E6D97F9CA14DBCC1628) >> 128; if (x & 0x40000000000 > 0) result = (result * 0x1000002C5C863B73F016468F6BAC5CA2B) >> 128; if (x & 0x20000000000 > 0) result = (result * 0x100000162E430E5A18F6119E3C02282A5) >> 128; if (x & 0x10000000000 > 0) result = (result * 0x1000000B1721835514B86E6D96EFD1BFE) >> 128; if (x & 0x8000000000 > 0) result = (result * 0x100000058B90C0B48C6BE5DF846C5B2EF) >> 128; if (x & 0x4000000000 > 0) result = (result * 0x10000002C5C8601CC6B9E94213C72737A) >> 128; if (x & 0x2000000000 > 0) result = (result * 0x1000000162E42FFF037DF38AA2B219F06) >> 128; if (x & 0x1000000000 > 0) result = (result * 0x10000000B17217FBA9C739AA5819F44F9) >> 128; if (x & 0x800000000 > 0) result = (result * 0x1000000058B90BFCDEE5ACD3C1CEDC823) >> 128; if (x & 0x400000000 > 0) result = (result * 0x100000002C5C85FE31F35A6A30DA1BE50) >> 128; if (x & 0x200000000 > 0) result = (result * 0x10000000162E42FF0999CE3541B9FFFCF) >> 128; if (x & 0x100000000 > 0) result = (result * 0x100000000B17217F80F4EF5AADDA45554) >> 128; if (x & 0x80000000 > 0) result = (result * 0x10000000058B90BFBF8479BD5A81B51AD) >> 128; if (x & 0x40000000 > 0) result = (result * 0x1000000002C5C85FDF84BD62AE30A74CC) >> 128; if (x & 0x20000000 > 0) result = (result * 0x100000000162E42FEFB2FED257559BDAA) >> 128; if (x & 0x10000000 > 0) result = (result * 0x1000000000B17217F7D5A7716BBA4A9AE) >> 128; if (x & 0x8000000 > 0) result = (result * 0x100000000058B90BFBE9DDBAC5E109CCE) >> 128; if (x & 0x4000000 > 0) result = (result * 0x10000000002C5C85FDF4B15DE6F17EB0D) >> 128; if (x & 0x2000000 > 0) result = (result * 0x1000000000162E42FEFA494F1478FDE05) >> 128; if (x & 0x1000000 > 0) result = (result * 0x10000000000B17217F7D20CF927C8E94C) >> 128; if (x & 0x800000 > 0) result = (result * 0x1000000000058B90BFBE8F71CB4E4B33D) >> 128; if (x & 0x400000 > 0) result = (result * 0x100000000002C5C85FDF477B662B26945) >> 128; if (x & 0x200000 > 0) result = (result * 0x10000000000162E42FEFA3AE53369388C) >> 128; if (x & 0x100000 > 0) result = (result * 0x100000000000B17217F7D1D351A389D40) >> 128; if (x & 0x80000 > 0) result = (result * 0x10000000000058B90BFBE8E8B2D3D4EDE) >> 128; if (x & 0x40000 > 0) result = (result * 0x1000000000002C5C85FDF4741BEA6E77E) >> 128; if (x & 0x20000 > 0) result = (result * 0x100000000000162E42FEFA39FE95583C2) >> 128; if (x & 0x10000 > 0) result = (result * 0x1000000000000B17217F7D1CFB72B45E1) >> 128; if (x & 0x8000 > 0) result = (result * 0x100000000000058B90BFBE8E7CC35C3F0) >> 128; if (x & 0x4000 > 0) result = (result * 0x10000000000002C5C85FDF473E242EA38) >> 128; if (x & 0x2000 > 0) result = (result * 0x1000000000000162E42FEFA39F02B772C) >> 128; if (x & 0x1000 > 0) result = (result * 0x10000000000000B17217F7D1CF7D83C1A) >> 128; if (x & 0x800 > 0) result = (result * 0x1000000000000058B90BFBE8E7BDCBE2E) >> 128; if (x & 0x400 > 0) result = (result * 0x100000000000002C5C85FDF473DEA871F) >> 128; if (x & 0x200 > 0) result = (result * 0x10000000000000162E42FEFA39EF44D91) >> 128; if (x & 0x100 > 0) result = (result * 0x100000000000000B17217F7D1CF79E949) >> 128; if (x & 0x80 > 0) result = (result * 0x10000000000000058B90BFBE8E7BCE544) >> 128; if (x & 0x40 > 0) result = (result * 0x1000000000000002C5C85FDF473DE6ECA) >> 128; if (x & 0x20 > 0) result = (result * 0x100000000000000162E42FEFA39EF366F) >> 128; if (x & 0x10 > 0) result = (result * 0x1000000000000000B17217F7D1CF79AFA) >> 128; if (x & 0x8 > 0) result = (result * 0x100000000000000058B90BFBE8E7BCD6D) >> 128; if (x & 0x4 > 0) result = (result * 0x10000000000000002C5C85FDF473DE6B2) >> 128; if (x & 0x2 > 0) result = (result * 0x1000000000000000162E42FEFA39EF358) >> 128; if (x & 0x1 > 0) result = (result * 0x10000000000000000B17217F7D1CF79AB) >> 128; result >>= int128toUint256(63 - (x >> 64)); require(result <= int128toUint256(MAX_64x64)); return uint256toInt128(result); } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp(int128 x) internal pure returns (int128) { require(x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2( int128((int256(x) * 0x171547652B82FE1777D0FFDA0D23A7D12) >> 128) ); } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu(uint256 x, uint256 y) private pure returns (uint128) { require(y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << (255 - msb)) / (((y - 1) >> (msb - 191)) + 1); require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert(xh == hi >> 128); result += xl / y; } require(result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128(result); } /** * Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point * number and y is unsigned 256-bit integer number. Revert on overflow. * * @param x unsigned 129.127-bit fixed point number * @param y uint256 value * @return unsigned 129.127-bit fixed point number */ function powu(uint256 x, uint256 y) private pure returns (uint256) { if (y == 0) return 0x80000000000000000000000000000000; else if (x == 0) return 0; else { int256 msb = 0; uint256 xc = x; if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; } if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 xe = msb - 127; if (xe > 0) x >>= uint256(xe); else x <<= uint256(-xe); uint256 result = 0x80000000000000000000000000000000; int256 re = 0; while (y > 0) { if (y & 1 > 0) { result = result * x; y -= 1; re += xe; if ( result >= 0x8000000000000000000000000000000000000000000000000000000000000000 ) { result >>= 128; re += 1; } else result >>= 127; if (re < -127) return 0; // Underflow require(re < 128); // Overflow } else { x = x * x; y >>= 1; xe <<= 1; if ( x >= 0x8000000000000000000000000000000000000000000000000000000000000000 ) { x >>= 128; xe += 1; } else x >>= 127; if (xe < -127) return 0; // Underflow require(xe < 128); // Overflow } } if (re > 0) result <<= uint256(re); else if (re < 0) result >>= uint256(-re); return result; } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu(uint256 x) private pure returns (uint128) { 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 uint128(r < r1 ? r : r1); } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; /// @title a PCV Deposit interface for only balance getters /// @author Fei Protocol interface IPCVDepositBalances { // ----------- Getters ----------- /// @notice gets the effective balance of "balanceReportedIn" token if the deposit were fully withdrawn function balance() external view returns (uint256); /// @notice gets the token address in which this deposit returns its balance function balanceReportedIn() external view returns (address); /// @notice gets the resistant token balance and protocol owned fei of this deposit function resistantBalanceAndFei() external view returns (uint256, uint256); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../external/Decimal.sol"; /// @title generic oracle interface for Fei Protocol /// @author Fei Protocol interface IOracle { // ----------- Events ----------- event Update(uint256 _peg); // ----------- State changing API ----------- function update() external; // ----------- Getters ----------- function read() external view returns (Decimal.D256 memory, bool); function isOutdated() external view returns (bool); } /* Copyright 2019 dYdX Trading Inc. Copyright 2020 Empty Set Squad <[email protected]> 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.8.4; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title Decimal * @author dYdX * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMath for uint256; // ============ Constants ============ uint256 private constant BASE = 10**18; // ============ Structs ============ struct D256 { uint256 value; } // ============ Static Functions ============ function zero() internal pure returns (D256 memory) { return D256({value: 0}); } function one() internal pure returns (D256 memory) { return D256({value: BASE}); } function from(uint256 a) internal pure returns (D256 memory) { return D256({value: a.mul(BASE)}); } function ratio(uint256 a, uint256 b) internal pure returns (D256 memory) { return D256({value: getPartial(a, BASE, b)}); } // ============ Self Functions ============ function add(D256 memory self, uint256 b) internal pure returns (D256 memory) { return D256({value: self.value.add(b.mul(BASE))}); } function sub(D256 memory self, uint256 b) internal pure returns (D256 memory) { return D256({value: self.value.sub(b.mul(BASE))}); } function sub( D256 memory self, uint256 b, string memory reason ) internal pure returns (D256 memory) { return D256({value: self.value.sub(b.mul(BASE), reason)}); } function mul(D256 memory self, uint256 b) internal pure returns (D256 memory) { return D256({value: self.value.mul(b)}); } function div(D256 memory self, uint256 b) internal pure returns (D256 memory) { return D256({value: self.value.div(b)}); } function pow(D256 memory self, uint256 b) internal pure returns (D256 memory) { if (b == 0) { return from(1); } D256 memory temp = D256({value: self.value}); for (uint256 i = 1; i < b; i++) { temp = mul(temp, self); } return temp; } function add(D256 memory self, D256 memory b) internal pure returns (D256 memory) { return D256({value: self.value.add(b.value)}); } function sub(D256 memory self, D256 memory b) internal pure returns (D256 memory) { return D256({value: self.value.sub(b.value)}); } function sub( D256 memory self, D256 memory b, string memory reason ) internal pure returns (D256 memory) { return D256({value: self.value.sub(b.value, reason)}); } function mul(D256 memory self, D256 memory b) internal pure returns (D256 memory) { return D256({value: getPartial(self.value, b.value, BASE)}); } function div(D256 memory self, D256 memory b) internal pure returns (D256 memory) { return D256({value: getPartial(self.value, BASE, b.value)}); } function equals(D256 memory self, D256 memory b) internal pure returns (bool) { return self.value == b.value; } function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 2; } function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 0; } function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) > 0; } function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) < 2; } function isZero(D256 memory self) internal pure returns (bool) { return self.value == 0; } function asUint256(D256 memory self) internal pure returns (uint256) { return self.value.div(BASE); } // ============ Core Methods ============ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) private pure returns (uint256) { return target.mul(numerator).div(denominator); } function compareTo(D256 memory a, D256 memory b) private pure returns (uint256) { if (a.value == b.value) { return 1; } return a.value > b.value ? 2 : 0; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.0; import "@uniswap/v2-periphery/contracts/interfaces/IWETH.sol"; library Constants { /// @notice the denominator for basis points granularity (10,000) uint256 public constant BASIS_POINTS_GRANULARITY = 10_000; uint256 public constant ONE_YEAR = 365.25 days; /// @notice WETH9 address IWETH public constant WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); /// @notice USD stand-in address address public constant USD = 0x1111111111111111111111111111111111111111; /// @notice Wei per ETH, i.e. 10**18 uint256 public constant ETH_GRANULARITY = 1e18; /// @notice number of decimals in ETH, 18 uint256 public constant ETH_DECIMALS = 18; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, 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 `from` to `to` 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 from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } pragma solidity >=0.5.0; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; }
@title a PCV Deposit interface for only balance getters @author Fei Protocol ----------- Getters -----------
interface IPCVDepositBalances { function balance() external view returns (uint256); function balanceReportedIn() external view returns (address); function resistantBalanceAndFei() external view returns (uint256, uint256); pragma solidity ^0.8.4; }
375,378
[ 1, 69, 453, 22007, 4019, 538, 305, 1560, 364, 1338, 11013, 23849, 225, 5782, 77, 4547, 300, 15392, 968, 5432, 300, 15392, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5831, 2971, 22007, 758, 1724, 38, 26488, 288, 203, 203, 565, 445, 11013, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 11013, 426, 1798, 382, 1435, 3903, 1476, 1135, 261, 2867, 1769, 203, 203, 565, 445, 400, 17175, 13937, 1876, 2954, 77, 1435, 3903, 1476, 1135, 261, 11890, 5034, 16, 2254, 5034, 1769, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xE83B94ECA0e76D9cE0119Fe6D37a539623C097D4/sources/contracts/staking/StakingPoolRewarder.sol
* @notice Calculates the amount withdrawable from vesting for a user. @dev Calculates the amount that can be withdrawn from the vesting schedule for a given user, the new claim time, and whether all amounts have been vested. If the amount or vesting schedule is zero, or the timestamp is before the start time or the current step time is before or equal to the last claim time, it returns zero. If all amounts have been vested, it returns the total amount to vest minus the amount already vested. If it's partially vested, it returns the amount to vest for the steps to vest. @param user Address of the user. @param poolId The id of the staking pool. @param timestamp Current timestamp. @return amount The amount withdrawable from vesting at this moment. @return newClaimTime The new claim time. @return allVested Whether all amounts have been vested./ All vested Partially vested
function _calculateWithdrawableFromVesting( address user, uint256 poolId, uint256 timestamp ) private view returns ( uint256 amount, uint256 newClaimTime, bool allVested ) { VestingSchedule memory vestingSchedule = vestingSchedules[user][poolId]; if (vestingSchedule.amount == 0) return (0, 0, false); if (timestamp <= uint256(vestingSchedule.startTime)) return (0, 0, false); uint256 currentStepTime = MathUpgradeable.min( timestamp .sub(uint256(vestingSchedule.startTime)) .div(uint256(vestingSchedule.step)) .mul(uint256(vestingSchedule.step)) .add(uint256(vestingSchedule.startTime)), uint256(vestingSchedule.endTime) ); if (currentStepTime <= uint256(vestingSchedule.lastClaimTime)) return (0, 0, false); uint256 totalSteps = uint256(vestingSchedule.endTime).sub(uint256(vestingSchedule.startTime)).div( vestingSchedule.step ); if (currentStepTime == uint256(vestingSchedule.endTime)) { uint256 stepsVested = uint256(vestingSchedule.lastClaimTime).sub(uint256(vestingSchedule.startTime)).div( vestingSchedule.step ); uint256 amountToVest = uint256(vestingSchedule.amount).sub( uint256(vestingSchedule.amount).div(totalSteps).mul(stepsVested) ); return (amountToVest, currentStepTime, true); uint256 stepsToVest = currentStepTime.sub(uint256(vestingSchedule.lastClaimTime)).div(vestingSchedule.step); uint256 amountToVest = uint256(vestingSchedule.amount).div(totalSteps).mul(stepsToVest); return (amountToVest, currentStepTime, false); } }
8,402,201
[ 1, 10587, 326, 3844, 598, 9446, 429, 628, 331, 10100, 364, 279, 729, 18, 225, 26128, 326, 3844, 716, 848, 506, 598, 9446, 82, 628, 326, 331, 10100, 4788, 364, 279, 864, 729, 16, 326, 394, 7516, 813, 16, 471, 2856, 777, 30980, 1240, 2118, 331, 3149, 18, 971, 326, 3844, 578, 331, 10100, 4788, 353, 3634, 16, 578, 326, 2858, 353, 1865, 326, 787, 813, 578, 326, 783, 2235, 813, 353, 1865, 578, 3959, 358, 326, 1142, 7516, 813, 16, 518, 1135, 3634, 18, 971, 777, 30980, 1240, 2118, 331, 3149, 16, 518, 1135, 326, 2078, 3844, 358, 331, 395, 12647, 326, 3844, 1818, 331, 3149, 18, 971, 518, 1807, 19976, 331, 3149, 16, 518, 1135, 326, 3844, 358, 331, 395, 364, 326, 6075, 358, 331, 395, 18, 225, 729, 5267, 434, 326, 729, 18, 225, 2845, 548, 1021, 612, 434, 326, 384, 6159, 2845, 18, 225, 2858, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 389, 11162, 1190, 9446, 429, 1265, 58, 10100, 12, 203, 3639, 1758, 729, 16, 203, 3639, 2254, 5034, 2845, 548, 16, 203, 3639, 2254, 5034, 2858, 203, 565, 262, 203, 3639, 3238, 203, 3639, 1476, 203, 3639, 1135, 261, 203, 5411, 2254, 5034, 3844, 16, 203, 5411, 2254, 5034, 394, 9762, 950, 16, 203, 5411, 1426, 777, 58, 3149, 203, 3639, 262, 203, 565, 288, 203, 3639, 776, 10100, 6061, 3778, 331, 10100, 6061, 273, 331, 10100, 27073, 63, 1355, 6362, 6011, 548, 15533, 203, 3639, 309, 261, 90, 10100, 6061, 18, 8949, 422, 374, 13, 327, 261, 20, 16, 374, 16, 629, 1769, 203, 3639, 309, 261, 5508, 1648, 2254, 5034, 12, 90, 10100, 6061, 18, 1937, 950, 3719, 327, 261, 20, 16, 374, 16, 629, 1769, 203, 203, 3639, 2254, 5034, 783, 4160, 950, 273, 2361, 10784, 429, 18, 1154, 12, 203, 5411, 2858, 203, 5411, 263, 1717, 12, 11890, 5034, 12, 90, 10100, 6061, 18, 1937, 950, 3719, 203, 5411, 263, 2892, 12, 11890, 5034, 12, 90, 10100, 6061, 18, 4119, 3719, 203, 5411, 263, 16411, 12, 11890, 5034, 12, 90, 10100, 6061, 18, 4119, 3719, 203, 5411, 263, 1289, 12, 11890, 5034, 12, 90, 10100, 6061, 18, 1937, 950, 13, 3631, 203, 5411, 2254, 5034, 12, 90, 10100, 6061, 18, 409, 950, 13, 203, 3639, 11272, 203, 203, 3639, 309, 261, 2972, 4160, 950, 1648, 2254, 5034, 12, 90, 10100, 6061, 18, 2722, 9762, 950, 3719, 327, 261, 20, 16, 374, 16, 629, 1769, 203, 203, 3639, 2254, 2 ]
// pragma solidity 0.5.10; pragma solidity >=0.4.22 <0.7.0; import "./lib/CompoundOracleInterface.sol"; import "./lib/UniswapExchangeInterface.sol"; import "./lib/UniswapFactoryInterface.sol"; import "../ERC20/IERC20.sol"; contract OptionsUtils { // defauls are for mainnet UniswapFactoryInterface public UNISWAP_FACTORY; CompoundOracleInterface public COMPOUND_ORACLE; constructor(address _uniswapFactory, address _compoundOracle) public { UNISWAP_FACTORY = UniswapFactoryInterface(_uniswapFactory); COMPOUND_ORACLE = CompoundOracleInterface(_compoundOracle); } // TODO: for now gets Uniswap, later update to get other exchanges function getExchange(address _token) public view returns (UniswapExchangeInterface) { if (address(UNISWAP_FACTORY.getExchange(_token)) == address(0)) { revert("No payout exchange"); } UniswapExchangeInterface exchange = UniswapExchangeInterface( UNISWAP_FACTORY.getExchange(_token) ); return exchange; } function isETH(IERC20 _ierc20) public pure returns (bool) { return _ierc20 == IERC20(0); } }
TODO: for now gets Uniswap, later update to get other exchanges
function getExchange(address _token) public view returns (UniswapExchangeInterface) { if (address(UNISWAP_FACTORY.getExchange(_token)) == address(0)) { revert("No payout exchange"); } UniswapExchangeInterface exchange = UniswapExchangeInterface( UNISWAP_FACTORY.getExchange(_token) ); return exchange; }
2,576,403
[ 1, 6241, 30, 364, 2037, 5571, 1351, 291, 91, 438, 16, 5137, 1089, 358, 336, 1308, 431, 6329, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 11688, 12, 2867, 389, 2316, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 984, 291, 91, 438, 11688, 1358, 13, 203, 565, 288, 203, 3639, 309, 261, 2867, 12, 2124, 5127, 59, 2203, 67, 16193, 18, 588, 11688, 24899, 2316, 3719, 422, 1758, 12, 20, 3719, 288, 203, 5411, 15226, 2932, 2279, 293, 2012, 7829, 8863, 203, 3639, 289, 203, 203, 3639, 1351, 291, 91, 438, 11688, 1358, 7829, 273, 1351, 291, 91, 438, 11688, 1358, 12, 203, 5411, 5019, 5127, 59, 2203, 67, 16193, 18, 588, 11688, 24899, 2316, 13, 203, 3639, 11272, 203, 203, 3639, 327, 7829, 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 ]
pragma solidity ^0.4.21; // File: contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: contracts/token/ERC20Basic.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); } // File: contracts/token/BasicToken.sol /** * @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); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: contracts/token/BurnableToken.sol /** * @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 { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(burner, _value); } } // File: contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts/token/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/token/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: contracts/token/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. * */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: contracts/token/SafeERC20.sol /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } // File: contracts/BitexToken.sol contract BitexToken is MintableToken, BurnableToken { using SafeERC20 for ERC20; string public constant name = "Bitex Coin"; string public constant symbol = "XBX"; uint8 public decimals = 18; bool public tradingStarted = false; // allow exceptional transfer fro sender address - this mapping can be modified only before the starting rounds mapping (address => bool) public transferable; /** * @dev modifier that throws if spender address is not allowed to transfer * and the trading is not enabled */ modifier allowTransfer(address _spender) { require(tradingStarted || transferable[_spender]); _; } /** * * Only the owner of the token smart contract can add allow token to be transfer before the trading has started * */ function modifyTransferableHash(address _spender, bool value) onlyOwner public { transferable[_spender] = value; } /** * @dev Allows the owner to enable the trading. */ function startTrading() onlyOwner public { tradingStarted = true; } /** * @dev Allows anyone to transfer the tokens once trading has started * @param _to the recipient address of the tokens. * @param _value number of tokens to be transfered. */ function transfer(address _to, uint _value) allowTransfer(msg.sender) public returns (bool){ return super.transfer(_to, _value); } /** * @dev Allows anyone to transfer the tokens once trading has started or if the spender is part of the mapping * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint _value) allowTransfer(_from) public returns (bool){ return super.transferFrom(_from, _to, _value); } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender when not paused. * @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 allowTransfer(_spender) returns (bool) { return super.approve(_spender, _value); } /** * Adding whenNotPaused */ function increaseApproval(address _spender, uint _addedValue) public allowTransfer(_spender) returns (bool success) { return super.increaseApproval(_spender, _addedValue); } /** * Adding whenNotPaused */ function decreaseApproval(address _spender, uint _subtractedValue) public allowTransfer(_spender) returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } // File: contracts/KnowYourCustomer.sol contract KnowYourCustomer is Ownable { // // with this structure // struct Contributor { // kyc cleared or not bool cleared; // % more for the contributor bring on board in 1/100 of % // 2.51 % --> 251 // 100% --> 10000 uint16 contributor_get; // eth address of the referer if any - the contributor address is the key of the hash address ref; // % more for the referrer uint16 affiliate_get; } mapping (address => Contributor) public whitelist; //address[] public whitelistArray; /** * @dev Populate the whitelist, only executed by whiteListingAdmin * whiteListingAdmin / */ function setContributor(address _address, bool cleared, uint16 contributor_get, uint16 affiliate_get, address ref) onlyOwner public{ // not possible to give an exorbitant bonus to be more than 100% (100x100 = 10000) require(contributor_get<10000); require(affiliate_get<10000); Contributor storage contributor = whitelist[_address]; contributor.cleared = cleared; contributor.contributor_get = contributor_get; contributor.ref = ref; contributor.affiliate_get = affiliate_get; } function getContributor(address _address) view public returns (bool, uint16, address, uint16 ) { return (whitelist[_address].cleared, whitelist[_address].contributor_get, whitelist[_address].ref, whitelist[_address].affiliate_get); } function getClearance(address _address) view public returns (bool) { return whitelist[_address].cleared; } } // File: contracts/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale { using SafeMath for uint256; // The token being sold MintableToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); token = createTokenContract(); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (MintableToken) { return new MintableToken(); } // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } // low level token purchase function // overrided to create custom buy function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.mul(rate); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // send ether to the fund collection wallet // overrided to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime ; bool nonZeroPurchase = msg.value != 0 ; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return now > endTime; } } // File: contracts/crowdsale/FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal{ } } // File: contracts/crowdsale/RefundVault.sol /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); function RefundVault(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { // this is this part that shall be removed, that way if called later it run the wallet transfer in any case // require(state == State.Active); state = State.Closed; emit Closed(); wallet.transfer(address(this).balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); emit Refunded(investor, depositedValue); } } // File: contracts/crowdsale/RefundableCrowdsale.sol /** * @title RefundableCrowdsale * @dev Extension of Crowdsale contract that adds a funding goal, and * the possibility of users getting a refund if goal is not met. * Uses a RefundVault as the crowdsale's vault. */ contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund vault used to hold funds while crowdsale is running RefundVault public vault; function RefundableCrowdsale(uint256 _goal) public { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; } // We're overriding the fund forwarding from Crowdsale. // In addition to sending the funds, we want to call // the RefundVault deposit function function forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } // if crowdsale is unsuccessful, investors can claim refunds here function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } // vault finalization task, called when owner calls finalize() function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } super.finalization(); } function goalReached() public view returns (bool) { return weiRaised >= goal; } } // File: contracts/BitexTokenCrowdSale.sol contract BitexTokenCrowdSale is Crowdsale, RefundableCrowdsale { using SafeMath for uint256; // number of participants uint256 public numberOfPurchasers = 0; // maximum tokens that can be minted in this crowd sale - initialised later by the constructor uint256 public maxTokenSupply = 0; // amounts of tokens already minted at the begining of this crowd sale - initialised later by the constructor uint256 public initialTokenAmount = 0; // Minimum amount to been able to contribute - initialised later by the constructor uint256 public minimumAmount = 0; // to compute the bonus bool public preICO; // the token BitexToken public token; // the kyc and affiliation management KnowYourCustomer public kyc; // remaining token are sent to this address address public walletRemaining; // this is the owner of the token, when the finalize function is called address public pendingOwner; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount, uint256 rate, address indexed referral, uint256 referredBonus ); event TokenPurchaseAffiliate(address indexed ref, uint256 amount ); function BitexTokenCrowdSale( uint256 _startTime, uint256 _endTime, uint256 _rate, uint256 _goal, uint256 _minimumAmount, uint256 _maxTokenSupply, address _wallet, BitexToken _token, KnowYourCustomer _kyc, bool _preICO, address _walletRemaining, address _pendingOwner ) FinalizableCrowdsale() RefundableCrowdsale(_goal) Crowdsale(_startTime, _endTime, _rate, _wallet) public { require(_minimumAmount >= 0); require(_maxTokenSupply > 0); require(_walletRemaining != address(0)); minimumAmount = _minimumAmount; maxTokenSupply = _maxTokenSupply; preICO = _preICO; walletRemaining = _walletRemaining; pendingOwner = _pendingOwner; kyc = _kyc; token = _token; // // record the amount of already minted token to been able to compute the delta with the tokens // minted during the pre sale, this is useful only for the pre - ico // if (preICO) { initialTokenAmount = token.totalSupply(); } } /** * * Create the token on the fly, owner is the contract, not the contract owner yet * **/ function createTokenContract() internal returns (MintableToken) { return token; } /** * @dev Calculates the amount of coins the buyer gets * @param weiAmount uint the amount of wei send to the contract * @return uint the amount of tokens the buyer gets */ function computeTokenWithBonus(uint256 weiAmount) public view returns(uint256) { uint256 tokens_ = 0; if (preICO) { if (weiAmount >= 50000 ether ) { tokens_ = weiAmount.mul(34).div(100); } else if (weiAmount<50000 ether && weiAmount >= 10000 ether) { tokens_ = weiAmount.mul(26).div(100); } else if (weiAmount<10000 ether && weiAmount >= 5000 ether) { tokens_ = weiAmount.mul(20).div(100); } else if (weiAmount<5000 ether && weiAmount >= 1000 ether) { tokens_ = weiAmount.mul(16).div(100); } }else{ if (weiAmount >= 50000 ether ) { tokens_ = weiAmount.mul(17).div(100); } else if (weiAmount<50000 ether && weiAmount >= 10000 ether) { tokens_ = weiAmount.mul(13).div(100); } else if (weiAmount<10000 ether && weiAmount >= 5000 ether) { tokens_ = weiAmount.mul(10).div(100); } else if (weiAmount<5000 ether && weiAmount >= 1000 ether) { tokens_ = weiAmount.mul(8).div(100); } } return tokens_; } // // override the claimRefund, so only user that have burn their token can claim for a refund // function claimRefund() public { // get the number of token from this sender uint256 tokenBalance = token.balanceOf(msg.sender); // the refund can be run only if the tokens has been burn require(tokenBalance == 0); // run the refund super.claimRefund(); } // transfer the token owner ship to the crowdsale contract // token.transferOwnership(currentIco); function finalization() internal { if (!preICO) { uint256 remainingTokens = maxTokenSupply.sub(token.totalSupply()); // mint the remaining amount and assign them to the beneficiary // --> here we can manage the vesting of the remaining tokens // token.mint(walletRemaining, remainingTokens); } // finalize the refundable inherited contract super.finalization(); if (!preICO) { // no more minting allowed - immutable token.finishMinting(); } // transfer the token owner ship from the contract address to the pendingOwner icoController token.transferOwnership(pendingOwner); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); // validate KYC here // if not part of kyc then throw bool cleared; uint16 contributor_get; address ref; uint16 affiliate_get; (cleared,contributor_get,ref,affiliate_get) = kyc.getContributor(beneficiary); // Transaction do not happen if the contributor is not KYC cleared require(cleared); // how much the contributor sent in wei uint256 weiAmount = msg.value; // Compute the number of tokens per wei using the rate uint256 tokens = weiAmount.mul(rate); // compute the amount of bonus, from the contribution amount uint256 bonus = computeTokenWithBonus(tokens); // compute the amount of token bonus for the contributor thank to his referral uint256 contributorGet = tokens.mul(contributor_get).div(100*100); // Sum it all tokens = tokens.add(bonus); tokens = tokens.add(contributorGet); // capped to a maxTokenSupply // make sure we can not mint more token than expected // require(((token.totalSupply()-initialTokenAmount) + tokens) <= maxTokenSupply); require((minted().add(tokens)) <= maxTokenSupply); // Mint the token token.mint(beneficiary, tokens); // log the event emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens, rate, ref, contributorGet); // update wei raised and number of purchasers weiRaised = weiRaised.add(weiAmount); numberOfPurchasers = numberOfPurchasers + 1; forwardFunds(); // ------------------------------------------------------------------ // compute the amount of token bonus that the referral get : // only if KYC cleared, only if enough tokens still available // ------------------------------------------------------------------ bool refCleared; (refCleared) = kyc.getClearance(ref); if (refCleared && ref != beneficiary) { // recompute the tokens amount using only the rate tokens = weiAmount.mul(rate); // compute the amount of token for the affiliate uint256 affiliateGet = tokens.mul(affiliate_get).div(100*100); // capped to a maxTokenSupply // make sure we can not mint more token than expected // we do not throw here as if this edge case happens it can be dealt with of chain // if ( (token.totalSupply()-initialTokenAmount) + affiliateGet <= maxTokenSupply) if ( minted().add(affiliateGet) <= maxTokenSupply) { // Mint the token token.mint(ref, affiliateGet); emit TokenPurchaseAffiliate(ref, tokens ); } } } // overriding Crowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment function validPurchase() internal view returns (bool) { // make sure we accept only the minimum contribution bool minAmount = (msg.value >= minimumAmount); // make sure that the purchase follow each rules to be valid return super.validPurchase() && minAmount; } function minted() public view returns(uint256) { return token.totalSupply().sub(initialTokenAmount); } // overriding Crowdsale#hasEnded to add cap logic // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { // bool capReached = (token.totalSupply() - initialTokenAmount) >= maxTokenSupply; // bool capReached = minted() >= maxTokenSupply; return super.hasEnded() || (minted() >= maxTokenSupply); } /** * * Admin functions only executed by owner: * Can change minimum amount * */ function changeMinimumAmount(uint256 _minimumAmount) onlyOwner public { require(_minimumAmount > 0); minimumAmount = _minimumAmount; } /** * * Admin functions only executed by owner: * Can change rate * * We do not use an oracle here as oracle need to be paid each time, and if the oracle is not responding * or hacked the rate could be detrimentally modified from an contributor perspective. * */ function changeRate(uint256 _rate) onlyOwner public { require(_rate > 0); rate = _rate; } /** * * Admin functions only called by owner: * Can change events dates * */ function changeDates(uint256 _startTime, uint256 _endTime) onlyOwner public { require(_startTime >= now); require(_endTime >= _startTime); startTime = _startTime; endTime = _endTime; } function modifyTransferableHash(address _spender, bool value) onlyOwner public { token.modifyTransferableHash(_spender,value); } /** * * Admin functions only called by owner: * Can transfer the owner ship of the vault, so a close can be called * only by the owner .... * */ function transferVault(address newOwner) onlyOwner public { vault.transferOwnership(newOwner); } }
* @title Burnable Token @dev Token that can be irreversibly burned (destroyed)./
contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) public { require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); emit Burn(burner, _value); } }
1,107,115
[ 1, 38, 321, 429, 3155, 225, 3155, 716, 848, 506, 9482, 266, 2496, 24755, 18305, 329, 261, 11662, 329, 2934, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 605, 321, 429, 1345, 353, 7651, 1345, 288, 203, 203, 565, 871, 605, 321, 12, 2867, 8808, 18305, 264, 16, 2254, 5034, 460, 1769, 203, 203, 203, 565, 445, 18305, 12, 11890, 5034, 389, 1132, 13, 1071, 288, 203, 3639, 2583, 24899, 1132, 1648, 324, 26488, 63, 3576, 18, 15330, 19226, 203, 203, 3639, 1758, 18305, 264, 273, 1234, 18, 15330, 31, 203, 3639, 324, 26488, 63, 70, 321, 264, 65, 273, 324, 26488, 63, 70, 321, 264, 8009, 1717, 24899, 1132, 1769, 203, 3639, 2078, 3088, 1283, 273, 2078, 3088, 1283, 18, 1717, 24899, 1132, 1769, 203, 3639, 3626, 605, 321, 12, 70, 321, 264, 16, 389, 1132, 1769, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]