file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
pragma solidity 0.4.24; /* * @author Ivan Borisov ([email protected]) (Github.com/pillardevelopment) */ 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) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } interface ERC20 { function transfer (address _beneficiary, uint256 _tokenAmount) external returns (bool); function transferFromICO(address _to, uint256 _value) external returns(bool); function balanceOf(address who) external view returns (uint256); } contract Ownable { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } } /********************************************************************************************************************* * @dev see https://github.com/ethereum/EIPs/issues/20 */ /*************************************************************************************************************/ contract WhalesburgCrowdsale is Ownable { using SafeMath for uint256; ERC20 public token; address public constant multisig = 0x5ac618ca87b61c1434325b6d60141c90f32590df; address constant bounty = 0x5ac618ca87b61c1434325b6d60141c90f32590df; address constant privateInvestors = 0x5ac618ca87b61c1434325b6d60141c90f32590df; address developers = 0xd7dadf6149FF75f76f36423CAD1E24c81847E85d; address constant founders = 0xd7dadf6149FF75f76f36423CAD1E24c81847E85d; uint256 public startICO = 1527989629; // Sunday, 03-Jun-18 16:00:00 UTC uint256 public endICO = 1530633600; // Tuesday, 03-Jul-18 16:00:00 UTC uint256 constant privateSaleTokens = 46988857; uint256 constant foundersReserve = 10000000; uint256 constant developmentReserve = 20500000; uint256 constant bountyReserve = 3500000; uint256 public individualRoundCap = 1250000000000000000; uint256 public constant hardCap = 1365000067400000000000; // 1365.0000674 ether uint256 public investors; uint256 public membersWhiteList; uint256 public constant buyPrice = 71800000000000; // 0.0000718 Ether bool public isFinalized = false; bool public distribute = false; uint256 public weisRaised; mapping (address => bool) public onChain; mapping (address => bool) whitelist; mapping (address => uint256) public moneySpent; address[] tokenHolders; event Finalized(); event Authorized(address wlCandidate, uint256 timestamp); event Revoked(address wlCandidate, uint256 timestamp); constructor(ERC20 _token) public { require(_token != address(0)); token = _token; } function setVestingAddress(address _newDevPool) public onlyOwner { developers = _newDevPool; } function distributionTokens() public onlyOwner { require(!distribute); token.transferFromICO(bounty, bountyReserve*1e18); token.transferFromICO(privateInvestors, privateSaleTokens*1e18); token.transferFromICO(developers, developmentReserve*1e18); token.transferFromICO(founders, foundersReserve*1e18); distribute = true; } /******************-- WhiteList --***************************/ function authorize(address _beneficiary) public onlyOwner { require(_beneficiary != address(0x0)); require(!isWhitelisted(_beneficiary)); whitelist[_beneficiary] = true; membersWhiteList++; emit Authorized(_beneficiary, now); } function addManyAuthorizeToWhitelist(address[] _beneficiaries) public onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { authorize(_beneficiaries[i]); } } function revoke(address _beneficiary) public onlyOwner { whitelist[_beneficiary] = false; emit Revoked(_beneficiary, now); } function isWhitelisted(address who) public view returns(bool) { return whitelist[who]; } function finalize() onlyOwner public { require(!isFinalized); require(now >= endICO || weisRaised >= hardCap); emit Finalized(); isFinalized = true; token.transferFromICO(owner, token.balanceOf(this)); } /***************************--Payable --*********************************************/ function () public payable { if(isWhitelisted(msg.sender)) { require(now >= startICO && now < endICO); currentSaleLimit(); moneySpent[msg.sender] = moneySpent[msg.sender].add(msg.value); require(moneySpent[msg.sender] <= individualRoundCap); sell(msg.sender, msg.value); weisRaised = weisRaised.add(msg.value); require(weisRaised <= hardCap); multisig.transfer(msg.value); } else { revert(); } } function currentSaleLimit() private { if(now >= startICO && now < startICO+7200) { individualRoundCap = 1250000000000000000; // 1.25 ETH } else if(now >= startICO+7200 && now < startICO+14400) { individualRoundCap = 3750000000000000000; // 3.75 ETH } else if(now >= startICO+14400 && now < endICO) { individualRoundCap = hardCap; // 1365 ether } else { revert(); } } function sell(address _investor, uint256 amount) private { uint256 _amount = amount.mul(1e18).div(buyPrice); token.transferFromICO(_investor, _amount); if (!onChain[msg.sender]) { tokenHolders.push(msg.sender); onChain[msg.sender] = true; } investors = tokenHolders.length; } }
*****************-- WhiteList --***************************/
function authorize(address _beneficiary) public onlyOwner { require(_beneficiary != address(0x0)); require(!isWhitelisted(_beneficiary)); whitelist[_beneficiary] = true; membersWhiteList++; emit Authorized(_beneficiary, now); }
10,727,160
[ 1, 413, 30233, 682, 1493, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 12229, 12, 2867, 389, 70, 4009, 74, 14463, 814, 13, 1071, 1338, 5541, 225, 288, 203, 202, 202, 6528, 24899, 70, 4009, 74, 14463, 814, 480, 1758, 12, 20, 92, 20, 10019, 203, 202, 202, 6528, 12, 5, 291, 18927, 329, 24899, 70, 4009, 74, 14463, 814, 10019, 203, 202, 202, 20409, 63, 67, 70, 4009, 74, 14463, 814, 65, 273, 638, 31, 203, 202, 202, 7640, 13407, 682, 9904, 31, 203, 202, 202, 18356, 6712, 1235, 24899, 70, 4009, 74, 14463, 814, 16, 2037, 1769, 203, 202, 97, 203, 202, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; // ---------------------------------------------------------------------------- // https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol // ---------------------------------------------------------------------------- library SafeMath { function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(a >= b); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // ---------------------------------------------------------------------------- // 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); } // ---------------------------------------------------------------------------- // https://github.com/ethereum/EIPs/issues/20 // ---------------------------------------------------------------------------- contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- contract BasicToken is ERC20Basic { using SafeMath for uint256; uint256 totalSupply_; mapping(address => uint256) balances; function totalSupply() public view returns (uint256) { return totalSupply_; } 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; } function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // ---------------------------------------------------------------------------- // https://github.com/ethereum/EIPs/issues/20 // ---------------------------------------------------------------------------- contract StandardToken is ERC20, BasicToken { mapping(address => mapping(address => uint256)) internal allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint256 _addedValue) public returns (bool) { allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // ---------------------------------------------------------------------------- // [email protected] // ---------------------------------------------------------------------------- contract OwnableToken is StandardToken { uint256 public constant OPERATOR_MAX_COUNT = 10; uint256 public operatorCount; address public owner; address[OPERATOR_MAX_COUNT] public operator; mapping(address => string) operatorName; event ChangeOwner(address indexed prevOwner, address indexed newOwner); event AddOperator(address indexed Operator, string name); event RemoveOperator(address indexed Operator); constructor() public { owner = msg.sender; operatorCount = 0; for (uint256 i = 0; i < OPERATOR_MAX_COUNT; i++) { operator[i] = address(0); } } modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyOperator() { require(msg.sender == owner || checkOperator(msg.sender) == true); _; } function checkOperator(address _operator) private view returns (bool) { for (uint256 i = 0; i < OPERATOR_MAX_COUNT; i++) { if (_operator == operator[i]) { return true; } } revert(); } function changeOwner(address _newOwner) external onlyOwner returns (bool) { require(_newOwner != address(0)); emit ChangeOwner(owner, _newOwner); owner = _newOwner; return true; } function addOperator(address _newOperator, string _name) external onlyOwner returns (bool) { require(_newOperator != address(0)); for (uint256 i = 0; i < OPERATOR_MAX_COUNT; i++) { if (_newOperator == operator[i]) { revert(); } } for (i = 0; i < OPERATOR_MAX_COUNT; i++) { if (operator[i] == address(0)) { operator[i] = _newOperator; operatorName[operator[i]] = _name; operatorCount++; emit AddOperator(_newOperator, _name); return true; } } revert(); } function removeOperator(address _operator) external onlyOwner returns (bool) { for (uint256 i = 0; i < OPERATOR_MAX_COUNT; i++) { if (_operator == operator[i]) { operatorName[operator[i]] = ""; operator[i] = address(0); operatorCount--; emit RemoveOperator(_operator); return true; } } revert(); } function getOperatorName(address _operator) external onlyOwner view returns (string) { return operatorName[_operator]; } } // ---------------------------------------------------------------------------- // [email protected] // ---------------------------------------------------------------------------- contract RestrictAmount is OwnableToken { mapping(address => uint256) public keepAmount; event LockAmount(address indexed addr, uint256 indexed amount); event DecLockAmount(address indexed addr, uint256 indexed amount); event UnlockAmount(address indexed addr); function lockAmount(address _address, uint256 _amount) external onlyOperator returns (bool) { keepAmount[_address] = _amount; if (_amount > 0) emit LockAmount(_address, _amount); else emit UnlockAmount(_address); } function decLockAmount(address _address, uint256 _amount) external onlyOperator returns (bool) { uint256 amount = _amount; if (amount > keepAmount[_address]) { amount = keepAmount[_address]; } keepAmount[_address] = keepAmount[_address].sub(amount); emit DecLockAmount(_address, _amount); } } // ---------------------------------------------------------------------------- // [email protected] // ---------------------------------------------------------------------------- contract LockAccount is OwnableToken { enum LOCK_STATE { unlock, lock, timeLock } struct lockInfo { LOCK_STATE lock; string reason; uint256 time; } mapping(address => lockInfo) lockAccount; event LockAddr(address indexed addr, string indexed reason, uint256 time); event UnlockAddr(address indexed addr); modifier checkLockAccount { if ( lockAccount[msg.sender].lock == LOCK_STATE.timeLock && lockAccount[msg.sender].time <= now ) { lockAccount[msg.sender].time = 0; lockAccount[msg.sender].reason = ""; lockAccount[msg.sender].lock = LOCK_STATE.unlock; emit UnlockAddr(msg.sender); } require( lockAccount[msg.sender].lock != LOCK_STATE.lock && lockAccount[msg.sender].lock != LOCK_STATE.timeLock); _; } function lockAddr(address _address, string _reason, uint256 _untilTime) public onlyOperator returns (bool) { require(_address != address(0)); require(_address != owner); require(_untilTime == 0 || _untilTime > now); if (_untilTime == 0) { lockAccount[_address].lock = LOCK_STATE.lock; } else { lockAccount[_address].lock = LOCK_STATE.timeLock; } lockAccount[_address].reason = _reason; lockAccount[_address].time = _untilTime; emit LockAddr(_address, _reason, _untilTime); return true; } function unlockAddr(address _address) public onlyOwner returns (bool) { lockAccount[_address].time = 0; lockAccount[_address].reason = ""; lockAccount[_address].lock = LOCK_STATE.unlock; emit UnlockAddr(_address); return true; } function getLockInfo(address _address) public returns (LOCK_STATE, string, uint256) { if ( lockAccount[_address].lock == LOCK_STATE.timeLock && lockAccount[_address].time <= now ) { lockAccount[_address].time = 0; lockAccount[_address].reason = ""; lockAccount[_address].lock = LOCK_STATE.unlock; } return ( lockAccount[_address].lock , lockAccount[_address].reason , lockAccount[_address].time ); } } // ---------------------------------------------------------------------------- // [email protected] // ---------------------------------------------------------------------------- contract TransferFromOperator is RestrictAmount, LockAccount { function transferToMany(address[] _to, uint256[] _value) onlyOperator checkLockAccount external returns (bool) { require(_to.length == _value.length); uint256 i; uint256 totValue = 0; for (i = 0; i < _to.length; i++) { require(_to[i] != address(0)); totValue = totValue.add(_value[i]); } require(balances[msg.sender].sub(keepAmount[msg.sender]) >= totValue); for (i = 0; i < _to.length; i++) { balances[msg.sender] = balances[msg.sender].sub(_value[i]); balances[_to[i]] = balances[_to[i]].add(_value[i]); emit Transfer(msg.sender, _to[i], _value[i]); } return true; } function transferFromOperator(address _to, uint256 _value) onlyOperator checkLockAccount public returns (bool) { require(_to != address(0)); require(balances[msg.sender].sub(keepAmount[msg.sender]) >= _value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } } // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- contract Pausable is OwnableToken { bool public paused = false; event Pause(); event Unpause(); modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() external onlyOwner whenNotPaused { paused = true; emit Pause(); } function unpause() external onlyOwner whenPaused { paused = false; emit Unpause(); } } // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- contract ControlledToken is Pausable, TransferFromOperator { function transfer(address _to, uint256 _value) public whenNotPaused checkLockAccount returns (bool) { require(balances[msg.sender].sub(keepAmount[msg.sender]) >= _value); return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused checkLockAccount returns (bool) { require(balances[_from].sub(keepAmount[_from]) >= _value); return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused checkLockAccount onlyOperator returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint256 _addedValue) public whenNotPaused checkLockAccount onlyOperator returns (bool) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint256 _subtractedValue) public whenNotPaused checkLockAccount onlyOperator returns (bool) { return super.decreaseApproval(_spender, _subtractedValue); } } // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- contract Burnable is OwnableToken { event Burn(address indexed burner, uint256 value); function burn(uint256 _value) onlyOwner public { require(_value <= balances[owner]); balances[owner] = balances[owner].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Transfer(owner, address(0), _value); emit Burn(msg.sender, _value); } } // ---------------------------------------------------------------------------- // https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol // ---------------------------------------------------------------------------- contract Mintable is OwnableToken { bool public mintingFinished = false; event Mint(address indexed to, uint256 value); event MintFinished(); modifier canMint() { require(!mintingFinished); _; } function mint(address _to, uint256 _value) onlyOwner canMint public returns (bool) { require(_to != address(0)); totalSupply_ = totalSupply_.add(_value); balances[_to] = balances[_to].add(_value); emit Transfer(address(0), _to, _value); emit Mint(_to, _value); return true; } function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // ---------------------------------------------------------------------------- // // ---------------------------------------------------------------------------- contract ManageSupplyToken is Mintable, Burnable { /* ... */ } // ---------------------------------------------------------------------------- // [email protected] // ---------------------------------------------------------------------------- contract PPCToken is ControlledToken, ManageSupplyToken { uint256 private constant INIT_SUPPLY = 1900000000; string public name = "PHILLIPS PAY COIN"; string public symbol = "PPC"; uint256 public decimals = 1; uint256 public initSupply = INIT_SUPPLY * (10 ** uint(decimals)); constructor() payable public { totalSupply_ = initSupply; balances[msg.sender] = totalSupply_; emit Transfer(0x0, msg.sender, totalSupply_); } }
---------------------------------------------------------------------------- [email protected] ----------------------------------------------------------------------------
contract PPCToken is ControlledToken, ManageSupplyToken { uint256 private constant INIT_SUPPLY = 1900000000; string public name = "PHILLIPS PAY COIN"; string public symbol = "PPC"; uint256 public decimals = 1; uint256 public initSupply = INIT_SUPPLY * (10 ** uint(decimals)); } constructor() payable public { totalSupply_ = initSupply; balances[msg.sender] = totalSupply_; emit Transfer(0x0, msg.sender, totalSupply_); } }
954,063
[ 1, 5802, 7620, 525, 318, 330, 36, 2431, 22, 710, 18, 832, 8879, 13849, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 453, 52, 1268, 969, 353, 8888, 1259, 1345, 16, 24247, 3088, 1283, 1345, 288, 203, 565, 2254, 5034, 3238, 5381, 12584, 67, 13272, 23893, 273, 5342, 12648, 31, 203, 565, 533, 1071, 508, 273, 315, 8939, 11465, 5857, 25095, 385, 6266, 14432, 203, 565, 533, 1071, 3273, 273, 315, 52, 3513, 14432, 203, 565, 2254, 5034, 1071, 15105, 273, 404, 31, 203, 565, 2254, 5034, 1071, 1208, 3088, 1283, 273, 12584, 67, 13272, 23893, 380, 261, 2163, 2826, 2254, 12, 31734, 10019, 203, 203, 97, 203, 565, 3885, 1435, 8843, 429, 1071, 288, 203, 3639, 2078, 3088, 1283, 67, 273, 1208, 3088, 1283, 31, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 2078, 3088, 1283, 67, 31, 203, 3639, 3626, 12279, 12, 20, 92, 20, 16, 1234, 18, 15330, 16, 2078, 3088, 1283, 67, 1769, 203, 565, 289, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x6afd85B5CF6ab3A1A5Eeac5e9D1dD488a8DF2D05/sources/project:/contracts/trust/IDSTrustService.sol
* @title IDSTrustService @dev An interface for a trust service which allows role-based access control for other contracts./SPDX-License-Identifier: UNLICENSED
interface IDSTrustService { function setServiceOwner( address _address /*onlyMaster*/ ) external returns (bool); function setRole( address _address, uint8 _role /*onlyMasterOrIssuer*/ ) external returns (bool); function removeRole( address _address /*onlyMasterOrIssuer*/ ) external returns (bool); function getRole(address _address) external view returns (uint8); function addEntity( string memory _name, address _owner /*onlyMasterOrIssuer onlyNewEntity onlyNewEntityOwner*/ ) external; function changeEntityOwner( string memory _name, address _oldOwner, address _newOwner /*onlyMasterOrIssuer onlyExistingEntityOwner*/ ) external; function addOperator( string memory _name, address _operator /*onlyEntityOwnerOrAbove onlyNewOperator*/ ) external; function removeOperator( string memory _name, address _operator /*onlyEntityOwnerOrAbove onlyExistingOperator*/ ) external; function addResource( string memory _name, address _resource /*onlyMasterOrIssuer onlyExistingEntity onlyNewResource*/ ) external; function removeResource( string memory _name, address _resource /*onlyMasterOrIssuer onlyExistingResource*/ ) external; function getEntityByOwner(address _owner) external view returns (string memory); function getEntityByOperator(address _operator) external view returns (string memory); function getEntityByResource(address _resource) external view returns (string memory); function isResourceOwner(address _resource, address _owner) external view returns (bool); function isResourceOperator(address _resource, address _operator) external view returns (bool); }
9,477,676
[ 1, 734, 882, 86, 641, 1179, 225, 1922, 1560, 364, 279, 10267, 1156, 1492, 5360, 2478, 17, 12261, 2006, 3325, 364, 1308, 20092, 18, 19, 3118, 28826, 17, 13211, 17, 3004, 30, 5019, 6065, 1157, 18204, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 1599, 882, 86, 641, 1179, 288, 203, 565, 445, 30000, 5541, 12, 203, 3639, 1758, 389, 2867, 1748, 3700, 7786, 5549, 203, 565, 262, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 444, 2996, 12, 203, 3639, 1758, 389, 2867, 16, 203, 3639, 2254, 28, 389, 4615, 1748, 3700, 7786, 1162, 16667, 5549, 203, 565, 262, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 1206, 2996, 12, 203, 3639, 1758, 389, 2867, 1748, 3700, 7786, 1162, 16667, 5549, 203, 565, 262, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 15673, 12, 2867, 389, 2867, 13, 3903, 1476, 1135, 261, 11890, 28, 1769, 203, 203, 565, 445, 527, 1943, 12, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 1758, 389, 8443, 1748, 3700, 7786, 1162, 16667, 1338, 1908, 1943, 1338, 1908, 1943, 5541, 5549, 203, 565, 262, 3903, 31, 203, 203, 565, 445, 2549, 1943, 5541, 12, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 1758, 389, 1673, 5541, 16, 203, 3639, 1758, 389, 2704, 5541, 1748, 3700, 7786, 1162, 16667, 1338, 9895, 1943, 5541, 5549, 203, 565, 262, 3903, 31, 203, 203, 565, 445, 527, 5592, 12, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 1758, 389, 9497, 1748, 3700, 1943, 5541, 1162, 25477, 1338, 1908, 5592, 5549, 203, 565, 262, 3903, 31, 203, 203, 565, 445, 1206, 5592, 12, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 1758, 389, 9497, 1748, 3700, 1943, 5541, 1162, 25477, 1338, 9895, 5592, 5549, 203, 565, 262, 3903, 31, 2 ]
./full_match/80001/0xc2d2F9F48937a6F04a73Ff97B466c9b392E785C1/sources/contracts/2_Owner.sol
* @dev Return challenger address @return address of challenger/
function getChallenger() external view returns (address) { return challenger; }
5,668,180
[ 1, 990, 462, 7862, 693, 1758, 327, 1758, 434, 462, 7862, 693, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 782, 7862, 693, 1435, 3903, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 462, 7862, 693, 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 ]
./partial_match/1/0xD898456E39A461B102Ce4626Aac191582C38Acb6/sources/contracts/vault/AssetVault.sol
* @title AssetVault @author Non-Fungible Technologies, Inc. The Asset Vault is a vault for the storage of collateralized assets. Designed for one-time use, like a piggy bank. Once withdrawals are enabled, and the bank is broken, the vault can no longer be used or transferred. It starts in a deposit-only state. Funds cannot be withdrawn at this point. When the owner calls "enableWithdraw()", the state is set to a withdrawEnabled state. Withdraws cannot be disabled once enabled. This restriction protects integrations and purchasers of AssetVaults from unexpected withdrawal and frontrunning attacks. For example: someone buys an AV assuming it contains token X, but I withdraw token X immediately before the sale concludes. @dev Asset Vaults support arbitrary external calls by either: - the current owner of the vault - someone who the current owner "delegates" through the ICallDelegator interface This is to enable airdrop claims by borrowers during loans and other forms of NFT utility. In practice, LoanCore delegates to the borrower during the period of an open loan. Arcade.xyz maintains an allowed and restricted list of calls to balance between utility and security./ ============================================ STATE ============================================== ========================================== CONSTRUCTOR ===========================================
contract AssetVault is IAssetVault, OwnableERC721, Initializable, ERC1155Holder, ERC721Holder, ReentrancyGuard { using Address for address; using Address for address payable; using SafeERC20 for IERC20; bool public override withdrawEnabled; ICallWhitelist public override whitelist; import { AV_WithdrawsDisabled, AV_WithdrawsEnabled, AV_AlreadyInitialized, AV_CallDisallowed, AV_NonWhitelistedCall } from "../errors/Vault.sol"; constructor() { withdrawEnabled = true; OwnableERC721._setNFT(msg.sender); } function initialize(address _whitelist) external override initializer { if (withdrawEnabled || ownershipToken != address(0)) revert AV_AlreadyInitialized(ownershipToken); OwnableERC721._setNFT(msg.sender); whitelist = ICallWhitelist(_whitelist); } function owner() public view override returns (address ownerAddress) { return OwnableERC721.owner(); } function enableWithdraw() external override onlyOwner onlyWithdrawDisabled { withdrawEnabled = true; emit WithdrawEnabled(msg.sender); } function withdrawERC20(address token, address to) external override onlyOwner onlyWithdrawEnabled { uint256 balance = IERC20(token).balanceOf(address(this)); IERC20(token).safeTransfer(to, balance); emit WithdrawERC20(msg.sender, token, to, balance); } function withdrawERC721( address token, uint256 tokenId, address to ) external override onlyOwner onlyWithdrawEnabled { IERC721(token).safeTransferFrom(address(this), to, tokenId); emit WithdrawERC721(msg.sender, token, to, tokenId); } function withdrawERC1155( address token, uint256 tokenId, address to ) external override onlyOwner onlyWithdrawEnabled { uint256 balance = IERC1155(token).balanceOf(address(this), tokenId); IERC1155(token).safeTransferFrom(address(this), to, tokenId, balance, ""); emit WithdrawERC1155(msg.sender, token, to, tokenId, balance); } function withdrawETH(address to) external override onlyOwner onlyWithdrawEnabled nonReentrant { uint256 balance = address(this).balance; payable(to).sendValue(balance); emit WithdrawETH(msg.sender, to, balance); } function withdrawPunk( address punks, uint256 punkIndex, address to ) external override onlyOwner onlyWithdrawEnabled { IPunks(punks).transferPunk(to, punkIndex); emit WithdrawPunk(msg.sender, punks, to, punkIndex); } function call(address to, bytes calldata data) external override onlyWithdrawDisabled nonReentrant { if (msg.sender != owner() && !ICallDelegator(owner()).canCallOn(msg.sender, address(this))) revert AV_CallDisallowed(msg.sender); if (!whitelist.isWhitelisted(to, bytes4(data[:4]))) revert AV_NonWhitelistedCall(to, bytes4(data[:4])); to.functionCall(data); emit Call(msg.sender, to, data); } modifier onlyWithdrawEnabled() { if (!withdrawEnabled) revert AV_WithdrawsDisabled(); _; } modifier onlyWithdrawDisabled() { if (withdrawEnabled) revert AV_WithdrawsEnabled(); _; } receive() external payable {} }
15,722,449
[ 1, 6672, 12003, 225, 3858, 17, 42, 20651, 1523, 30960, 27854, 16, 15090, 18, 1021, 10494, 17329, 353, 279, 9229, 364, 326, 2502, 434, 4508, 2045, 287, 1235, 7176, 18, 29703, 329, 364, 1245, 17, 957, 999, 16, 3007, 279, 293, 360, 7797, 11218, 18, 12419, 598, 9446, 1031, 854, 3696, 16, 471, 326, 11218, 353, 12933, 16, 326, 9229, 848, 1158, 7144, 506, 1399, 578, 906, 4193, 18, 2597, 2542, 316, 279, 443, 1724, 17, 3700, 919, 18, 478, 19156, 2780, 506, 598, 9446, 82, 622, 333, 1634, 18, 5203, 326, 3410, 4097, 315, 7589, 1190, 9446, 1435, 3113, 326, 919, 353, 444, 358, 279, 598, 9446, 1526, 919, 18, 3423, 9446, 87, 2780, 506, 5673, 3647, 3696, 18, 1220, 9318, 17151, 87, 11301, 1012, 471, 5405, 343, 345, 414, 434, 10494, 12003, 87, 628, 9733, 598, 9446, 287, 471, 284, 1949, 313, 318, 2093, 28444, 18, 2457, 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, 10494, 12003, 353, 467, 6672, 12003, 16, 14223, 6914, 654, 39, 27, 5340, 16, 10188, 6934, 16, 4232, 39, 2499, 2539, 6064, 16, 4232, 39, 27, 5340, 6064, 16, 868, 8230, 12514, 16709, 288, 203, 565, 1450, 5267, 364, 1758, 31, 203, 565, 1450, 5267, 364, 1758, 8843, 429, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 203, 565, 1426, 1071, 3849, 598, 9446, 1526, 31, 203, 203, 565, 467, 1477, 18927, 1071, 3849, 10734, 31, 203, 203, 203, 203, 5666, 288, 15068, 67, 1190, 9446, 87, 8853, 16, 15068, 67, 1190, 9446, 87, 1526, 16, 15068, 67, 9430, 11459, 16, 15068, 67, 1477, 1669, 8151, 16, 15068, 67, 3989, 18927, 329, 1477, 289, 628, 315, 6216, 4324, 19, 12003, 18, 18281, 14432, 203, 565, 3885, 1435, 288, 203, 3639, 598, 9446, 1526, 273, 638, 31, 203, 3639, 14223, 6914, 654, 39, 27, 5340, 6315, 542, 50, 4464, 12, 3576, 18, 15330, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 4046, 12, 2867, 389, 20409, 13, 3903, 3849, 12562, 288, 203, 3639, 309, 261, 1918, 9446, 1526, 747, 23178, 1345, 480, 1758, 12, 20, 3719, 15226, 15068, 67, 9430, 11459, 12, 995, 12565, 1345, 1769, 203, 3639, 14223, 6914, 654, 39, 27, 5340, 6315, 542, 50, 4464, 12, 3576, 18, 15330, 1769, 203, 3639, 10734, 273, 467, 1477, 18927, 24899, 20409, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 3410, 1435, 1071, 1476, 3849, 1135, 261, 2867, 3410, 1887, 13, 288, 203, 3639, 2 ]
pragma solidity 0.5.13; import "./interfaces/IERC721Full.sol"; import "./utils/SafeMath.sol"; /// @title Augur Markets interface /// @notice Gets the winner of each market from Augur interface IMarket { function getWinningPayoutNumerator(uint256 _outcome) external view returns (uint256); } /// @title Dai contract interface /// @notice Various cash functions interface Cash { function approve(address _spender, uint256 _amount) external returns (bool); function balanceOf(address _ownesr) external view returns (uint256); function faucet(uint256 _amount) external; function transfer(address _to, uint256 _amount) external returns (bool); function transferFrom(address _from, address _to, uint256 _amount) external returns (bool); } /// @title Augur OICash interface /// @notice adding or removing open interest to secure the Augur Oracle interface OICash { function deposit(uint256 _amount) external returns (bool); function withdraw(uint256 _amount) external returns (bool); } //TODO: replace completesets with OICash //TODO: update design pattens to take into account the recent changes //TODO: change front end to only approve the same amount that is being sent //TODO: add test where someone calls exit and they are not the current owner //TODO: add tests where current owner calls newRental twice // ^ will also need to figure out how to pass this number in the correct format because decimal // ^ does not seem to work for more than 100 dai, it needs big number /// @title Harber /// @author Andrew Stanger contract Harber { using SafeMath for uint256; /// NUMBER OF TOKENS /// @dev also equals number of markets on augur uint256 constant public numberOfTokens = 20; /// CONTRACT VARIABLES /// ERC721: IERC721Full public team; /// Augur contracts: IMarket[numberOfTokens] public market; OICash public augur; Cash public cash; /// UINTS, ADDRESSES, BOOLS /// @dev my whiskey fund, for my 1% cut address private andrewsAddress; /// @dev the addresses of the various Augur binary markets. One market for each token. Initiated in the constructor and does not change. address[numberOfTokens] public marketAddresses; /// @dev in attodai (so $100 = 100000000000000000000) uint256[numberOfTokens] public price; /// @dev an easy way to track the above across all tokens. It should always increment at the same time as the above increments. uint256 public totalCollected; /// @dev used to determine the rent due. Rent is due for the period (now - timeLastCollected), at which point timeLastCollected is set to now. uint256[numberOfTokens] public timeLastCollected; /// @dev when a token was bought. used only for front end 'owned since' section. Rent collection only needs timeLastCollected. uint256[numberOfTokens] public timeAcquired; /// @dev tracks the position of the current owner in the ownerTracker mapping uint256[numberOfTokens] public currentOwnerIndex; /// WINNING OUTCOME VARIABLES /// @dev start with invalid winning outcome uint256 public winningOutcome = 42069; //// @dev so the function to manually set the winner can only be called long after /// @dev ...it should have resolved via Augur. Must be public so others can verify it is accurate. uint256 public marketExpectedResolutionTime; /// MARKET RESOLUTION VARIABLES /// @dev step1: bool public marketsResolved = false; // must be false for step1, true for step2 bool public marketsResolvedWithoutErrors = false; // set in step 1. If true, normal payout. If false, return all funds /// @dev step 2: bool public step2Complete = false; // must be false for step2, true for complete /// @dev step 3: bool public step3Complete = false; // must be false for step2, true for complete /// @dev complete: uint256 public daiAvailableToDistribute; /// STRUCTS struct purchase { address owner; uint256 price; } /// MAPPINGS /// @dev keeps track of all previous owners of a token, including the price, so that if the current owner's deposit runs out, /// @dev ...ownership can be reverted to a previous owner with the previous price. Index 0 is NOT used, this tells the contract to foreclose. /// @dev this does NOT keep a reliable list of all owners, if it reverts to a previous owner then the next owner will overwrite the owner that was in that slot. /// @dev the variable currentOwnerIndex is used to track the location of the current owner. mapping (uint256 => mapping (uint256 => purchase) ) public ownerTracker; /// @dev how many seconds each user has held each token for, for determining winnings mapping (uint256 => mapping (address => uint256) ) public timeHeld; /// @dev sums all the timeHelds for each token. Not required, but saves on gas when paying out. Should always increment at the same time as timeHeld mapping (uint256 => uint256) public totalTimeHeld; /// @dev keeps track of all the deposits for each token, for each owner. Unused deposits are not returned automatically when there is a new buyer. /// @dev they can be withdrawn manually however. Unused deposits are returned automatically upon resolution of the market mapping (uint256 => mapping (address => uint256) ) public deposits; /// @dev keeps track of all the rent paid by each user. So that it can be returned in case of an invalid market outcome. Only required in this instance. mapping (address => uint256) public collectedPerUser; ////////////// CONSTRUCTOR ////////////// constructor(address _andrewsAddress, address _addressOfToken, address _addressOfCashContract, address[numberOfTokens] memory _addressesOfMarkets, address _addressOfOICashContract, address _addressOfMainAugurContract, uint _marketExpectedResolutionTime) public { marketExpectedResolutionTime = _marketExpectedResolutionTime; andrewsAddress = _andrewsAddress; marketAddresses = _addressesOfMarkets; // this is to make the market addresses public so users can check the actual augur markets for themselves // external contract variables: team = IERC721Full(_addressOfToken); cash = Cash(_addressOfCashContract); augur = OICash(_addressOfOICashContract); // initialise arrays for (uint i = 0; i < numberOfTokens; i++) { currentOwnerIndex[i]=0; market[i] = IMarket(_addressesOfMarkets[i]); } // approve Augur contract to transfer this contract's dai cash.approve(_addressOfMainAugurContract,(2**256)-1); } event LogNewRental(address indexed newOwner, uint256 indexed newPrice, uint256 indexed tokenId); event LogPriceChange(uint256 indexed newPrice, uint256 indexed tokenId); event LogForeclosure(address indexed prevOwner, uint256 indexed tokenId); event LogRentCollection(uint256 indexed rentCollected, uint256 indexed tokenId); event LogReturnToPreviousOwner(uint256 indexed tokenId, address indexed previousOwner); event LogDepositWithdrawal(uint256 indexed daiWithdrawn, uint256 indexed tokenId, address indexed returnedTo); event LogDepositIncreased(uint256 indexed daiDeposited, uint256 indexed tokenId, address indexed sentBy); event LogExit(uint256 indexed tokenId); event LogStep1Complete(bool indexed didAugurMarketsResolve, uint256 indexed winningOutcome, bool indexed didAugurMarketsResolveCorrectly); event LogStep2Complete(uint256 indexed daiAvailableToDistribute); event LogWinningsPaid(address indexed paidTo, uint256 indexed amountPaid); event LogRentReturned(address indexed returnedTo, uint256 indexed amountReturned); event LogAndrewPaid(uint256 indexed additionsToWhiskeyFund); ////////////// MODIFIERS ////////////// /// @notice prevents functions from being interacted with after the end of the competition /// @dev should be on all public/external 'ordinary course of business' functions modifier notResolved() { require(marketsResolved == false); _; } /// @notice checks the team exists modifier tokenExists(uint256 _tokenId) { require(_tokenId >= 0 && _tokenId < numberOfTokens, "This token does not exist"); _; } /// @notice what it says on the tin modifier amountNotZero(uint256 _dai) { require(_dai > 0, "Amount must be above zero"); _; } ////////////// VIEW FUNCTIONS ////////////// /// @dev used in testing only function getOwnerTrackerPrice(uint256 _tokenId, uint256 _index) public view returns (uint256) { return (ownerTracker[_tokenId][_index].price); } /// @dev used in testing only function getOwnerTrackerAddress(uint256 _tokenId, uint256 _index) public view returns (address) { return (ownerTracker[_tokenId][_index].owner); } /// @dev called in collectRent function, and various other view functions function rentOwed(uint256 _tokenId) public view returns (uint256 augurFundsDue) { return price[_tokenId].mul(now.sub(timeLastCollected[_tokenId])).div(1 days); } /// @dev for front end only /// @return how much the current owner has deposited function liveDepositAbleToWithdraw(uint256 _tokenId) public view returns (uint256) { uint256 _rentOwed = rentOwed(_tokenId); address _currentOwner = team.ownerOf(_tokenId); if(_rentOwed >= deposits[_tokenId][_currentOwner]) { return 0; } else { return deposits[_tokenId][_currentOwner].sub(_rentOwed); } } /// @dev for front end only /// @return how much the current user has deposited (note: user not owner) function userDepositAbleToWithdraw(uint256 _tokenId) public view returns (uint256) { uint256 _rentOwed = rentOwed(_tokenId); address _currentOwner = team.ownerOf(_tokenId); if(_currentOwner == msg.sender) { if(_rentOwed >= deposits[_tokenId][msg.sender]) { return 0; } else { return deposits[_tokenId][msg.sender].sub(_rentOwed); } } else { return deposits[_tokenId][msg.sender]; } } /// @dev for front end only /// @return estimated rental expiry time function rentalExpiryTime(uint256 _tokenId) public view returns (uint256) { uint256 pps; pps = price[_tokenId].div(1 days); if (pps == 0) { return now; //if price is so low that pps = 0 just return current time as a fallback } else { return now + liveDepositAbleToWithdraw(_tokenId).div(pps); } } ////////////// AUGUR FUNCTIONS ////////////// // * internal * /// @notice send the Dai to Augur function _augurDeposit(uint256 _rentOwed) internal { augur.deposit(_rentOwed); } // * internal * /// @notice receive the Dai back from Augur function _augurWithdraw() internal { augur.withdraw(totalCollected); } // * internal * /// @notice THIS FUNCTION HAS NOT BEEN TESTED ON AUGUR YET /// @notice checks if all X (x = number of tokens = number of teams) markets have resolved to either yes, no, or invalid /// @return true if yes, false if no function _haveAllAugurMarketsResolved() internal view returns(bool) { uint256 _resolvedOutcomesCount = 0; for (uint i = 0; i < numberOfTokens; i++) { // binary market has three outcomes: 0 (invalid), 1 (yes), 2 (no) if (market[i].getWinningPayoutNumerator(0) > 0 || market[i].getWinningPayoutNumerator(1) > 0 || market[i].getWinningPayoutNumerator(2) > 0 ) { _resolvedOutcomesCount = _resolvedOutcomesCount.add(1); } } // returns true if all resolved, false otherwise return (_resolvedOutcomesCount == numberOfTokens); } // * internal * /// @notice THIS FUNCTION HAS NOT BEEN TESTED ON AUGUR YET /// @notice checks if all markets have resolved without conflicts or errors /// @return true if yes, false if no /// @dev this function will also set the winningOutcome variable function _haveAllAugurMarketsResolvedWithoutErrors() internal returns(bool) { uint256 _winningOutcomesCount = 0; uint256 _invalidOutcomesCount = 0; for (uint i = 0; i < numberOfTokens; i++) { if (market[i].getWinningPayoutNumerator(0) > 0) { _invalidOutcomesCount = _invalidOutcomesCount.add(1); } if (market[i].getWinningPayoutNumerator(1) > 0) { winningOutcome = i; // <- the winning outcome (a global variable) is set here _winningOutcomesCount = _winningOutcomesCount.add(1); } } return (_winningOutcomesCount == 1 && _invalidOutcomesCount == 0); } ////////////// DAI CONTRACT FUNCTIONS ////////////// // * internal * /// @notice common function for all outgoing DAI transfers function _sendCash(address _to, uint256 _amount) internal { require(cash.transfer(_to,_amount)); } // * internal * /// @notice common function for all incoming DAI transfers function _receiveCash(address _from, uint256 _amount) internal { require(cash.transferFrom(_from, address(this), _amount)); } // * internal * /// @return DAI balance of the contract /// @dev this is used to know how much exists to payout to winners function _getContractsCashBalance() internal view returns (uint256) { return cash.balanceOf(address(this)); } ////////////// MARKET RESOLUTION FUNCTIONS ////////////// /// @notice the first of three functions which must be called, one after the other, to conclude the competition /// @notice winnings can be paid out (or funds returned) only when these two steps are completed /// @notice this function checks whether the Augur markets have resolved, and if yes, whether they resolved correct or not /// @dev they are split into two sections due to the presence of step1BemergencyExit and step1CcircuitBreaker /// @dev can be called by anyone /// @dev can be called multiple times, but only once after markets have indeed resolved /// @dev the two arguments passed are for testing only function step1checkMarketsResolved() external { require(marketsResolved == false, "Step1 can only be completed once"); // first check if all X markets have all resolved one way or the other if (_haveAllAugurMarketsResolved()) { // do a final rent collection before the contract is locked down collectRentAllTokens(); // lock everything down marketsResolved = true; // now check if they all resolved without errors. It is set to false upon contract initialisation // this function also sets winningOutcome if there is one if (_haveAllAugurMarketsResolvedWithoutErrors()) { marketsResolvedWithoutErrors = true; } emit LogStep1Complete(true, winningOutcome, marketsResolvedWithoutErrors); } } /// @notice emergency function in case the augur markets never resolve for whatever reason /// @notice returns all funds to all users /// @notice can only be called 6 months after augur markets should have ended function step1BemergencyExit() external { require(marketsResolved == false, "Step1 can only be completed once"); require(now > (marketExpectedResolutionTime + 15778800), "Must wait 6 months for Augur Oracle"); collectRentAllTokens(); marketsResolved = true; emit LogStep1Complete(false, winningOutcome, false); } /// @notice Same as above, except that only I can call it, and I can call it whenever /// @notice to be clear, this only allows me to return all funds. I can not set a winner. function step1CcircuitBreaker() external { require(marketsResolved == false, "Step1 can only be completed once"); require(msg.sender == andrewsAddress, "Only owner can call this"); collectRentAllTokens(); marketsResolved = true; emit LogStep1Complete(false, winningOutcome, false); } /// @notice the second of the three functions which must be called, one after the other, to conclude the competition /// @dev gets funds back from Augur, gets the available funds for distribution /// @dev can be called by anyone, but only once function step2withdrawFromAugur() external { require(marketsResolved == true, "Must wait for market resolution"); require(step2Complete == false, "Step2 should only be run once"); step2Complete = true; uint256 _balanceBefore = _getContractsCashBalance(); _augurWithdraw(); uint256 _balanceAfter = _getContractsCashBalance(); // daiAvailableToDistribute therefore does not include unused deposits daiAvailableToDistribute = _balanceAfter.sub(_balanceBefore); emit LogStep2Complete(daiAvailableToDistribute); } /// @notice the final of the three functions which must be called, one after the other, to conclude the competition /// @notice pays me my 1% if markets resolved correctly. If not I don't deserve shit /// @dev this was originally included within step3 but it was modifed so that ineraction with Dai contract happened at the end function step3payAndrew() external { require(step2Complete == true, "Must wait for market resolution"); require(step3Complete == false, "Step3 should only be run once"); step3Complete = true; if (marketsResolvedWithoutErrors) { uint256 _andrewsWellEarntMonies = daiAvailableToDistribute.div(100); daiAvailableToDistribute = daiAvailableToDistribute.sub(_andrewsWellEarntMonies); _sendCash(andrewsAddress,_andrewsWellEarntMonies); emit LogAndrewPaid(_andrewsWellEarntMonies); } } /// @notice the final function of the competition resolution process. Pays out winnings, or returns funds, as necessary /// @dev users pull dai into their account. Replaces previous push vesion which required looping over unbounded mapping. function complete() external { require(step3Complete == true, "Step3 must be completed first"); if (marketsResolvedWithoutErrors) { _payoutWinnings(); } else { _returnRent(); } } // * internal * /// @notice pays winnings to the winners /// @dev must be internal and only called by complete function _payoutWinnings() internal { uint256 _winnersTimeHeld = timeHeld[winningOutcome][msg.sender]; if (_winnersTimeHeld > 0) { timeHeld[winningOutcome][msg.sender] = 0; // otherwise they can keep paying themselves over and over uint256 _numerator = daiAvailableToDistribute.mul(_winnersTimeHeld); uint256 _winningsToTransfer = _numerator.div(totalTimeHeld[winningOutcome]); _sendCash(msg.sender, _winningsToTransfer); emit LogWinningsPaid(msg.sender, _winningsToTransfer); } } // * internal * /// @notice returns all funds to users in case of invalid outcome /// @dev must be internal and only called by complete function _returnRent() internal { uint256 _rentCollected = collectedPerUser[msg.sender]; if (_rentCollected > 0) { collectedPerUser[msg.sender] = 0; // otherwise they can keep paying themselves over and over uint256 _numerator = daiAvailableToDistribute.mul(_rentCollected); uint256 _rentToToReturn = _numerator.div(totalCollected); _sendCash(msg.sender, _rentToToReturn); emit LogRentReturned(msg.sender, _rentToToReturn); } } /// @notice withdraw full deposit after markets have resolved /// @dev the other withdraw deposit functions are locked when markets have resolved so must use this one /// @dev ... which can only be called if markets have resolved. This function is also different in that it does /// @dev ... not attempt to collect rent or transfer ownership to a previous owner function withdrawDepositAfterResolution() external { require(marketsResolved == true, "step1 must be completed first"); for (uint i = 0; i < numberOfTokens; i++) { uint256 _depositToReturn = deposits[i][msg.sender]; if (_depositToReturn > 0) { deposits[i][msg.sender] = 0; _sendCash(msg.sender, _depositToReturn); emit LogDepositWithdrawal(_depositToReturn, i, msg.sender); } } } ////////////// ORDINARY COURSE OF BUSINESS FUNCTIONS ////////////// /// @notice collects rent for all tokens /// @dev makes it easy for me to call whenever I want to keep people paying their rent, thus cannot be internal /// @dev cannot be external because it is called within the step1 functions, therefore public function collectRentAllTokens() public notResolved() { for (uint i = 0; i < numberOfTokens; i++) { _collectRent(i); } } /// @notice collects rent for a specific token /// @dev also calculates and updates how long the current user has held the token for /// @dev called frequently internally, so cant be external. /// @dev is not a problem if called externally, but making internal to save gas function _collectRent(uint256 _tokenId) internal notResolved() { //only collect rent if the token is owned (ie, if owned by the contract this implies unowned) if (team.ownerOf(_tokenId) != address(this)) { uint256 _rentOwed = rentOwed(_tokenId); address _currentOwner = team.ownerOf(_tokenId); uint256 _timeOfThisCollection; if (_rentOwed >= deposits[_tokenId][_currentOwner]) { // run out of deposit. Calculate time it was actually paid for, then revert to previous owner _timeOfThisCollection = timeLastCollected[_tokenId].add(((now.sub(timeLastCollected[_tokenId])).mul(deposits[_tokenId][_currentOwner]).div(_rentOwed))); _rentOwed = deposits[_tokenId][_currentOwner]; // take what's left _revertToPreviousOwner(_tokenId); } else { // normal collection _timeOfThisCollection = now; } // decrease deposit by rent owed deposits[_tokenId][_currentOwner] = deposits[_tokenId][_currentOwner].sub(_rentOwed); // the 'important bit', where the duration the token has been held by each user is updated // it is essential that timeHeld and totalTimeHeld are incremented together such that the sum of // the first is equal to the second uint256 _timeHeldToIncrement = (_timeOfThisCollection.sub(timeLastCollected[_tokenId])); //just for readability timeHeld[_tokenId][_currentOwner] = timeHeld[_tokenId][_currentOwner].add(_timeHeldToIncrement); totalTimeHeld[_tokenId] = totalTimeHeld[_tokenId].add(_timeHeldToIncrement); // it is also essential that collectedPerUser and totalCollected are all incremented together // such that the sum of the first two (individually) is equal to the third collectedPerUser[_currentOwner] = collectedPerUser[_currentOwner].add(_rentOwed); totalCollected = totalCollected.add(_rentOwed); _augurDeposit(_rentOwed); emit LogRentCollection(_rentOwed, _tokenId); } // timeLastCollected is updated regardless of whether the token is owned, so that the clock starts ticking // ... when the first owner buys it, because this function is run before ownership changes upon calling // ... newRental timeLastCollected[_tokenId] = now; } /// @notice to rent a token function newRental(uint256 _newPrice, uint256 _tokenId, uint256 _deposit) external tokenExists(_tokenId) amountNotZero(_deposit) notResolved() { require(_newPrice > price[_tokenId], "Price must be higher than current price"); _collectRent(_tokenId); // require(1==2, "STFU"); address _currentOwner = team.ownerOf(_tokenId); if (_currentOwner == msg.sender) { // bought by current owner (ie, token ownership does not change, so it is as if the current owner // ... called changePrice and depositDai seperately) _changePrice(_newPrice, _tokenId); _depositDai(_deposit, _tokenId); } else { // bought by different user (the normal situation) // deposits are updated via depositDai function if _currentOwner = msg.sender // therefore deposits only updated inside this else section deposits[_tokenId][msg.sender] = deposits[_tokenId][msg.sender].add(_deposit); // update currentOwnerIndex and ownerTracker currentOwnerIndex[_tokenId] = currentOwnerIndex[_tokenId].add(1); ownerTracker[_tokenId][currentOwnerIndex[_tokenId]].price = _newPrice; ownerTracker[_tokenId][currentOwnerIndex[_tokenId]].owner = msg.sender; // update timeAcquired for the front end timeAcquired[_tokenId] = now; _transferTokenTo(_currentOwner, msg.sender, _newPrice, _tokenId); _receiveCash(msg.sender, _deposit); emit LogNewRental(msg.sender, _newPrice, _tokenId); } } /// @notice add new dai deposit to an existing rental /// @dev it is possible a user's deposit could be reduced to zero following _collectRent /// @dev they would then increase their deposit despite no longer owning it /// @dev this is ok, they can withdraw via withdrawDeposit. function depositDai(uint256 _dai, uint256 _tokenId) external amountNotZero(_dai) tokenExists(_tokenId) notResolved() { _collectRent(_tokenId); _depositDai(_dai, _tokenId); } /// @dev depositDai is split into two, because it needs to be called direct from newRental /// @dev ... without collecing rent first (otherwise it would be collected twice, possibly causing logic errors) function _depositDai(uint256 _dai, uint256 _tokenId) internal { deposits[_tokenId][msg.sender] = deposits[_tokenId][msg.sender].add(_dai); _receiveCash(msg.sender, _dai); emit LogDepositIncreased(_dai, _tokenId, msg.sender); } /// @notice increase the price of an existing rental /// @dev can't be external because also called within newRental function changePrice(uint256 _newPrice, uint256 _tokenId) public tokenExists(_tokenId) notResolved() { require(_newPrice > price[_tokenId], "New price must be higher than current price"); require(msg.sender == team.ownerOf(_tokenId), "Not owner"); _collectRent(_tokenId); _changePrice(_newPrice, _tokenId); } /// @dev changePrice is split into two, because it needs to be called direct from newRental /// @dev ... without collecing rent first (otherwise it would be collected twice, possibly causing logic errors) function _changePrice(uint256 _newPrice, uint256 _tokenId) internal { // below is the only instance when price is modifed outside of the _transferTokenTo function price[_tokenId] = _newPrice; ownerTracker[_tokenId][currentOwnerIndex[_tokenId]].price = _newPrice; emit LogPriceChange(price[_tokenId], _tokenId); } /// @notice withdraw deposit /// @dev do not need to be the current owner function withdrawDeposit(uint256 _dai, uint256 _tokenId) external amountNotZero(_dai) tokenExists(_tokenId) notResolved() returns (uint256) { _collectRent(_tokenId); // if statement needed because deposit may have just reduced to zero following _collectRent if (deposits[_tokenId][msg.sender] > 0) { _withdrawDeposit(_dai, _tokenId); emit LogDepositWithdrawal(_dai, _tokenId, msg.sender); } } /// @notice withdraw full deposit /// @dev do not need to be the current owner function exit(uint256 _tokenId) external tokenExists(_tokenId) notResolved() { _collectRent(_tokenId); // if statement needed because deposit may have just reduced to zero following _collectRent modifier if (deposits[_tokenId][msg.sender] > 0) { _withdrawDeposit(deposits[_tokenId][msg.sender], _tokenId); emit LogExit(_tokenId); } } /* internal */ /// @notice actually withdraw the deposit and call _revertToPreviousOwner if necessary function _withdrawDeposit(uint256 _dai, uint256 _tokenId) internal { require(deposits[_tokenId][msg.sender] >= _dai, 'Withdrawing too much'); deposits[_tokenId][msg.sender] = deposits[_tokenId][msg.sender].sub(_dai); address _currentOwner = team.ownerOf(_tokenId); if(_currentOwner == msg.sender && deposits[_tokenId][msg.sender] == 0) { _revertToPreviousOwner(_tokenId); } _sendCash(msg.sender, _dai); } /* internal */ /// @notice if a users deposit runs out, either return to previous owner or foreclose function _revertToPreviousOwner(uint256 _tokenId) internal { bool _reverted = false; bool _toForeclose = false; uint256 _index; address _previousOwner; while (_reverted == false) { assert(currentOwnerIndex[_tokenId] >=0); currentOwnerIndex[_tokenId] = currentOwnerIndex[_tokenId].sub(1); // currentOwnerIndex will now point to previous owner _index = currentOwnerIndex[_tokenId]; // just for readability _previousOwner = ownerTracker[_tokenId][_index].owner; //if no previous owners. price -> zero, foreclose //if previous owner still has a deposit, transfer to them, update the price to what it used to be if (_index == 0) { _toForeclose = true; _reverted = true; } else if (deposits[_tokenId][_previousOwner] > 0) { _reverted = true; } } if (_toForeclose) { _foreclose(_tokenId); } else { address _currentOwner = team.ownerOf(_tokenId); uint256 _oldPrice = ownerTracker[_tokenId][_index].price; _transferTokenTo(_currentOwner, _previousOwner, _oldPrice, _tokenId); emit LogReturnToPreviousOwner(_tokenId, _previousOwner); } } /* internal */ /// @notice return token to the contract and return price to zero function _foreclose(uint256 _tokenId) internal { address _currentOwner = team.ownerOf(_tokenId); // third field is price, ie price goes to zero _transferTokenTo(_currentOwner, address(this), 0, _tokenId); emit LogForeclosure(_currentOwner, _tokenId); } /* internal */ /// @notice transfer ERC 721 between users /// @dev there is no event emitted as this is handled in ERC721.sol function _transferTokenTo(address _currentOwner, address _newOwner, uint256 _newPrice, uint256 _tokenId) internal { require(_currentOwner != address(0) && _newOwner != address(0) , "Cannot send to/from zero address"); team.transferFrom(_currentOwner, _newOwner, _tokenId); price[_tokenId] = _newPrice; } }
@notice the second of the three functions which must be called, one after the other, to conclude the competition @dev gets funds back from Augur, gets the available funds for distribution @dev can be called by anyone, but only once daiAvailableToDistribute therefore does not include unused deposits
function step2withdrawFromAugur() external { require(marketsResolved == true, "Must wait for market resolution"); require(step2Complete == false, "Step2 should only be run once"); step2Complete = true; uint256 _balanceBefore = _getContractsCashBalance(); _augurWithdraw(); uint256 _balanceAfter = _getContractsCashBalance(); daiAvailableToDistribute = _balanceAfter.sub(_balanceBefore); emit LogStep2Complete(daiAvailableToDistribute); }
15,828,461
[ 1, 5787, 2205, 434, 326, 8925, 4186, 1492, 1297, 506, 2566, 16, 1245, 1839, 326, 1308, 16, 358, 356, 1571, 326, 25163, 608, 225, 5571, 284, 19156, 1473, 628, 432, 637, 295, 16, 5571, 326, 2319, 284, 19156, 364, 7006, 225, 848, 506, 2566, 635, 1281, 476, 16, 1496, 1338, 3647, 5248, 77, 5268, 774, 1669, 887, 13526, 1552, 486, 2341, 10197, 443, 917, 1282, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2235, 22, 1918, 9446, 1265, 37, 637, 295, 1435, 3903, 288, 203, 3639, 2583, 12, 3355, 2413, 12793, 422, 638, 16, 315, 10136, 2529, 364, 13667, 7861, 8863, 203, 3639, 2583, 12, 4119, 22, 6322, 422, 629, 16, 315, 4160, 22, 1410, 1338, 506, 1086, 3647, 8863, 203, 3639, 2235, 22, 6322, 273, 638, 31, 203, 203, 3639, 2254, 5034, 389, 12296, 4649, 273, 389, 588, 20723, 39, 961, 13937, 5621, 203, 3639, 389, 6480, 295, 1190, 9446, 5621, 203, 3639, 2254, 5034, 389, 12296, 4436, 273, 389, 588, 20723, 39, 961, 13937, 5621, 203, 3639, 5248, 77, 5268, 774, 1669, 887, 273, 389, 12296, 4436, 18, 1717, 24899, 12296, 4649, 1769, 203, 3639, 3626, 1827, 4160, 22, 6322, 12, 2414, 77, 5268, 774, 1669, 887, 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 ]
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier:MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/interfaces/IPancakeRouter01.sol pragma solidity 0.7.6; interface IPancakeRouter01 { 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); } // File: contracts/interfaces/IPancakeRouter02.sol pragma solidity 0.7.6; interface IPancakeRouter02 is IPancakeRouter01 { 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; } // File: contracts/interfaces/IPegswap.sol pragma solidity 0.7.6; interface IPegswap{ /** * @notice exchanges the source token for target token * @param amount count of tokens being swapped * @param source the token that is being given * @param target the token that is being taken */ function swap( uint256 amount, address source, address target ) external; } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @opengsn/contracts/src/forwarder/IForwarder.sol pragma solidity >=0.7.6; pragma abicoder v2; interface IForwarder { struct ForwardRequest { address from; address to; uint256 value; uint256 gas; uint256 nonce; bytes data; uint256 validUntil; } event DomainRegistered(bytes32 indexed domainSeparator, bytes domainValue); event RequestTypeRegistered(bytes32 indexed typeHash, string typeStr); function getNonce(address from) external view returns(uint256); /** * verify the transaction would execute. * validate the signature and the nonce of the request. * revert if either signature or nonce are incorrect. * also revert if domainSeparator or requestTypeHash are not registered. */ function verify( ForwardRequest calldata forwardRequest, bytes32 domainSeparator, bytes32 requestTypeHash, bytes calldata suffixData, bytes calldata signature ) external view; /** * execute a transaction * @param forwardRequest - all transaction parameters * @param domainSeparator - domain used when signing this request * @param requestTypeHash - request type used when signing this request. * @param suffixData - the extension data used when signing this request. * @param signature - signature to validate. * * the transaction is verified, and then executed. * the success and ret of "call" are returned. * This method would revert only verification errors. target errors * are reported using the returned "success" and ret string */ function execute( ForwardRequest calldata forwardRequest, bytes32 domainSeparator, bytes32 requestTypeHash, bytes calldata suffixData, bytes calldata signature ) external payable returns (bool success, bytes memory ret); /** * Register a new Request typehash. * @param typeName - the name of the request type. * @param typeSuffix - any extra data after the generic params. * (must add at least one param. The generic ForwardRequest type is always registered by the constructor) */ function registerRequestType(string calldata typeName, string calldata typeSuffix) external; /** * Register a new domain separator. * The domain separator must have the following fields: name,version,chainId, verifyingContract. * the chainId is the current network's chainId, and the verifyingContract is this forwarder. * This method is given the domain name and version to create and register the domain separator value. * @param name the domain's display name * @param version the domain/protocol version */ function registerDomainSeparator(string calldata name, string calldata version) external; } // File: @opengsn/contracts/src/utils/GsnTypes.sol pragma solidity >=0.7.6; interface GsnTypes { /// @notice gasPrice, pctRelayFee and baseRelayFee must be validated inside of the paymaster's preRelayedCall in order not to overpay struct RelayData { uint256 gasPrice; uint256 pctRelayFee; uint256 baseRelayFee; address relayWorker; address paymaster; address forwarder; bytes paymasterData; uint256 clientId; } //note: must start with the ForwardRequest to be an extension of the generic forwarder struct RelayRequest { IForwarder.ForwardRequest request; RelayData relayData; } } // File: @opengsn/contracts/src/interfaces/IStakeManager.sol pragma solidity >=0.7.6; interface IStakeManager { /// Emitted when a stake or unstakeDelay are initialized or increased event StakeAdded( address indexed relayManager, address indexed owner, uint256 stake, uint256 unstakeDelay ); /// Emitted once a stake is scheduled for withdrawal event StakeUnlocked( address indexed relayManager, address indexed owner, uint256 withdrawBlock ); /// Emitted when owner withdraws relayManager funds event StakeWithdrawn( address indexed relayManager, address indexed owner, uint256 amount ); /// Emitted when an authorized Relay Hub penalizes a relayManager event StakePenalized( address indexed relayManager, address indexed beneficiary, uint256 reward ); event HubAuthorized( address indexed relayManager, address indexed relayHub ); event HubUnauthorized( address indexed relayManager, address indexed relayHub, uint256 removalBlock ); event OwnerSet( address indexed relayManager, address indexed owner ); /// @param stake - amount of ether staked for this relay /// @param unstakeDelay - number of blocks to elapse before the owner can retrieve the stake after calling 'unlock' /// @param withdrawBlock - first block number 'withdraw' will be callable, or zero if the unlock has not been called /// @param owner - address that receives revenue and manages relayManager's stake struct StakeInfo { uint256 stake; uint256 unstakeDelay; uint256 withdrawBlock; address payable owner; } struct RelayHubInfo { uint256 removalBlock; } /// Set the owner of a Relay Manager. Called only by the RelayManager itself. /// Note that owners cannot transfer ownership - if the entry already exists, reverts. /// @param owner - owner of the relay (as configured off-chain) function setRelayManagerOwner(address payable owner) external; /// Only the owner can call this function. If the entry does not exist, reverts. /// @param relayManager - address that represents a stake entry and controls relay registrations on relay hubs /// @param unstakeDelay - number of blocks to elapse before the owner can retrieve the stake after calling 'unlock' function stakeForRelayManager(address relayManager, uint256 unstakeDelay) external payable; function unlockStake(address relayManager) external; function withdrawStake(address relayManager) external; function authorizeHubByOwner(address relayManager, address relayHub) external; function authorizeHubByManager(address relayHub) external; function unauthorizeHubByOwner(address relayManager, address relayHub) external; function unauthorizeHubByManager(address relayHub) external; function isRelayManagerStaked(address relayManager, address relayHub, uint256 minAmount, uint256 minUnstakeDelay) external view returns (bool); /// Slash the stake of the relay relayManager. In order to prevent stake kidnapping, burns half of stake on the way. /// @param relayManager - entry to penalize /// @param beneficiary - address that receives half of the penalty amount /// @param amount - amount to withdraw from stake function penalizeRelayManager(address relayManager, address payable beneficiary, uint256 amount) external; function getStakeInfo(address relayManager) external view returns (StakeInfo memory stakeInfo); function maxUnstakeDelay() external view returns (uint256); function versionSM() external view returns (string memory); } // File: @opengsn/contracts/src/interfaces/IRelayHub.sol pragma solidity >=0.7.6; interface IRelayHub { struct RelayHubConfig { // maximum number of worker accounts allowed per manager uint256 maxWorkerCount; // Gas set aside for all relayCall() instructions to prevent unexpected out-of-gas exceptions uint256 gasReserve; // Gas overhead to calculate gasUseWithoutPost uint256 postOverhead; // Gas cost of all relayCall() instructions after actual 'calculateCharge()' // Assume that relay has non-zero balance (costs 15'000 more otherwise). uint256 gasOverhead; // Maximum funds that can be deposited at once. Prevents user error by disallowing large deposits. uint256 maximumRecipientDeposit; // Minimum unstake delay blocks of a relay manager's stake on the StakeManager uint256 minimumUnstakeDelay; // Minimum stake a relay can have. An attack on the network will never cost less than half this value. uint256 minimumStake; // relayCall()'s msg.data upper bound gas cost per byte uint256 dataGasCostPerByte; // relayCalls() minimal gas overhead when calculating cost of putting tx on chain. uint256 externalCallDataCostOverhead; } event RelayHubConfigured(RelayHubConfig config); /// Emitted when a relay server registers or updates its details /// Looking at these events lets a client discover relay servers event RelayServerRegistered( address indexed relayManager, uint256 baseRelayFee, uint256 pctRelayFee, string relayUrl ); /// Emitted when relays are added by a relayManager event RelayWorkersAdded( address indexed relayManager, address[] newRelayWorkers, uint256 workersCount ); /// Emitted when an account withdraws funds from RelayHub. event Withdrawn( address indexed account, address indexed dest, uint256 amount ); /// Emitted when depositFor is called, including the amount and account that was funded. event Deposited( address indexed paymaster, address indexed from, uint256 amount ); /// Emitted when an attempt to relay a call fails and Paymaster does not accept the transaction. /// The actual relayed call was not executed, and the recipient not charged. /// @param reason contains a revert reason returned from preRelayedCall or forwarder. event TransactionRejectedByPaymaster( address indexed relayManager, address indexed paymaster, address indexed from, address to, address relayWorker, bytes4 selector, uint256 innerGasUsed, bytes reason ); /// Emitted when a transaction is relayed. Note that the actual encoded function might be reverted: this will be /// indicated in the status field. /// Useful when monitoring a relay's operation and relayed calls to a contract. /// Charge is the ether value deducted from the recipient's balance, paid to the relay's manager. event TransactionRelayed( address indexed relayManager, address indexed relayWorker, address indexed from, address to, address paymaster, bytes4 selector, RelayCallStatus status, uint256 charge ); event TransactionResult( RelayCallStatus status, bytes returnValue ); event HubDeprecated(uint256 fromBlock); /// Reason error codes for the TransactionRelayed event /// @param OK - the transaction was successfully relayed and execution successful - never included in the event /// @param RelayedCallFailed - the transaction was relayed, but the relayed call failed /// @param RejectedByPreRelayed - the transaction was not relayed due to preRelatedCall reverting /// @param RejectedByForwarder - the transaction was not relayed due to forwarder check (signature,nonce) /// @param PostRelayedFailed - the transaction was relayed and reverted due to postRelatedCall reverting /// @param PaymasterBalanceChanged - the transaction was relayed and reverted due to the paymaster balance change enum RelayCallStatus { OK, RelayedCallFailed, RejectedByPreRelayed, RejectedByForwarder, RejectedByRecipientRevert, PostRelayedFailed, PaymasterBalanceChanged } /// Add new worker addresses controlled by sender who must be a staked Relay Manager address. /// Emits a RelayWorkersAdded event. /// This function can be called multiple times, emitting new events function addRelayWorkers(address[] calldata newRelayWorkers) external; function registerRelayServer(uint256 baseRelayFee, uint256 pctRelayFee, string calldata url) external; // Balance management /// Deposits ether for a contract, so that it can receive (and pay for) relayed transactions. Unused balance can only /// be withdrawn by the contract itself, by calling withdraw. /// Emits a Deposited event. function depositFor(address target) external payable; /// Withdraws from an account's balance, sending it back to it. Relay managers call this to retrieve their revenue, and /// contracts can also use it to reduce their funding. /// Emits a Withdrawn event. function withdraw(uint256 amount, address payable dest) external; // Relaying /// Relays a transaction. For this to succeed, multiple conditions must be met: /// - Paymaster's "preRelayCall" method must succeed and not revert /// - the sender must be a registered Relay Worker that the user signed /// - the transaction's gas price must be equal or larger than the one that was signed by the sender /// - the transaction must have enough gas to run all internal transactions if they use all gas available to them /// - the Paymaster must have enough balance to pay the Relay Worker for the scenario when all gas is spent /// /// If all conditions are met, the call will be relayed and the recipient charged. /// /// Arguments: /// @param maxAcceptanceBudget - max valid value for paymaster.getGasLimits().acceptanceBudget /// @param relayRequest - all details of the requested relayed call /// @param signature - client's EIP-712 signature over the relayRequest struct /// @param approvalData: dapp-specific data forwarded to preRelayedCall. /// This value is *not* verified by the Hub. For example, it can be used to pass a signature to the Paymaster /// @param externalGasLimit - the value passed as gasLimit to the transaction. /// /// Emits a TransactionRelayed event. function relayCall( uint maxAcceptanceBudget, GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint externalGasLimit ) external returns (bool paymasterAccepted, bytes memory returnValue); function penalize(address relayWorker, address payable beneficiary) external; function setConfiguration(RelayHubConfig memory _config) external; // Deprecate hub (reverting relayCall()) from block number 'fromBlock' // Can only be called by owner function deprecateHub(uint256 fromBlock) external; /// The fee is expressed as a base fee in wei plus percentage on actual charge. /// E.g. a value of 40 stands for a 40% fee, so the recipient will be /// charged for 1.4 times the spent amount. function calculateCharge(uint256 gasUsed, GsnTypes.RelayData calldata relayData) external view returns (uint256); /* getters */ /// Returns the whole hub configuration function getConfiguration() external view returns (RelayHubConfig memory config); function calldataGasCost(uint256 length) external view returns (uint256); function workerToManager(address worker) external view returns(address); function workerCount(address manager) external view returns(uint256); /// Returns an account's deposits. It can be either a deposit of a paymaster, or a revenue of a relay manager. function balanceOf(address target) external view returns (uint256); function stakeManager() external view returns (IStakeManager); function penalizer() external view returns (address); /// Uses StakeManager info to decide if the Relay Manager can be considered staked /// @return true if stake size and delay satisfy all requirements function isRelayManagerStaked(address relayManager) external view returns(bool); // Checks hubs' deprecation status function isDeprecated() external view returns (bool); // Returns the block number from which the hub no longer allows relaying calls. function deprecationBlock() external view returns (uint256); /// @return a SemVer-compliant version of the hub contract function versionHub() external view returns (string memory); } // File: @opengsn/contracts/src/interfaces/IRelayRecipient.sol pragma solidity >=0.7.6; /** * a contract must implement this interface in order to support relayed transaction. * It is better to inherit the BaseRelayRecipient as its implementation. */ abstract contract IRelayRecipient { /** * return if the forwarder is trusted to forward relayed transactions to us. * the forwarder is required to verify the sender's signature, and verify * the call is not a replay. */ function isTrustedForwarder(address forwarder) public virtual view returns(bool); /** * return the sender of this call. * if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes * of the msg.data. * otherwise, return `msg.sender` * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal virtual view returns (address payable); /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise (if the call was made directly and not through the forwarder), return `msg.data` * should be used in the contract instead of msg.data, where this difference matters. */ function _msgData() internal virtual view returns (bytes memory); function versionRecipient() external virtual view returns (string memory); } // File: @opengsn/contracts/src/BaseRelayRecipient.sol // solhint-disable no-inline-assembly pragma solidity >=0.7.6; /** * A base contract to be inherited by any contract that want to receive relayed transactions * A subclass must use "_msgSender()" instead of "msg.sender" */ abstract contract BaseRelayRecipient is IRelayRecipient { /* * Forwarder singleton we accept calls from */ address public trustedForwarder; function isTrustedForwarder(address forwarder) public override view returns(bool) { return forwarder == trustedForwarder; } /** * return the sender of this call. * if the call came through our trusted forwarder, return the original sender. * otherwise, return `msg.sender`. * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal override virtual view returns (address payable ret) { if (msg.data.length >= 20 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // so we trust that the last bytes of msg.data are the verified sender address. // extract sender address from the end of msg.data assembly { ret := shr(96,calldataload(sub(calldatasize(),20))) } } else { return msg.sender; } } /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise, return `msg.data` * should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly * signing or hashing the */ function _msgData() internal override virtual view returns (bytes memory ret) { if (msg.data.length >= 20 && isTrustedForwarder(msg.sender)) { return msg.data[0:msg.data.length-20]; } else { return msg.data; } } } // File: @chainlink/contracts/src/v0.7/vendor/SafeMathChainlink.sol pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathChainlink { /** * @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: @chainlink/contracts/src/v0.7/interfaces/LinkTokenInterface.sol pragma solidity ^0.7.0; interface LinkTokenInterface { function allowance( address owner, address spender ) external view returns ( uint256 remaining ); function approve( address spender, uint256 value ) external returns ( bool success ); function balanceOf( address owner ) external view returns ( uint256 balance ); function decimals() external view returns ( uint8 decimalPlaces ); function decreaseApproval( address spender, uint256 addedValue ) external returns ( bool success ); function increaseApproval( address spender, uint256 subtractedValue ) external; function name() external view returns ( string memory tokenName ); function symbol() external view returns ( string memory tokenSymbol ); function totalSupply() external view returns ( uint256 totalTokensIssued ); function transfer( address to, uint256 value ) external returns ( bool success ); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns ( bool success ); function transferFrom( address from, address to, uint256 value ) external returns ( bool success ); } // File: @chainlink/contracts/src/v0.7/dev/VRFRequestIDBase.sol pragma solidity ^0.7.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns ( uint256 ) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId( bytes32 _keyHash, uint256 _vRFInputSeed ) internal pure returns ( bytes32 ) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } // File: @chainlink/contracts/src/v0.7/dev/VRFConsumerBase.sol pragma solidity ^0.7.0; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK_ERC677 * @dev price for VRF service. Make sure your contract has sufficient LINK_ERC677, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { using SafeMathChainlink for uint256; /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness( bytes32 requestId, uint256 randomness ) internal virtual; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK_ERC677 to send with the request * @param _seed seed mixed into the input of the VRF. * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness( bytes32 _keyHash, uint256 _fee, uint256 _seed ) internal returns ( bytes32 requestId ) { LINK_ERC677.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, _seed)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, _seed, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK_ERC677.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash].add(1); return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface immutable internal LINK_ERC677; address immutable private vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK_ERC677 token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor( address _vrfCoordinator, address _link ) { vrfCoordinator = _vrfCoordinator; LINK_ERC677 = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness( bytes32 requestId, uint256 randomness ) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/tokens/ERC20.sol pragma solidity ^0.7.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_) { _name = name_; _symbol = symbol_; _decimals = 2; } /** * @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 { } } // File: contracts/tokens/NGNT.sol pragma solidity 0.7.6; contract NGNTContract is ERC20("Naira Token", "NGNT"){ uint256 public gsnFee; constructor() { _mint(msg.sender, 1e18); } } // File: contracts/WinNgnt.sol pragma solidity 0.7.6; contract WinNgnt is BaseRelayRecipient, VRFConsumerBase { using SafeMath for uint256; NGNTContract public NGNT; //ERC20 version of original ERC677 token IERC20 public LINK_ERC20; IPancakeRouter02 private pancakeswap; IPegswap public pegswap; IRelayHub public relayHub; address public WBNB; address private paymaster; struct Game { address[] tickets; address gameWinner; } uint256 public commission; uint256 public gameNumber = 1; uint256 public ticketPrice = 50000; uint256 public maximumPurchasableTickets = 250; uint256 public maximumTicketsPerAddress = 250; uint256 public TOTAL_NGNT; uint256 gsnFee = 5000; uint256 internal chainLinkFee; address[] path_NGNTBNB; address[] path_NGNTLINKERC20; string public override versionRecipient = "2.2.0+opengsn.winngnt.irelayrecipient"; bytes32 internal keyHash; mapping(uint256 => Game) public games; mapping(address => uint256) public addressTicketCount; mapping(uint256 => mapping(address => uint256)) public addressTicketCountPerGame; mapping(bytes32 => bool) public pendingQueries; event GameEnded(uint256 gameNumber); event BoughtTicket( address indexed buyer, uint256 numOfTickets, uint256 totalTicketPrice ); event RandomNumberQuerySent(bytes32 queryId, uint256 indexed gameNumber); event RandomNumberGenerated( uint16 randomNumber, uint256 indexed gameNumber ); event WinnerSelected( address winner, uint256 amount, uint256 indexed gameNumber ); modifier atLeastOneTicket(uint256 numberOfTickets) { require( numberOfTickets >= 1, "WinNgnt:Cannot buy less than one ticket" ); _; } modifier ticketLimitNotExceed(uint256 numberOfTickets) { require( (games[gameNumber].tickets.length + numberOfTickets) <= maximumPurchasableTickets, "WinNgnt:Total ticket per game limit exceeded" ); _; } modifier maxTicketPerAddressLimitNotExceed( address _address, uint256 numberOfTickets ) { require( (addressTicketCountPerGame[gameNumber][_address] + numberOfTickets) <= maximumTicketsPerAddress, "WinNgnt:Maximum ticket limit per address exceeded" ); _; } modifier queryIdHasNotBeenProcessed(bytes32 queryId) { require( pendingQueries[queryId] == true, "WinNgnt:QueryId has been processed" ); _; } constructor( NGNTContract _NGNT, IPegswap _pegswap, IERC20 _LINK_ERC20, address _WBNB, IPancakeRouter02 _pancakeswap, IRelayHub _relayHub, address _vrfCoordinator, address _LINK_ERC677, address _trustedForwarder, address _paymaster, uint256 _chainLinkFee, uint256 _maximumPurchasableTickets ) VRFConsumerBase( _vrfCoordinator, _LINK_ERC677 ) { NGNT = _NGNT; pegswap = _pegswap; LINK_ERC20 = _LINK_ERC20; WBNB = _WBNB; pancakeswap = _pancakeswap; maximumPurchasableTickets = _maximumPurchasableTickets; keyHash = 0xcaf3c3727e033261d383b315559476f48034c13b18f8cafed4d871abe5049186; chainLinkFee = _chainLinkFee; trustedForwarder = _trustedForwarder; relayHub = _relayHub; paymaster = _paymaster; path_NGNTLINKERC20 = [address(NGNT), WBNB, address(LINK_ERC20)]; path_NGNTBNB = [address(NGNT), WBNB]; NGNT.approve(address(pancakeswap), type(uint256).max); LINK_ERC20.approve(address(pegswap), type(uint256).max); } function buyTicket(uint256 numberOfTickets) external atLeastOneTicket(numberOfTickets) ticketLimitNotExceed(numberOfTickets) maxTicketPerAddressLimitNotExceed(_msgSender(), numberOfTickets) { uint256 totalTicketPrice = ticketPrice.mul(numberOfTickets); uint256 totalAddressTicketCount = addressTicketCount[_msgSender()]; uint256 totalAddressTicketCountPerGame = addressTicketCountPerGame[gameNumber][_msgSender()]; NGNT.transferFrom(_msgSender(), address(this), totalTicketPrice); uint addCommission = gsnFee.mul(numberOfTickets); totalTicketPrice = totalTicketPrice.sub(addCommission); commission = commission.add(addCommission); TOTAL_NGNT = TOTAL_NGNT.add(totalTicketPrice); totalAddressTicketCount = totalAddressTicketCount.add(numberOfTickets); totalAddressTicketCountPerGame = totalAddressTicketCountPerGame.add(numberOfTickets); addressTicketCount[_msgSender()] = totalAddressTicketCount; addressTicketCountPerGame[gameNumber][ _msgSender() ] = totalAddressTicketCountPerGame; Game storage game = games[gameNumber]; for (uint256 i = 0; i < numberOfTickets; i++) { game.tickets.push(_msgSender()); } emit BoughtTicket(_msgSender(), numberOfTickets, totalTicketPrice); if (games[gameNumber].tickets.length == maximumPurchasableTickets) { uint LINK_ERC677_Balance = LINK_ERC677.balanceOf(address(this)); if (LINK_ERC677_Balance < chainLinkFee) { uint amountOut = chainLinkFee - LINK_ERC677_Balance; uint[] memory amountsIn = pancakeswap.getAmountsIn(amountOut, path_NGNTLINKERC20); if(commission >= amountsIn[0]){ swapNGNTForLINK_ERC20(amountsIn[0], amountOut); swapLINK_ERC20ForLINK_ERC677(amountOut); } if(gameNumber.mod(5) == 0){ swapNGNTForBNB(); relayHub.depositFor{value: address(this).balance}(paymaster); } } endGame(); } } function numberOfTicketsLeft() external view returns (uint256) { Game storage game = games[gameNumber]; uint256 ticketsBought = game.tickets.length; return maximumPurchasableTickets.sub(ticketsBought); } function numberOfTicketsPurchased() external view returns (uint256) { Game storage game = games[gameNumber]; uint256 ticketsBought = game.tickets.length; return ticketsBought; } function getNgntAddress() external view returns (address) { return address(NGNT); } function fulfillRandomness(bytes32 queryId, uint256 randomness) internal override queryIdHasNotBeenProcessed(queryId) { require(games[gameNumber].tickets.length == maximumPurchasableTickets); delete pendingQueries[queryId]; uint16 randomIndex = uint16(randomness.mod(maximumPurchasableTickets) + 1); emit RandomNumberGenerated(randomIndex, gameNumber); sendNgntToWinner(randomIndex); } function generateRandomNumber() private { require( LINK_ERC677.balanceOf(address(this)) >= chainLinkFee, "WinNgnt: LINK_ERC677 balance not enough for query" ); bytes32 queryId = requestRandomness(keyHash, chainLinkFee, block.timestamp); pendingQueries[queryId] = true; emit RandomNumberQuerySent(queryId, gameNumber); } function startNextGame() public { generateRandomNumber(); } function sendNgntToWinner(uint256 randomIndex) private { Game storage game = games[gameNumber]; address winner = game.tickets[randomIndex]; game.gameWinner = winner; uint256 amountWon = TOTAL_NGNT.mul(90).div(100); commission = NGNT.balanceOf(address(this)).sub(amountWon); resetGame(); NGNT.transfer(winner, amountWon); emit WinnerSelected(winner, amountWon, gameNumber); } function swapNGNTForLINK_ERC20(uint256 _amountIn, uint256 _amountOut) private { pancakeswap.swapTokensForExactTokens( _amountOut, _amountIn, path_NGNTLINKERC20, address(this), block.timestamp.add(20 minutes) ); } function swapLINK_ERC20ForLINK_ERC677(uint256 _amount) private { require( LINK_ERC20.balanceOf(address(this)) >= _amount, "WinNgnt: ERC20 LINK balance not enough for swap" ); pegswap.swap(_amount, address(LINK_ERC20), address(LINK_ERC677)); } function swapNGNTForBNB() private { if(relayHub.balanceOf(paymaster) < 1 ether){ uint tokenSold = commission; commission = 0; pancakeswap.swapExactTokensForETH( tokenSold, 1 wei, path_NGNTBNB, address(this), block.timestamp.add(20 minutes) ); } } function resetGame() private { gameNumber++; TOTAL_NGNT = 0; } function endGame() private { emit GameEnded(gameNumber); if(LINK_ERC677.balanceOf(address(this)) >= chainLinkFee) generateRandomNumber(); } receive() external payable {} }
* @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 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; constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _decimals = 2; } function name() public view virtual returns (string memory) { return _name; } function symbol() public view virtual returns (string memory) { return _symbol; } function decimals() public view virtual returns (uint8) { return _decimals; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual 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 _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
6,487,690
[ 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, 4232, 39, 3462, 353, 1772, 16, 467, 654, 39, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 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, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 203, 203, 565, 3885, 261, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 13, 288, 203, 3639, 389, 529, 273, 508, 67, 31, 203, 3639, 389, 7175, 273, 3273, 67, 31, 203, 3639, 389, 31734, 273, 576, 31, 203, 565, 289, 203, 203, 565, 445, 508, 1435, 1071, 1476, 5024, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 1071, 1476, 5024, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 1476, 5024, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 389, 31734, 31, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 31, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 1071, 1476, 5024, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 2 ]
./full_match/1/0xa3C8d390c3965D33937865973b6159D37B777C54/sources/src/fund/fees/PerformanceFee.sol
@notice Assumes management fee is zero
function updateState() external { require(lastPayoutTime[msg.sender] != 0, "Not initialized"); require( canUpdate(msg.sender), "Not within a update window or already updated this period" ); Hub hub = FeeManager(msg.sender).hub(); Accounting accounting = Accounting(hub.accounting()); Shares shares = Shares(hub.shares()); uint gav = accounting.calcGav(); uint currentGavPerShare = accounting.valuePerShare(gav, shares.totalSupply()); require( currentGavPerShare > highWaterMark[msg.sender], "Current share price does not pass high water mark" ); lastPayoutTime[msg.sender] = block.timestamp; highWaterMark[msg.sender] = currentGavPerShare; emit HighWaterMarkUpdate(msg.sender, currentGavPerShare); }
3,057,647
[ 1, 2610, 6411, 11803, 14036, 353, 3634, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1089, 1119, 1435, 3903, 288, 203, 3639, 2583, 12, 2722, 52, 2012, 950, 63, 3576, 18, 15330, 65, 480, 374, 16, 315, 1248, 6454, 8863, 203, 3639, 2583, 12, 203, 5411, 848, 1891, 12, 3576, 18, 15330, 3631, 203, 5411, 315, 1248, 3470, 279, 1089, 2742, 578, 1818, 3526, 333, 3879, 6, 203, 3639, 11272, 203, 3639, 21353, 11891, 273, 30174, 1318, 12, 3576, 18, 15330, 2934, 14986, 5621, 203, 3639, 6590, 310, 2236, 310, 273, 6590, 310, 12, 14986, 18, 4631, 310, 10663, 203, 3639, 2638, 4807, 24123, 273, 2638, 4807, 12, 14986, 18, 30720, 10663, 203, 3639, 2254, 314, 842, 273, 2236, 310, 18, 12448, 43, 842, 5621, 203, 3639, 2254, 783, 43, 842, 2173, 9535, 273, 2236, 310, 18, 1132, 2173, 9535, 12, 75, 842, 16, 24123, 18, 4963, 3088, 1283, 10663, 203, 3639, 2583, 12, 203, 5411, 783, 43, 842, 2173, 9535, 405, 3551, 24064, 3882, 63, 3576, 18, 15330, 6487, 203, 5411, 315, 3935, 7433, 6205, 1552, 486, 1342, 3551, 16313, 2267, 6, 203, 3639, 11272, 203, 3639, 1142, 52, 2012, 950, 63, 3576, 18, 15330, 65, 273, 1203, 18, 5508, 31, 203, 3639, 3551, 24064, 3882, 63, 3576, 18, 15330, 65, 273, 783, 43, 842, 2173, 9535, 31, 203, 3639, 3626, 15207, 24064, 3882, 1891, 12, 3576, 18, 15330, 16, 783, 43, 842, 2173, 9535, 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 ]
./partial_match/1/0x56FC8BefdDd4bdba1F24E4f54Ad4CF6DeaD2cFBa/sources/TKRPToken.sol
* @title Standard ERC20 token @dev Implementation of the basic standard token./
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; function transferFrom(address _from, address _to, uint256 _value) { var _allowance = allowed[_from][msg.sender]; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); } function approve(address _spender, uint256 _value) { if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } }
2,627,286
[ 1, 8336, 4232, 39, 3462, 1147, 225, 25379, 434, 326, 5337, 4529, 1147, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 8263, 1345, 353, 4232, 39, 3462, 16, 7651, 1345, 288, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 2935, 31, 203, 203, 565, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 1132, 13, 288, 203, 3639, 569, 389, 5965, 1359, 273, 2935, 63, 67, 2080, 6362, 3576, 18, 15330, 15533, 203, 203, 203, 3639, 324, 26488, 63, 67, 869, 65, 273, 324, 26488, 63, 67, 869, 8009, 1289, 24899, 1132, 1769, 203, 3639, 324, 26488, 63, 67, 2080, 65, 273, 324, 26488, 63, 67, 2080, 8009, 1717, 24899, 1132, 1769, 203, 3639, 2935, 63, 67, 2080, 6362, 3576, 18, 15330, 65, 273, 389, 5965, 1359, 18, 1717, 24899, 1132, 1769, 203, 3639, 12279, 24899, 2080, 16, 389, 869, 16, 389, 1132, 1769, 203, 565, 289, 203, 203, 565, 445, 6617, 537, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 13, 288, 203, 203, 3639, 309, 14015, 67, 1132, 480, 374, 13, 597, 261, 8151, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 480, 374, 3719, 604, 31, 203, 203, 3639, 2935, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 273, 389, 1132, 31, 203, 3639, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 389, 87, 1302, 264, 16, 389, 1132, 1769, 203, 565, 289, 203, 203, 565, 445, 1699, 1359, 12, 2867, 389, 8443, 16, 1758, 389, 87, 1302, 264, 13, 5381, 1135, 261, 11890, 5034, 4463, 13, 288, 203, 3639, 327, 2935, 63, 2 ]
./full_match/1/0xD243629A94c657cB415cFfbfB4f84fb8b98496ec/sources/contracts/TipJarManager.sol
* @notice Create batch proposal @param targets target address @param values ETH value @param datas function call bytes @param predecessor predecessor function call @param salt salt used in proposal/
function createProposalBatch( address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt ) external onlyAdmin { timelock.scheduleBatch(targets, values, datas, predecessor, salt, criticalDelay); }
9,784,605
[ 1, 1684, 2581, 14708, 225, 5774, 1018, 1758, 225, 924, 512, 2455, 460, 225, 5386, 445, 745, 1731, 225, 24282, 24282, 445, 745, 225, 4286, 4286, 1399, 316, 14708, 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, 752, 14592, 4497, 12, 203, 3639, 1758, 8526, 745, 892, 5774, 16, 7010, 3639, 2254, 5034, 8526, 745, 892, 924, 16, 7010, 3639, 1731, 8526, 745, 892, 5386, 16, 7010, 3639, 1731, 1578, 24282, 16, 7010, 3639, 1731, 1578, 4286, 203, 565, 262, 3903, 1338, 4446, 288, 203, 3639, 1658, 292, 975, 18, 10676, 4497, 12, 11358, 16, 924, 16, 5386, 16, 24282, 16, 4286, 16, 11239, 6763, 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 ]
./partial_match/1/0x55225774775fcF8A804d77D6cFDF0e951b0236F0/sources/ALTCrowdsale.sol
Step 4: 0.30$; +7 000 000 ALT tokens
steps.push(Step(30, 22000000));
4,032,476
[ 1, 4160, 1059, 30, 374, 18, 5082, 8, 31, 397, 27, 20546, 20546, 30939, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6075, 18, 6206, 12, 4160, 12, 5082, 16, 11201, 9449, 10019, 4766, 12900, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.3 <0.9.0; contract Escrow { // think about adding a USD => WEI converter for easier purchase legibility //state variables address payable internal buyer; address payable internal seller; // owner of the item address payable internal arbiter; // arbiter for the escrow uint public amountInEth; uint public balance; uint Gwei = 1000000000; // 1 ETH = 1000000000 GWEI; uint Wei = 1000000000; // 1 Gwei = 1000000000 WEI; // variables for time tracking // 259200 is 3 days uint private limit = 1; // 1 second uint private begin = 0; // variable for beginning of contract uint public end_time = 0; // variable for end of contract // Define a function 'kill' if required to cancel contract function kill() external { if (msg.sender == arbiter) { selfdestruct(payable(address(this))); } } //solidity events event FundingReceived(uint _amount); event SellerPaid(uint _amount); event BuyerRefunded(uint _amount); event ContractNull(uint _timestamp); // allow contract to use ETH fallback() external payable { // do nothing emit FundingReceived(block.timestamp); } // allow contract to hold ETH receive() external payable { // do nothing emit FundingReceived(block.timestamp); } //function that confirms/validates success of transaction function validate() public payable { require(msg.sender == arbiter); //only arbiter can execute this function //if the buyer has paid if (balance >= 0) { //if the buyer has paid more than the amount in the contract if (balance > amountInEth) { //refund the buyer uint difference = balance - amountInEth; buyer.transfer(difference); emit BuyerRefunded(block.timestamp); // re-adjust balance and pay seller balance -= difference; payoutToSeller(balance); balance = 0; //set balance to 0 after transaction //selfdestruct(payable(address(this))); // kill the contract } else if (balance == amountInEth) { // if correct amount has been input payoutToSeller(balance); balance = 0; //selfdestruct(payable(address(this))); // kill the contract } //if the buyer has paid less than the amount in the contract else{ // INVALID CONTRACT // refund to the buyer and cancel the contract refundBuyer(); balance = 0; emit ContractNull(block.timestamp); // emit voided contract //selfdestruct(payable(address(this))); // kill the contract } } } function convertAmount(uint256 _amount) public pure returns (uint) { return _amount * (1 ether / 100); // return ETH amount converted roughly down to dollars } //function for buyer to fund; payable keyword must be used function fund() public payable { require(msg.sender == arbiter && msg.value == amountInEth); //conditional checks to make sure only the buyer's address); balance += msg.value; // add value to the contract emit FundingReceived(balance); //emit FundingReceived() event } //function for buyer to payout seller function payoutToSeller(uint _amount) public { require(msg.sender == arbiter); //only arbiter can execute this function seller.transfer(_amount); //using the solidity's built in transfer function, the funds are sent to the seller emit SellerPaid(_amount); //emit SellerPaid() event balance = 0; //set balance to 0 after transaction } //function for seller to refund the buyer function refundBuyer() public { require(msg.sender == arbiter);//only arbiter can execute this function emit BuyerRefunded(balance);//emit BuyerRefunded() event buyer.transfer(balance); //using the solidity's built in transfer function, the funds are returned to the buyer balance = 0; } /* //function that creates and holds a time limit for the escrow using validator function timeLimit() external payable { if(checkTime()) { } else { } } */ // function checkTime() to check time status of the contract // would need to be used by an exteranl script/service as ethereum does not have internal scheduling functions function checkTime() public returns (bool) { //if the time limit has not been reached if (block.timestamp < (begin + limit)) { return true; } //if the time limit has been reached else { refundBuyer(); return false; } } //constructor function; used to set initial state of contract /* constructor(address payable arbiter) public { begin = block.timestamp; // set beginning of contract end_time = begin + limit; // set contract limit at 3 days } */ ////////////////////// // GET-SET FXNS ///// function setSeller(address payable _seller) external { require(msg.sender == arbiter || msg.sender == seller); //only arbiter can execute this function seller = _seller; } function getSeller() external view returns (address){ return seller; } function setBuyer(address payable _buyer) external { require(msg.sender == arbiter); //only arbiter can execute this function buyer = _buyer; } function getbuyer() external view returns (address){ return buyer; } // internal so as to avoid shenanigans function setArbiter(address payable _arbiter) internal { arbiter = _arbiter; } function setPrice(uint _amountInWei) external { require(msg.sender == arbiter || msg.sender == seller); //only arbiter can execute this function amountInEth = _amountInWei; } function getPrice() external view returns(uint) { return amountInEth; } /////////////////////// }
using the solidity's built in transfer function, the funds are sent to the seller
seller.transfer(_amount);
5,429,803
[ 1, 9940, 326, 18035, 560, 1807, 6650, 316, 7412, 445, 16, 326, 284, 19156, 854, 3271, 358, 326, 29804, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 29804, 18, 13866, 24899, 8949, 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, -100, -100, -100 ]
pragma solidity ^0.8.0; // SPDX-License-Identifier: MIT contract Payment { address public contract_owner; struct Contributor { address addr; uint share; } Contributor[] public contributors; constructor() { contract_owner = msg.sender; // address of creator of contract } //to add contributors in contract function add(address _addr, uint256 _share) public restricted { contributors.push(Contributor(_addr, _share)); } //to find particular user from address function find(address _addr) internal view returns (uint256 id_) { for (uint256 i = 0; i < contributors.length; i++) { if (contributors[i].addr == _addr) { return i; } } revert("Contributor does not exist"); } //someone buying product and distibuting to users function buy_item() public payable { require(contributors.length > 0); for (uint256 i = 0; i < contributors.length; i++) { uint256 amount = 0; amount = percent(msg.value, contributors[i].share); payable(contributors[i].addr).transfer(amount); } } //calculating percentage amount function percent(uint256 amount, uint256 fraction) public pure returns (uint256) { //require((amount / 10000) * 10000 == amount, 'too small'); return (amount * fraction) / 10000; //fraction of 2.15 is 215 } modifier restricted() { require(msg.sender == contract_owner); //only owner can do _; } }
fraction of 2.15 is 215
return (amount * fraction) / 10000;
1,004,001
[ 1, 16744, 434, 576, 18, 3600, 353, 225, 576, 3600, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 327, 261, 8949, 380, 8330, 13, 342, 12619, 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 ]
pragma solidity ^0.4.18; contract SCTFBank{ event LogBalance(address addr, uint256 value); mapping (address => uint256) private balance; uint256 private donation_deposit; address private owner; //constructor constructor() public{ owner = msg.sender; } //logging balance of requested address function showBalance(address addr) public { emit LogBalance(addr, balance[addr]); } //withdraw my balance function withdraw(uint256 value) public{ require(balance[msg.sender] >= value); msg.sender.call.value(value)(); balance[msg.sender] -= value; } //transfer my balance to other function transfer(address to, uint256 value) public { require(balance[msg.sender] >= value); balance[msg.sender] -= value; balance[to]+=value; } //transfer my balance to others function multiTransfer(address[] to_list, uint256 value) public { require(balance[msg.sender] >= value*to_list.length); balance[msg.sender] -= value*to_list.length; for(uint i=0; i < to_list.length; i++){ balance[to_list[i]] += value; } } //donate my balance function donate(uint256 value) public { balance[msg.sender] -= value; donation_deposit += value; } //Only bank owner can deliver donations to anywhere he want. function deliver(address to) public { require(tx.origin == owner); to.transfer(donation_deposit); donation_deposit = 0; } //balance deposit, simple fallback function function () payable public { balance[msg.sender]+=msg.value; } } //END
transfer my balance to others
function multiTransfer(address[] to_list, uint256 value) public { require(balance[msg.sender] >= value*to_list.length); balance[msg.sender] -= value*to_list.length; for(uint i=0; i < to_list.length; i++){ balance[to_list[i]] += value; } }
891,303
[ 1, 13866, 3399, 11013, 358, 10654, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3309, 5912, 12, 2867, 8526, 358, 67, 1098, 16, 2254, 5034, 460, 13, 1071, 288, 203, 3639, 2583, 12, 12296, 63, 3576, 18, 15330, 65, 1545, 460, 14, 869, 67, 1098, 18, 2469, 1769, 203, 3639, 11013, 63, 3576, 18, 15330, 65, 3947, 460, 14, 869, 67, 1098, 18, 2469, 31, 203, 3639, 364, 12, 11890, 277, 33, 20, 31, 277, 411, 358, 67, 1098, 18, 2469, 31, 277, 27245, 95, 203, 5411, 11013, 63, 869, 67, 1098, 63, 77, 13563, 1011, 460, 31, 203, 3639, 289, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: contracts/interfaces/ITransferRules.sol pragma solidity ^0.5.0; /** * @title ITransferRules interface * @dev Represents interface for any on-chain SRC20 transfer rules * implementation. Transfer Rules are expected to follow * same interface, managing multiply transfer rule implementations with * capabilities of managing what happens with tokens. * * This interface is working with ERC20 transfer() function */ interface ITransferRules { function setSRC(address src20) external returns (bool); function doTransfer(address from, address to, uint256 value) external returns (bool); } // File: contracts/interfaces/ISRC20.sol pragma solidity ^0.5.0; /** * @title SRC20 public interface */ interface ISRC20 { event RestrictionsAndRulesUpdated(address restrictions, address rules); function transferToken(address to, uint256 value, uint256 nonce, uint256 expirationTime, bytes32 msgHash, bytes calldata signature) external returns (bool); function transferTokenFrom(address from, address to, uint256 value, uint256 nonce, uint256 expirationTime, bytes32 hash, bytes calldata signature) external returns (bool); function getTransferNonce() external view returns (uint256); function getTransferNonce(address account) external view returns (uint256); function executeTransfer(address from, address to, uint256 value) external returns (bool); function updateRestrictionsAndRules(address restrictions, address rules) external returns (bool); // ERC20 part-like interface event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function 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 increaseAllowance(address spender, uint256 value) external returns (bool); function decreaseAllowance(address spender, uint256 value) external returns (bool); } // File: openzeppelin-solidity/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/rules/ManualApproval.sol pragma solidity ^0.5.0; /* * @title ManualApproval contract * @dev On-chain transfer rule that is handling transfer request/execution for * grey-listed account */ contract ManualApproval is Ownable { struct TransferReq { address from; address to; uint256 value; } uint256 public _reqNumber; ISRC20 public _src20; mapping(uint256 => TransferReq) public _transferReq; mapping(address => bool) public _greyList; event TransferRequest( uint256 indexed requestNumber, address from, address to, uint256 value ); event TransferApproval( uint256 indexed requestNumber, address indexed from, address indexed to, uint256 value ); event TransferRequestCanceled( uint256 indexed requestNumber, address indexed from, address indexed to, uint256 value ); constructor () public { } /** * @dev Owner of this contract have authority to approve tx which are valid. * * @param reqNumber - transfer request number. */ function transferApproval(uint256 reqNumber) external onlyOwner returns (bool) { TransferReq memory req = _transferReq[reqNumber]; require(_src20.executeTransfer(address(this), req.to, req.value), "SRC20 transfer failed"); delete _transferReq[reqNumber]; emit TransferApproval(reqNumber, req.from, req.to, req.value); return true; } /** * @dev Canceling transfer request and returning funds to from. * * @param reqNumber - transfer request number. */ function cancelTransferRequest(uint256 reqNumber) external returns (bool) { TransferReq memory req = _transferReq[reqNumber]; require(req.from == msg.sender, "Not owner of the transfer request"); require(_src20.executeTransfer(address(this), req.from, req.value), "SRC20: External transfer failed"); delete _transferReq[reqNumber]; emit TransferRequestCanceled(reqNumber, req.from, req.to, req.value); return true; } // Handling grey listing function isGreyListed(address account) public view returns (bool){ return _greyList[account]; } function greyListAccount(address account) external onlyOwner returns (bool) { _greyList[account] = true; return true; } function bulkGreyListAccount(address[] calldata accounts) external onlyOwner returns (bool) { for (uint256 i = 0; i < accounts.length ; i++) { address account = accounts[i]; _greyList[account] = true; } return true; } function unGreyListAccount(address account) external onlyOwner returns (bool) { delete _greyList[account]; return true; } function bulkUnGreyListAccount(address[] calldata accounts) external onlyOwner returns (bool) { for (uint256 i = 0; i < accounts.length ; i++) { address account = accounts[i]; delete _greyList[account]; } return true; } function _transferRequest(address from, address to, uint256 value) internal returns (bool) { require(_src20.executeTransfer(from, address(this), value), "SRC20 transfer failed"); _transferReq[_reqNumber] = TransferReq(from, to, value); emit TransferRequest(_reqNumber, from, to, value); _reqNumber = _reqNumber + 1; return true; } } // File: contracts/rules/Whitelisted.sol pragma solidity ^0.5.0; /** * @title Whitelisted transfer restriction example * @dev Example of simple transfer rule, having a list * of whitelisted addresses manged by owner, and checking * that from and to address in src20 transfer are whitelisted. */ contract Whitelisted is Ownable { mapping (address => bool) public _whitelisted; function whitelistAccount(address account) external onlyOwner { _whitelisted[account] = true; } function bulkWhitelistAccount(address[] calldata accounts) external onlyOwner { for (uint256 i = 0; i < accounts.length ; i++) { address account = accounts[i]; _whitelisted[account] = true; } } function unWhitelistAccount(address account) external onlyOwner { delete _whitelisted[account]; } function bulkUnWhitelistAccount(address[] calldata accounts) external onlyOwner { for (uint256 i = 0; i < accounts.length ; i++) { address account = accounts[i]; delete _whitelisted[account]; } } function isWhitelisted(address account) public view returns (bool) { return _whitelisted[account]; } } // File: contracts/interfaces/ITransferRestrictions.sol pragma solidity ^0.5.0; /** * @title ITransferRestrictions interface * @dev Represents interface for any on-chain SRC20 transfer restriction * implementation. Transfer Restriction registries are expected to follow * same interface, managing multiply transfer restriction implementations. * * It is intended to implementation of this interface be used for transferToken() */ interface ITransferRestrictions { function authorize(address from, address to, uint256 value) external returns (bool); } // File: contracts/rules/TransferRules.sol pragma solidity ^0.5.0; /* * @title TransferRules contract * @dev Contract that is checking if on-chain rules for token transfers are concluded. * It implements whitelist and grey list. */ contract TransferRules is ITransferRules, ManualApproval, Whitelisted { modifier onlySRC20 { require(msg.sender == address(_src20)); _; } constructor(address owner) public { _transferOwnership(owner); _whitelisted[owner] = true; } /** * @dev Set for what contract this rules are. * * @param src20 - Address of SRC20 contract. */ function setSRC(address src20) external returns (bool) { require(address(_src20) == address(0), "SRC20 already set"); _src20 = ISRC20(src20); return true; } /** * @dev Checks if transfer passes transfer rules. * * @param from The address to transfer from. * @param to The address to send tokens to. * @param value The amount of tokens to send. */ function authorize(address from, address to, uint256 value) public returns (bool) { return (isWhitelisted(from) || isGreyListed(from)) && (isWhitelisted(to) || isGreyListed(to)); } /** * @dev Do transfer and checks where funds should go. If both from and to are * on the whitelist funds should be transferred but if one of them are on the * grey list token-issuer/owner need to approve transfer. * * @param from The address to transfer from. * @param to The address to send tokens to. * @param value The amount of tokens to send. */ function doTransfer(address from, address to, uint256 value) external onlySRC20 returns (bool) { require(authorize(from, to, value), "Transfer not authorized"); if (isGreyListed(from) || isGreyListed(to)) { _transferRequest(from, to, value); return true; } require(ISRC20(_src20).executeTransfer(from, to, value), "SRC20 transfer failed"); return true; } }
* @dev Owner of this contract have authority to approve tx which are valid. @param reqNumber - transfer request number./
function transferApproval(uint256 reqNumber) external onlyOwner returns (bool) { TransferReq memory req = _transferReq[reqNumber]; require(_src20.executeTransfer(address(this), req.to, req.value), "SRC20 transfer failed"); delete _transferReq[reqNumber]; emit TransferApproval(reqNumber, req.from, req.to, req.value); return true; }
2,554,255
[ 1, 5541, 434, 333, 6835, 1240, 11675, 358, 6617, 537, 2229, 1492, 854, 923, 18, 225, 1111, 1854, 300, 7412, 590, 1300, 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 ]
[ 1, 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, 7412, 23461, 12, 11890, 5034, 1111, 1854, 13, 3903, 1338, 5541, 1135, 261, 6430, 13, 288, 203, 3639, 12279, 6113, 3778, 1111, 273, 389, 13866, 6113, 63, 3658, 1854, 15533, 203, 203, 3639, 2583, 24899, 4816, 3462, 18, 8837, 5912, 12, 2867, 12, 2211, 3631, 1111, 18, 869, 16, 1111, 18, 1132, 3631, 315, 28413, 3462, 7412, 2535, 8863, 203, 203, 3639, 1430, 389, 13866, 6113, 63, 3658, 1854, 15533, 203, 3639, 3626, 12279, 23461, 12, 3658, 1854, 16, 1111, 18, 2080, 16, 1111, 18, 869, 16, 1111, 18, 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 ]
./partial_match/56/0xfe18d6364D83D21fC0ce4fEaD6653cCBCF903835/sources/OXMasterFarmer.sol
The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorToOXSwap public migrator;
11,063,536
[ 1, 1986, 30188, 6835, 18, 2597, 711, 279, 17417, 434, 7212, 18, 4480, 1338, 506, 444, 3059, 314, 1643, 82, 1359, 261, 8443, 2934, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6246, 2757, 639, 774, 22550, 12521, 1071, 30188, 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 ]
./full_match/5/0x98061d960c2EaA127cB1921a6f912A2Ebb981Db4/sources/src/DonationHandler.sol
@notice Returns the token balance of a user @param _token Address of the token @param _user Address of the user @return Token balance of the user
function balanceOf(address _token, address _user) external view returns (uint256) { return balances[_user][_token]; }
11,624,867
[ 1, 1356, 326, 1147, 11013, 434, 279, 729, 225, 389, 2316, 5267, 434, 326, 1147, 225, 389, 1355, 5267, 434, 326, 729, 327, 3155, 11013, 434, 326, 729, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 11013, 951, 12, 2867, 389, 2316, 16, 1758, 389, 1355, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 324, 26488, 63, 67, 1355, 6362, 67, 2316, 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, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535 * * Implementation of a diamond. /******************************************************************************/ import { LibDiamond } from "./libraries/LibDiamond.sol"; import { IDiamondCut } from "./interfaces/IDiamondCut.sol"; import "./ErcDiamondStorage.sol"; contract Diamond is ErcDiamondStorage, IDiamondCut{ constructor(string memory _coinSymbol) ErcDiamondStorage(keccak256(abi.encodePacked(_coinSymbol, msg.sender, block.timestamp))) { LibDiamond.setContractOwner(_storagePos, msg.sender); } function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external override { LibDiamond.enforceIsContractOwner(_storagePos); LibDiamond.diamondCut(_storagePos, _diamondCut, _init, _calldata); } // Get Storage Position As Bytes32 function getStoragePosition() external view returns (bytes32 pos){ LibDiamond.enforceIsContractOwner(_storagePos); return _storagePos; } // Find facet for function that is called and execute the // function if a facet is found and return any value. fallback() external payable { LibDiamond.DiamondStorage storage ds; bytes32 position = _storagePos; // get diamond storage assembly { ds.slot := position } // get facet from function selector address facet = ds.selectorToFacetAndPosition[msg.sig].facetAddress; require(facet != address(0), "Diamond: Function does not exist"); // Execute external function from facet using delegatecall and return any value. assembly { // copy function selector and any arguments calldatacopy(0, 0, calldatasize()) // execute function call using the facet let result := delegatecall(gas(), facet, 0, calldatasize(), 0, 0) // get any return value returndatacopy(0, 0, returndatasize()) // return any return value or error back to the caller switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } receive() external payable {} }
Get Storage Position As Bytes32
function getStoragePosition() external view returns (bytes32 pos){ LibDiamond.enforceIsContractOwner(_storagePos); return _storagePos; }
13,122,657
[ 1, 967, 5235, 11010, 2970, 5985, 1578, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 13840, 2555, 1435, 3903, 1476, 1135, 261, 3890, 1578, 949, 15329, 203, 3639, 10560, 14521, 301, 1434, 18, 275, 5734, 2520, 8924, 5541, 24899, 5697, 1616, 1769, 203, 3639, 327, 389, 5697, 1616, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-05-25 */ pragma solidity ^0.4.18; contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract RaceNetZero is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function RaceNetZero() public { symbol = "RN0"; name = "RaceNetZero"; decimals = 18; _totalSupply = 1000000000000000000000000000; balances[0x49D6bbb7Ca6ED3EA94F39793400081960A1cfD0a] = _totalSupply; Transfer(address(0), 0x49D6bbb7Ca6ED3EA94F39793400081960A1cfD0a, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract RaceNetZero is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function RaceNetZero() public { symbol = "RN0"; name = "RaceNetZero"; decimals = 18; _totalSupply = 1000000000000000000000000000; balances[0x49D6bbb7Ca6ED3EA94F39793400081960A1cfD0a] = _totalSupply; Transfer(address(0), 0x49D6bbb7Ca6ED3EA94F39793400081960A1cfD0a, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
10,563,939
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 1551, 25444, 1147, 29375, 8879, 13849, 8879, 17082, 11417, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 534, 623, 7308, 7170, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 16, 14060, 10477, 288, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 225, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 1071, 389, 4963, 3088, 1283, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 203, 203, 565, 445, 534, 623, 7308, 7170, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 54, 50, 20, 14432, 203, 3639, 508, 273, 315, 54, 623, 7308, 7170, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 12648, 12648, 2787, 11706, 31, 203, 3639, 324, 26488, 63, 20, 92, 7616, 40, 26, 9897, 70, 27, 23508, 26, 2056, 23, 41, 37, 11290, 42, 5520, 7235, 5026, 3784, 28, 3657, 4848, 37, 21, 8522, 40, 20, 69, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 12279, 12, 2867, 12, 20, 3631, 374, 92, 7616, 40, 26, 9897, 70, 27, 23508, 26, 2056, 23, 41, 37, 11290, 42, 5520, 7235, 5026, 3784, 28, 3657, 4848, 37, 21, 8522, 40, 20, 69, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 5381, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 225, 300, 324, 26488, 63, 2867, 12, 20, 13, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 11013, 951, 12, 2867, 2 ]
pragma solidity ^0.5.0; import "../../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./Valset.sol"; import "./BridgeBank/BridgeBank.sol"; contract CosmosBridge { using SafeMath for uint256; string COSMOS_NATIVE_ASSET_PREFIX = "PEGGY"; /* * @dev: Public variable declarations */ address public operator; Valset public valset; address public oracle; bool public hasOracle; BridgeBank public bridgeBank; bool public hasBridgeBank; uint256 public prophecyClaimCount; mapping(uint256 => ProphecyClaim) public prophecyClaims; enum Status {Null, Pending, Success, Failed} enum ClaimType {Unsupported, Burn, Lock} struct ProphecyClaim { ClaimType claimType; bytes cosmosSender; address payable ethereumReceiver; address originalValidator; address tokenAddress; string symbol; uint256 amount; Status status; } /* * @dev: Event declarations */ event LogOracleSet(address _oracle); event LogBridgeBankSet(address _bridgeBank); event LogNewProphecyClaim( uint256 _prophecyID, ClaimType _claimType, bytes _cosmosSender, address payable _ethereumReceiver, address _validatorAddress, address _tokenAddress, string _symbol, uint256 _amount ); event LogProphecyCompleted(uint256 _prophecyID, ClaimType _claimType); /* * @dev: Modifier which only allows access to currently pending prophecies */ modifier isPending(uint256 _prophecyID) { require( isProphecyClaimActive(_prophecyID), "Prophecy claim is not active" ); _; } /* * @dev: Modifier to restrict access to the operator. */ modifier onlyOperator() { require(msg.sender == operator, "Must be the operator."); _; } /* * @dev: The bridge is not active until oracle and bridge bank are set */ modifier isActive() { require( hasOracle == true && hasBridgeBank == true, "The Operator must set the oracle and bridge bank for bridge activation" ); _; } /* * @dev: Constructor */ constructor(address _operator, address _valset) public { prophecyClaimCount = 0; operator = _operator; valset = Valset(_valset); hasOracle = false; hasBridgeBank = false; } /* * @dev: setOracle */ function setOracle(address _oracle) public onlyOperator { require( !hasOracle, "The Oracle cannot be updated once it has been set" ); hasOracle = true; oracle = _oracle; emit LogOracleSet(oracle); } /* * @dev: setBridgeBank */ function setBridgeBank(address payable _bridgeBank) public onlyOperator { require( !hasBridgeBank, "The Bridge Bank cannot be updated once it has been set" ); hasBridgeBank = true; bridgeBank = BridgeBank(_bridgeBank); emit LogBridgeBankSet(address(bridgeBank)); } /* * @dev: newProphecyClaim * Creates a new burn or lock prophecy claim, adding it to the prophecyClaims mapping. * Burn claims require that there are enough locked Ethereum assets to complete the prophecy. * Lock claims have a new token contract deployed or use an existing contract based on symbol. */ function newProphecyClaim( ClaimType _claimType, bytes memory _cosmosSender, address payable _ethereumReceiver, string memory _symbol, uint256 _amount ) public isActive { require( valset.isActiveValidator(msg.sender), "Must be an active validator" ); address tokenAddress; string memory symbol; if (_claimType == ClaimType.Burn) { require( bridgeBank.getLockedFunds(_symbol) >= _amount, "Not enough locked assets to complete the proposed prophecy" ); symbol = _symbol; tokenAddress = bridgeBank.getLockedTokenAddress(_symbol); } else if (_claimType == ClaimType.Lock) { symbol = concat(COSMOS_NATIVE_ASSET_PREFIX, _symbol); // Add 'PEGGY' symbol prefix address bridgeTokenAddress = bridgeBank.getBridgeToken(symbol); if (bridgeTokenAddress == address(0)) { // First lock of this asset, deploy new contract and get new symbol/token address tokenAddress = bridgeBank.createNewBridgeToken(symbol); } else { // Not the first lock of this asset, get existing symbol/token address tokenAddress = bridgeTokenAddress; } } else { revert("Invalid claim type, only burn and lock are supported."); } // Create the new ProphecyClaim ProphecyClaim memory prophecyClaim = ProphecyClaim( _claimType, _cosmosSender, _ethereumReceiver, msg.sender, tokenAddress, symbol, _amount, Status.Pending ); // Increment count and add the new ProphecyClaim to the mapping prophecyClaimCount = prophecyClaimCount.add(1); prophecyClaims[prophecyClaimCount] = prophecyClaim; emit LogNewProphecyClaim( prophecyClaimCount, _claimType, _cosmosSender, _ethereumReceiver, msg.sender, tokenAddress, symbol, _amount ); } /* * @dev: completeProphecyClaim * Allows for the completion of ProphecyClaims once processed by the Oracle. * Burn claims unlock tokens stored by BridgeBank. * Lock claims mint BridgeTokens on BridgeBank's token whitelist. */ function completeProphecyClaim(uint256 _prophecyID) public isPending(_prophecyID) { require( msg.sender == oracle, "Only the Oracle may complete prophecies" ); prophecyClaims[_prophecyID].status = Status.Success; ClaimType claimType = prophecyClaims[_prophecyID].claimType; if (claimType == ClaimType.Burn) { unlockTokens(_prophecyID); } else { issueBridgeTokens(_prophecyID); } emit LogProphecyCompleted(_prophecyID, claimType); } /* * @dev: issueBridgeTokens * Issues a request for the BridgeBank to mint new BridgeTokens */ function issueBridgeTokens(uint256 _prophecyID) internal { ProphecyClaim memory prophecyClaim = prophecyClaims[_prophecyID]; bridgeBank.mintBridgeTokens( prophecyClaim.cosmosSender, prophecyClaim.ethereumReceiver, prophecyClaim.tokenAddress, prophecyClaim.symbol, prophecyClaim.amount ); } /* * @dev: unlockTokens * Issues a request for the BridgeBank to unlock funds held on contract */ function unlockTokens(uint256 _prophecyID) internal { ProphecyClaim memory prophecyClaim = prophecyClaims[_prophecyID]; bridgeBank.unlock( prophecyClaim.ethereumReceiver, prophecyClaim.symbol, prophecyClaim.amount ); } /* * @dev: isProphecyClaimActive * Returns boolean indicating if the ProphecyClaim is active */ function isProphecyClaimActive(uint256 _prophecyID) public view returns (bool) { return prophecyClaims[_prophecyID].status == Status.Pending; } /* * @dev: isProphecyValidatorActive * Returns boolean indicating if the validator that originally * submitted the ProphecyClaim is still an active validator */ function isProphecyClaimValidatorActive(uint256 _prophecyID) public view returns (bool) { return valset.isActiveValidator( prophecyClaims[_prophecyID].originalValidator ); } /* * @dev: Performs low gas-comsuption string concatenation * * @param _prefix: start of the string * @param _suffix: end of the string */ function concat(string memory _prefix, string memory _suffix) internal pure returns (string memory) { return string(abi.encodePacked(_prefix, _suffix)); } }
@dev: newProphecyClaim Creates a new burn or lock prophecy claim, adding it to the prophecyClaims mapping. Burn claims require that there are enough locked Ethereum assets to complete the prophecy. Lock claims have a new token contract deployed or use an existing contract based on symbol./ First lock of this asset, deploy new contract and get new symbol/token address Not the first lock of this asset, get existing symbol/token address
function newProphecyClaim( ClaimType _claimType, bytes memory _cosmosSender, address payable _ethereumReceiver, string memory _symbol, uint256 _amount ) public isActive { require( valset.isActiveValidator(msg.sender), "Must be an active validator" ); address tokenAddress; string memory symbol; if (_claimType == ClaimType.Burn) { require( bridgeBank.getLockedFunds(_symbol) >= _amount, "Not enough locked assets to complete the proposed prophecy" ); symbol = _symbol; tokenAddress = bridgeBank.getLockedTokenAddress(_symbol); address bridgeTokenAddress = bridgeBank.getBridgeToken(symbol); if (bridgeTokenAddress == address(0)) { tokenAddress = bridgeBank.createNewBridgeToken(symbol); tokenAddress = bridgeTokenAddress; } revert("Invalid claim type, only burn and lock are supported."); } _claimType, _cosmosSender, _ethereumReceiver, msg.sender, tokenAddress, symbol, _amount, Status.Pending ); prophecyClaims[prophecyClaimCount] = prophecyClaim; emit LogNewProphecyClaim( prophecyClaimCount, _claimType, _cosmosSender, _ethereumReceiver, msg.sender, tokenAddress, symbol, _amount ); }
6,435,603
[ 1, 30, 394, 626, 844, 557, 93, 9762, 4202, 10210, 279, 394, 18305, 578, 2176, 450, 844, 557, 93, 7516, 16, 6534, 518, 358, 326, 450, 844, 557, 93, 15925, 2874, 18, 4202, 605, 321, 11955, 2583, 716, 1915, 854, 7304, 8586, 512, 18664, 379, 7176, 358, 3912, 326, 450, 844, 557, 93, 18, 4202, 3488, 11955, 1240, 279, 394, 1147, 6835, 19357, 578, 999, 392, 2062, 6835, 2511, 603, 3273, 18, 19, 5783, 2176, 434, 333, 3310, 16, 7286, 394, 6835, 471, 336, 394, 3273, 19, 2316, 1758, 2288, 326, 1122, 2176, 434, 333, 3310, 16, 336, 2062, 3273, 19, 2316, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 394, 626, 844, 557, 93, 9762, 12, 203, 3639, 18381, 559, 389, 14784, 559, 16, 203, 3639, 1731, 3778, 389, 14445, 26719, 12021, 16, 203, 3639, 1758, 8843, 429, 389, 546, 822, 379, 12952, 16, 203, 3639, 533, 3778, 389, 7175, 16, 203, 3639, 2254, 5034, 389, 8949, 203, 565, 262, 1071, 15083, 288, 203, 3639, 2583, 12, 203, 5411, 1244, 542, 18, 291, 3896, 5126, 12, 3576, 18, 15330, 3631, 203, 5411, 315, 10136, 506, 392, 2695, 4213, 6, 203, 3639, 11272, 203, 203, 3639, 1758, 1147, 1887, 31, 203, 3639, 533, 3778, 3273, 31, 203, 3639, 309, 261, 67, 14784, 559, 422, 18381, 559, 18, 38, 321, 13, 288, 203, 5411, 2583, 12, 203, 7734, 10105, 16040, 18, 588, 8966, 42, 19156, 24899, 7175, 13, 1545, 389, 8949, 16, 203, 7734, 315, 1248, 7304, 8586, 7176, 358, 3912, 326, 20084, 450, 844, 557, 93, 6, 203, 5411, 11272, 203, 5411, 3273, 273, 389, 7175, 31, 203, 5411, 1147, 1887, 273, 10105, 16040, 18, 588, 8966, 1345, 1887, 24899, 7175, 1769, 203, 5411, 1758, 10105, 1345, 1887, 273, 10105, 16040, 18, 588, 13691, 1345, 12, 7175, 1769, 203, 5411, 309, 261, 18337, 1345, 1887, 422, 1758, 12, 20, 3719, 288, 203, 7734, 1147, 1887, 273, 10105, 16040, 18, 2640, 1908, 13691, 1345, 12, 7175, 1769, 203, 7734, 1147, 1887, 273, 10105, 1345, 1887, 31, 203, 5411, 289, 203, 5411, 15226, 2932, 1941, 7516, 618, 16, 1338, 18305, 471, 2176, 854, 3260, 1199, 1769, 203, 3639, 289, 203, 203, 5411, 389, 14784, 2 ]
// SPDX-License-Identifier: MIT //** Demon Random Generation Contract */ //** Author Alex Hong : DEMONS 2021.12 */ pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@chainlink/contracts/src/v0.6/VRFConsumerBase.sol"; contract DemonRandom is Ownable, VRFConsumerBase { bytes32 internal keyHash; uint256 internal fee; uint256 public randomResult; uint256 public randomRange; address public spender; /** * Constructor inherits VRFConsumerBase * * Network: Kovan * Chainlink VRF Coordinator address: 0xb3dCcb4Cf7a26f6cf6B120Cf5A73875B7BBc655B * LINK token address: 0x01BE23585060835E02B77ef475b0Cc51aA1e0709 * Key Hash: 0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311 */ constructor() public VRFConsumerBase( 0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, 0x514910771AF9Ca656af840dff83E8264EcF986CA ) { keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445; fee = 2 * 10**18; // 0.1 LINK (Varies by network) } /** * Requests randomness */ function getRandomNumber() public returns (bytes32 requestId) { require(msg.sender == spender); require( LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet" ); return requestRandomness(keyHash, fee); } /** * Callback function used by VRF Coordinator */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override { randomResult = randomness.mod(randomRange).add(1); } function setRandomRange(uint256 _randomRange) external onlyOwner { require(_randomRange != 0, "It should bigger than 0 "); randomRange = _randomRange; } function setSpender(address _account) external onlyOwner { require(_account != address(0), "Invalid account for spender"); spender = _account; } function withdrawLink() external onlyOwner { LINK.transfer(msg.sender, LINK.balanceOf(address(this))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @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 SafeMathChainlink { /** * @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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success); function transferFrom(address from, address to, uint256 value) external returns (bool success); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed(bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce) internal pure returns (uint256) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId( bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./vendor/SafeMathChainlink.sol"; import "./interfaces/LinkTokenInterface.sol"; import "./VRFRequestIDBase.sol"; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { using SafeMathChainlink for uint256; /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 constant private USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness(bytes32 _keyHash, uint256 _fee) internal returns (bytes32 requestId) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash].add(1); return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface immutable internal LINK; address immutable private vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor(address _vrfCoordinator, address _link) public { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } }
* Requests randomness/
function getRandomNumber() public returns (bytes32 requestId) { require(msg.sender == spender); require( LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet" ); return requestRandomness(keyHash, fee); }
120,269
[ 1, 6421, 2744, 4496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 20581, 1854, 1435, 1071, 1135, 261, 3890, 1578, 14459, 13, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 17571, 264, 1769, 203, 3639, 2583, 12, 203, 5411, 22926, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 1545, 14036, 16, 203, 5411, 315, 1248, 7304, 22926, 300, 3636, 6835, 598, 11087, 5286, 278, 6, 203, 3639, 11272, 203, 3639, 327, 590, 8529, 4496, 12, 856, 2310, 16, 14036, 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 ]
./full_match/1/0xb43a17C3205Dfc6A00AE55D08ce4d5509704D218/sources/contracts/Senpai.sol
change this for your cexWallet
cexWallet = address(0x184aEba054189C26cB95dc0fa0e5369F296940C7);
3,848,811
[ 1, 3427, 333, 364, 3433, 276, 338, 16936, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 276, 338, 16936, 273, 1758, 12, 20, 92, 29242, 69, 41, 12124, 6260, 24, 29426, 39, 5558, 71, 38, 8778, 7201, 20, 507, 20, 73, 25, 5718, 29, 42, 5540, 8148, 7132, 39, 27, 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 ]
./full_match/421613/0x712A3480705560bB3158c8933403B04564305158/sources/project_/contracts/tokens/Corn.sol
Check to see if there is LAND in the farm
if (farm.amount == 0) {
11,566,787
[ 1, 1564, 358, 2621, 309, 1915, 353, 511, 4307, 316, 326, 284, 4610, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 309, 261, 74, 4610, 18, 8949, 422, 374, 13, 288, 4766, 21394, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.23; contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title Oracle Escrow * @dev The Oracle Escrow contract has an owner address, acting as the agent, a depositor, * and a beneficiary. It allows for funds to be held in escrow until a given real-world * external event has occurred. Relies on a unique Oracle contract address to be created * using smartcontract.com. Inheriting the Ownable contract allows for the agent to be updated * or removed from the contract without altering the execution of the contract or outcome. */ contract OracleEscrow is Ownable { uint256 public expiration; bool public contractExecuted; address public depositor; address public beneficiary; IOracle internal oracle; // Expected value is hard-coded into the contract and can be verified by all parties // before any deposit is made. bytes32 public constant EXPECTED = "yes"; // Expiration date should be a factor of days to prevent timestamp dependence. // https://consensys.github.io/smart-contract-best-practices/recommendations/#timestamp-dependence uint256 internal constant TO_EXPIRE = 75 days; /** * @dev The OracleEscrow constructor sets the oracle, depositor, and beneficiary addresses. * It also sets the `contractExecuted` field to `false` and sets the expiration of the agreement * to be 30 days after the OracleEscrow contract has been deployed. * @param _oracle address, the address of the deployed Oracle contract. * @param _depositor address, the address of the depositor. * @param _beneficiary address, the address of the beneficiary. */ constructor(address _oracle, address _depositor, address _beneficiary) public payable Ownable() { oracle = IOracle(_oracle); depositor = _depositor; beneficiary = _beneficiary; contractExecuted = false; expiration = now + TO_EXPIRE; } /** * @dev Logs a message indicating where the escrow payment was sent to. */ event ContractExecuted(bytes32 message); /** * @dev payable fallback only allows the depositor to send funds, as long as the contract * hasn&#39;t been executed already, and the expiration has not been passed. */ function() external payable onlyDepositor { require(contractExecuted == false); require(now < expiration); } /** * @dev Executes the contract if called by an authorized user and the balance of the escrow * is greater than 0. If the Oracle contract&#39;s reported value is the expected value, payment * goes to the beneficiary. If the escrow contract has gone passed the expiration and the * Oracle contract&#39;s reported value still is not what is expected, payment is returned to * the depositor. */ function executeContract() public checkAuthorizedUser() { require(address(this).balance > 0); if (oracle.current() == EXPECTED) { contractExecuted = true; emit ContractExecuted("Payment sent to beneficiary."); beneficiary.transfer(address(this).balance); } else if (now >= expiration) { contractExecuted = true; emit ContractExecuted("Payment refunded to depositor."); depositor.transfer(address(this).balance); } } /** * @dev Check the current value stored on the Oracle contract. * @return The current value at the Oracle contract. */ function requestOracleValue() public view onlyOwner returns(bytes32) { return oracle.current(); } /** * @dev Reverts if called by any account other than the owner, depositor, or beneficiary. */ modifier checkAuthorizedUser() { require(msg.sender == owner || msg.sender == depositor || msg.sender == beneficiary, "Only authorized users may call this function."); _; } /** * @dev Reverts if called by any account other than the depositor. */ modifier onlyDepositor() { require(msg.sender == depositor, "Only the depositor may call this function."); _; } } /** * @dev Interface for the Oracle contract. */ interface IOracle{ function current() view external returns(bytes32); }
* @dev Reverts if called by any account other than the depositor./
modifier onlyDepositor() { require(msg.sender == depositor, "Only the depositor may call this function."); _; }
2,353,689
[ 1, 426, 31537, 309, 2566, 635, 1281, 2236, 1308, 2353, 326, 443, 1724, 280, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 9606, 1338, 758, 1724, 280, 1435, 288, 203, 565, 2583, 12, 3576, 18, 15330, 422, 443, 1724, 280, 16, 315, 3386, 326, 443, 1724, 280, 2026, 745, 333, 445, 1199, 1769, 203, 565, 389, 31, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >=0.6.0; interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } interface InterfaceTimeToken { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function debtOf(address owner) 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); } interface TimeswapCallee { function timeswapCall(address sender, uint256 presentOut, uint256 futureOut, bytes calldata data) external; } library SafeMathUint256 { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, "SafeMathUint256: Add Overflow"); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "SafeMathUint256: Sub Overflow"); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "SafeMathUint256: Mul Overflow"); } function div(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y > 0, "SafeMathUint256: Div Overflow"); z = x / y; } } contract Timeswap { using SafeMathUint256 for uint256; // CONSTANT bytes4 private constant SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)"))); address private constant _factory = address(0); address private constant _presentToken = address(0); address private constant _futureToken = address(0); uint16 private constant _maturityDate = 0; uint256 constant MATURITY_TIME = 1593561600; // MODEL uint112 private _tokenReserve; uint112 private _equityReserve; uint32 private _blockTimestampLast; uint256 private _priceCumulativeLast; uint256 private _invariance; // EVENT // UPDATE function receive(uint256 presentOut, address to, bytes calldata data) external { require(block.timestamp >= MATURITY_TIME, "Timeswap: NOT MATURE"); require(presentOut > 0, "Timeswap: Insufficient Output"); (uint256 tokenReserve,,,) = reserves(); require(presentOut <= tokenReserve); uint256 tokenBalance; uint256 equityBalance; { address presentToken = _presentToken; require(to != presentToken, "Timeswap: Invalid To"); if (presentOut > 0) _safeTransfer(presentToken, to, presentOut); // optimistically transfer tokens } } function swap(uint256 presentOut, uint256 futureOut, address to, bytes calldata data) external { require(presentOut > 0 || futureOut > 0, "Timeswap: Insufficient Output"); (uint256 tokenReserve, uint256 equityReserve, uint256 interestReserve,) = reserves(); require(presentOut < tokenReserve && futureOut < tokenReserve.add(interestReserve), "Timeswap: Insufficient Reserve"); uint256 tokenBalance; uint256 equityBalance; { address presentToken = _presentToken; address futureToken = _futureToken; require(to != presentToken && to != futureToken, "Timeswap: Invalid To"); if (presentOut > 0) _safeTransfer(presentToken, to, presentOut); // optimistically trasfer tokens if (futureOut > 0) _safeTransfer(futureToken, to, futureOut); // optimistically transfer tokens if (data.length > 0) TimeswapCallee(to).timeswapCall(msg.sender, presentOut, futureOut, data); tokenBalance = IERC20(presentToken).balanceOf(address(this)); uint256 balance = InterfaceTimeToken(futureToken).balanceOf(address(this)); uint256 debt = InterfaceTimeToken(futureToken).debtOf(address(this)); equityBalance = debt == 0 ? tokenBalance.add(balance) : tokenBalance.sub(debt); } uint256 presentIn = tokenBalance > tokenReserve - presentOut ? tokenBalance - (tokenReserve - presentOut) : 0; uint256 futureIn = equityBalance > equityReserve + presentIn - futureOut ? equityBalance + presentOut - (interestReserve + presentIn - futureOut) : 0; require(presentIn > 0 || futureIn > 0, "Timeswap: Insufficient Input"); { uint256 _presentOut = presentOut; uint256 interestBalance = interestReserve.add(futureIn).sub(futureOut); uint256 interestAdjusted = interestBalance.mul(10).sub(futureIn.sub(_presentOut).mul(3)); require(tokenBalance.mul(interestAdjusted) >= _invariance.mul(10), "Timeswap: Constant Product"); } _update(tokenBalance, equityBalance, tokenReserve, interestReserve); } // VIEW function reserves() public view returns (uint256 tokenReserve, uint256 equityReserve, uint256 interestReserve, uint32 blockTimestampLast) { tokenReserve = uint256(_tokenReserve); equityReserve = uint256(_equityReserve); interestReserve = _invariance.div(tokenReserve); blockTimestampLast = _blockTimestampLast; } // HELPER function _update(uint256 tokenBalance, uint256 equityBalance, uint256 tokenReserve, uint256 interestReserve) private { require(tokenBalance <= uint112(-1) && equityBalance <= uint112(-1), "Timeswap: Overflow"); uint32 blockTimestamp = uint32(block.timestamp % (2**32)); uint32 timeElapsed = blockTimestamp - _blockTimestampLast; // overflow is desired if (timeElapsed > 0 && tokenReserve != 0 && interestReserve != 0) { // never overflows // overflow is desired _priceCumulativeLast += interestReserve / tokenReserve * timeElapsed; // FIX must be interest insted of equity } _tokenReserve = uint112(tokenBalance); _equityReserve = uint112(equityBalance); _blockTimestampLast = blockTimestamp; } function _safeTransfer(address token, address to, uint256 value) private { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "Timeswap: Transfer Failed"); } }
optimistically transfer tokens
if (presentOut > 0) _safeTransfer(presentToken, to, presentOut);
13,140,030
[ 1, 16689, 5846, 1230, 7412, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 261, 6706, 1182, 405, 374, 13, 389, 4626, 5912, 12, 6706, 1345, 16, 358, 16, 3430, 1182, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-07-05 */ // Verified using https://dapp.tools // hevm: flattened sources of src/fabs/mgr.sol pragma solidity =0.5.12; ////// src/mgr.sol /// tinlake_manager.sol -- Tinlake dss adapter // 2020 Lucas Vogelsang <[email protected]>, // 2020 Martin Lundfall <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity =0.5.12; */ interface GemLike_3 { function decimals() external view returns (uint256); function transfer(address,uint256) external returns (bool); function transferFrom(address,address,uint256) external returns (bool); function approve(address,uint256) external returns (bool); function totalSupply() external returns (uint256); function balanceOf(address) external returns (uint256); } interface JoinLike { function join(address,uint256) external; function exit(address,uint256) external; } interface EndLike { function debt() external returns (uint256); } interface RedeemLike { function redeemOrder(uint256) external; function disburse(uint256) external returns (uint256,uint256,uint256,uint256); } interface VatLike_5 { function urns(bytes32,address) external returns (uint256,uint256); function ilks(bytes32) external returns (uint256,uint256,uint256,uint256,uint256); function live() external returns(uint); } interface GemJoinLike { function gem() external returns (address); function ilk() external returns (bytes32); } interface MIP21UrnLike { function lock(uint256 wad) external; function free(uint256 wad) external; // n.b. DAI can only go to the output conduit function draw(uint256 wad) external; // n.b. anyone can wipe function wipe(uint256 wad) external; function quit() external; function gemJoin() external returns (address); } interface MIP21LiquidationLike { function ilks(bytes32 ilk) external returns (string memory, address, uint48, uint48); } contract TinlakeManager { // --- Auth --- mapping (address => uint256) public wards; function rely(address usr) external auth { wards[usr] = 1; emit Rely(usr); } function deny(address usr) external auth { wards[usr] = 0; emit Deny(usr); } modifier auth { require(wards[msg.sender] == 1, "TinlakeMgr/not-authorized"); _; } // Events event Rely(address indexed usr); event Deny(address indexed usr); event Draw(uint256 wad); event Wipe(uint256 wad); event Join(uint256 wad); event Exit(uint256 wad); event Tell(uint256 wad); event Unwind(uint256 payBack); event Cull(uint256 tab); event Recover(uint256 recovered, uint256 payBack); event Cage(); event File(bytes32 indexed what, address indexed data); event Migrate(address indexed dst); bool public safe; // Soft liquidation not triggered bool public glad; // Write-off not triggered bool public live; // Global settlement not triggered uint256 public tab; // Dai owed // --- Contracts --- // dss components VatLike_5 public vat; GemLike_3 public dai; EndLike public end; address public vow; JoinLike public daiJoin; // Tinlake components GemLike_3 public gem; RedeemLike public pool; // MIP21 RWAUrn MIP21UrnLike public urn; MIP21LiquidationLike public liq; address public tranche; address public owner; constructor(address dai_, address daiJoin_, address drop_, address pool_, address tranche_, address end_, address vat_, address vow_ ) public { dai = GemLike_3(dai_); daiJoin = JoinLike(daiJoin_); vat = VatLike_5(vat_); vow = vow_; end = EndLike(end_); gem = GemLike_3(drop_); pool = RedeemLike(pool_); wards[msg.sender] = 1; emit Rely(msg.sender); safe = true; glad = true; live = true; tranche = tranche_; } // --- Math --- uint256 constant RAY = 10 ** 27; function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } function divup(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(x, sub(y, 1)) / y; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x > y ? y : x; } // --- Gem Operation --- // moves the rwaToken into the vault // requires that mgr contract holds the rwaToken function lock(uint256 wad) public auth { GemLike_3(GemJoinLike(urn.gemJoin()).gem()).approve(address(urn), uint256(wad)); urn.lock(wad); } // removes the rwaToken from the vault function free(uint256 wad) public auth { urn.free(wad); } // --- DROP Operation --- // join & exit move the gem directly into/from the urn function join(uint256 wad) public auth { require(safe && live, "TinlakeManager/bad-state"); require(int256(wad) >= 0, "TinlakeManager/overflow"); gem.transferFrom(msg.sender, address(this), wad); emit Join(wad); } function exit(uint256 wad) public auth { require(safe && live, "TinlakeManager/bad-state"); require(wad <= 2 ** 255, "TinlakeManager/overflow"); gem.transfer(msg.sender, wad); emit Exit(wad); } // --- DAI Operation --- // draw & wipe call daiJoin.exit/join immediately function draw(uint256 wad) public auth { require(safe && live, "TinlakeManager/bad-state"); urn.draw(wad); dai.transfer(msg.sender, wad); emit Draw(wad); } function wipe(uint256 wad) public { require(safe && live, "TinlakeManager/bad-state"); dai.transferFrom(msg.sender, address(urn), wad); urn.wipe(wad); emit Wipe(wad); } // Take DAI from the urn in case there is any in the Urn // can be dealt with through migrate() after ES function quit() public auth { urn.quit(); } // --- Administration --- function migrate(address dst) public auth { dai.approve(dst, uint256(-1)); gem.approve(dst, uint256(-1)); live = false; emit Migrate(dst); } function file(bytes32 what, address data) public auth { emit File(what, data); if (what == "urn") { urn = MIP21UrnLike(data); dai.approve(data, uint256(-1)); } else if (what == "liq") { liq = MIP21LiquidationLike(data); } else if (what == "owner") { owner = data; } else if (what == "vow") { vow = data; } else if (what == "end") { end = EndLike(data); } else if (what == "pool") { pool = RedeemLike(data); } else if (what == "tranche") { tranche = data; } else revert("TinlakeMgr/file-unknown-param"); } // --- Liquidation --- // triggers a soft liquidation of the DROP collateral // a redeemOrder is submitted to receive DAI back function tell() public { require(safe, "TinlakeMgr/not-safe"); bytes32 ilk = GemJoinLike(urn.gemJoin()).ilk(); (,,, uint48 toc) = liq.ilks(ilk); require(toc != 0, "TinlakeMgr/not-liquidated"); (, uint256 art) = vat.urns(ilk, address(urn)); (, uint256 rate, , ,) = vat.ilks(ilk); tab = mul(art, rate); uint256 ink = gem.balanceOf(address(this)); safe = false; gem.approve(tranche, ink); pool.redeemOrder(ink); emit Tell(ink); } // triggers the payout of a DROP redemption // method can be called multiple times until all DROP is redeemed function unwind(uint256 endEpoch) public { require(!safe && glad && live, "TinlakeMgr/not-soft-liquidation"); (uint256 redeemed, , ,) = pool.disburse(endEpoch); bytes32 ilk = GemJoinLike(urn.gemJoin()).ilk(); (, uint256 art) = vat.urns(ilk, address(urn)); (, uint256 rate, , ,) = vat.ilks(ilk); uint256 tab_ = mul(art, rate); uint256 payBack = min(redeemed, divup(tab_, RAY)); dai.transferFrom(address(this), address(urn), payBack); urn.wipe(payBack); // Return possible remainder to the owner dai.transfer(owner, dai.balanceOf(address(this))); tab = sub(tab_, mul(payBack, RAY)); emit Unwind(payBack); } // --- Write-off --- // can be called after RwaLiquidationOracle.cull() function cull() public { require(!safe && glad && live, "TinlakeMgr/bad-state"); bytes32 ilk = GemJoinLike(urn.gemJoin()).ilk(); (uint256 ink, uint256 art) = vat.urns(ilk, address(urn)); require(ink == 0 && art == 0, "TinlakeMgr/not-written-off"); (,, uint48 tau, uint48 toc) = liq.ilks(ilk); require(toc != 0, "TinlakeMgr/not-liquidated"); require(block.timestamp >= add(toc, tau), "TinlakeMgr/early-cull"); glad = false; emit Cull(tab); } // recovers DAI from the Tinlake pool by triggering a payout // method can be called multiple times until all DROP is redeemed function recover(uint256 endEpoch) public { require(!glad, "TinlakeMgr/not-written-off"); (uint256 recovered, , ,) = pool.disburse(endEpoch); uint256 payBack; if (end.debt() == 0) { payBack = min(recovered, tab / RAY); dai.approve(address(daiJoin), payBack); daiJoin.join(vow, payBack); tab = sub(tab, mul(payBack, RAY)); } dai.transfer(owner, dai.balanceOf(address(this))); emit Recover(recovered, payBack); } function cage() external { require(!glad, "TinlakeMgr/bad-state"); require(wards[msg.sender] == 1 || vat.live() == 0, "TinlakeMgr/not-authorized"); live = false; emit Cage(); } }
--- Administration ---
function migrate(address dst) public auth { dai.approve(dst, uint256(-1)); gem.approve(dst, uint256(-1)); live = false; emit Migrate(dst); }
226,126
[ 1, 6062, 7807, 4218, 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, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 13187, 12, 2867, 3046, 13, 1071, 1357, 288, 203, 3639, 5248, 77, 18, 12908, 537, 12, 11057, 16, 2254, 5034, 19236, 21, 10019, 203, 3639, 17474, 18, 12908, 537, 12, 11057, 16, 2254, 5034, 19236, 21, 10019, 203, 3639, 8429, 273, 629, 31, 203, 3639, 3626, 26507, 12, 11057, 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 ]
./partial_match/1/0x98b7893C5717aF41d3e351c6e3445Be02a062A90/sources/contracts/MapleLoanStorage.sol
The number of seconds a payment can be late.
uint256 internal _gracePeriod;
3,924,840
[ 1, 1986, 1300, 434, 3974, 279, 5184, 848, 506, 26374, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 2713, 389, 2752, 311, 5027, 31, 4202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.11; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/utils/SafeCast.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import "./interfaces/IDefiRound.sol"; import "./interfaces/IWETH.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; contract DefiRound is IDefiRound, Ownable { using SafeMath for uint256; using SafeCast for int256; using SafeERC20 for IERC20; using Address for address; using Address for address payable; using EnumerableSet for EnumerableSet.AddressSet; // solhint-disable-next-line address public immutable WETH; address public immutable override treasury; OversubscriptionRate public overSubscriptionRate; mapping(address => uint256) public override totalSupply; // account -> accountData mapping(address => AccountData) private accountData; mapping(address => RateData) private tokenRates; //Token -> oracle, genesis mapping(address => SupportedTokenData) private tokenSettings; EnumerableSet.AddressSet private supportedTokens; EnumerableSet.AddressSet private configuredTokenRates; STAGES public override currentStage; WhitelistSettings public whitelistSettings; uint256 public lastLookExpiration = type(uint256).max; uint256 private immutable maxTotalValue; bool private stage1Locked; constructor( // solhint-disable-next-line address _WETH, address _treasury, uint256 _maxTotalValue ) public { require(_WETH != address(0), "INVALID_WETH"); require(_treasury != address(0), "INVALID_TREASURY"); require(_maxTotalValue > 0, "INVALID_MAXTOTAL"); WETH = _WETH; treasury = _treasury; currentStage = STAGES.STAGE_1; maxTotalValue = _maxTotalValue; } function deposit(TokenData calldata tokenInfo, bytes32[] memory proof) external payable override { require(currentStage == STAGES.STAGE_1, "DEPOSITS_NOT_ACCEPTED"); require(!stage1Locked, "DEPOSITS_LOCKED"); if (whitelistSettings.enabled) { require( verifyDepositor(msg.sender, whitelistSettings.root, proof), "PROOF_INVALID" ); } TokenData memory data = tokenInfo; address token = data.token; uint256 tokenAmount = data.amount; require(supportedTokens.contains(token), "UNSUPPORTED_TOKEN"); require(tokenAmount > 0, "INVALID_AMOUNT"); // Convert ETH to WETH if ETH is passed in, otherwise treat WETH as a regular ERC20 if (token == WETH && msg.value > 0) { require(tokenAmount == msg.value, "INVALID_MSG_VALUE"); IWETH(WETH).deposit{value: tokenAmount}(); } else { require(msg.value == 0, "NO_ETH"); } AccountData storage tokenAccountData = accountData[msg.sender]; if (tokenAccountData.token == address(0)) { tokenAccountData.token = token; } require(tokenAccountData.token == token, "SINGLE_ASSET_DEPOSITS"); tokenAccountData.initialDeposit = tokenAccountData.initialDeposit.add( tokenAmount ); tokenAccountData.currentBalance = tokenAccountData.currentBalance.add( tokenAmount ); require( tokenAccountData.currentBalance <= tokenSettings[token].maxLimit, "MAX_LIMIT_EXCEEDED" ); // No need to transfer from msg.sender since is ETH was converted to WETH if (!(token == WETH && msg.value > 0)) { IERC20(token).safeTransferFrom( msg.sender, address(this), tokenAmount ); } if (_totalValue() >= maxTotalValue) { stage1Locked = true; } emit Deposited(msg.sender, tokenInfo); } // solhint-disable-next-line no-empty-blocks receive() external payable { require(msg.sender == WETH); } //We disallow withdrawal /* function withdraw(TokenData calldata tokenInfo, bool asETH) external override { require(currentStage == STAGES.STAGE_2, "WITHDRAWS_NOT_ACCEPTED"); require(!_isLastLookComplete(), "WITHDRAWS_EXPIRED"); TokenData memory data = tokenInfo; address token = data.token; uint256 tokenAmount = data.amount; require(supportedTokens.contains(token), "UNSUPPORTED_TOKEN"); require(tokenAmount > 0, "INVALID_AMOUNT"); AccountData storage tokenAccountData = accountData[msg.sender]; require(token == tokenAccountData.token, "INVALID_TOKEN"); tokenAccountData.currentBalance = tokenAccountData.currentBalance.sub( tokenAmount ); // set the data back in the mapping, otherwise updates are not saved accountData[msg.sender] = tokenAccountData; // Don't transfer WETH, WETH is converted to ETH and sent to the recipient if (token == WETH && asETH) { IWETH(WETH).withdraw(tokenAmount); msg.sender.sendValue(tokenAmount); } else { IERC20(token).safeTransfer(msg.sender, tokenAmount); } emit Withdrawn(msg.sender, tokenInfo, asETH); } */ function configureWhitelist(WhitelistSettings memory settings) external override onlyOwner { whitelistSettings = settings; emit WhitelistConfigured(settings); } function addSupportedTokens(SupportedTokenData[] calldata tokensToSupport) external override onlyOwner { uint256 tokensLength = tokensToSupport.length; for (uint256 i = 0; i < tokensLength; i++) { SupportedTokenData memory data = tokensToSupport[i]; require(supportedTokens.add(data.token), "TOKEN_EXISTS"); tokenSettings[data.token] = data; } emit SupportedTokensAdded(tokensToSupport); } function getSupportedTokens() external view override returns (address[] memory tokens) { uint256 tokensLength = supportedTokens.length(); tokens = new address[](tokensLength); for (uint256 i = 0; i < tokensLength; i++) { tokens[i] = supportedTokens.at(i); } } function publishRates( RateData[] calldata ratesData, OversubscriptionRate memory oversubRate, uint256 lastLookDuration ) external override onlyOwner { // check rates havent been published before require(currentStage == STAGES.STAGE_1, "RATES_ALREADY_SET"); //require(lastLookDuration > 0, "INVALID_DURATION"); require(oversubRate.overDenominator > 0, "INVALID_DENOMINATOR"); require(oversubRate.overNumerator > 0, "INVALID_NUMERATOR"); uint256 ratesLength = ratesData.length; for (uint256 i = 0; i < ratesLength; i++) { RateData memory data = ratesData[i]; require(data.numerator > 0, "INVALID_NUMERATOR"); require(data.denominator > 0, "INVALID_DENOMINATOR"); require( tokenRates[data.token].token == address(0), "RATE_ALREADY_SET" ); require(configuredTokenRates.add(data.token), "ALREADY_CONFIGURED"); tokenRates[data.token] = data; } require( configuredTokenRates.length() == supportedTokens.length(), "MISSING_RATE" ); // Stage only moves forward when prices are published currentStage = STAGES.STAGE_2; lastLookExpiration = block.number + lastLookDuration; overSubscriptionRate = oversubRate; emit RatesPublished(ratesData); } function getRates(address[] calldata tokens) external view override returns (RateData[] memory rates) { uint256 tokensLength = tokens.length; rates = new RateData[](tokensLength); for (uint256 i = 0; i < tokensLength; i++) { rates[i] = tokenRates[tokens[i]]; } } function getTokenValue(address token, uint256 balance) internal view returns (uint256 value) { uint256 tokenDecimals = ERC20(token).decimals(); (, int256 tokenRate, , , ) = AggregatorV3Interface( tokenSettings[token].oracle ).latestRoundData(); uint256 rate = tokenRate.toUint256(); value = (balance.mul(rate)).div(10**tokenDecimals); //Chainlink USD prices are always to 8 } function totalValue() external view override returns (uint256) { return _totalValue(); } function _totalValue() internal view returns (uint256 value) { uint256 tokensLength = supportedTokens.length(); for (uint256 i = 0; i < tokensLength; i++) { address token = supportedTokens.at(i); uint256 tokenBalance = IERC20(token).balanceOf(address(this)); value = value.add(getTokenValue(token, tokenBalance)); } } function accountBalance(address account) external view override returns (uint256 value) { uint256 tokenBalance = accountData[account].currentBalance; value = value.add( getTokenValue(accountData[account].token, tokenBalance) ); } function finalizeAssets() external override { require(currentStage == STAGES.STAGE_3, "NOT_SYSTEM_FINAL"); AccountData storage data = accountData[msg.sender]; address token = data.token; require(token != address(0), "NO_DATA"); (, uint256 ineffective, ) = _getRateAdjustedAmounts( data.currentBalance, token ); require(ineffective > 0, "NOTHING_TO_MOVE"); // zero out balance data.currentBalance = 0; accountData[msg.sender] = data; // transfer ineffectiveTokenBalance back to user IERC20(token).safeTransfer(msg.sender, ineffective); emit AssetsFinalized(msg.sender, token, ineffective); } function getGenesisPools(address[] calldata tokens) external view override returns (address[] memory genesisAddresses) { uint256 tokensLength = tokens.length; genesisAddresses = new address[](tokensLength); for (uint256 i = 0; i < tokensLength; i++) { require(supportedTokens.contains(tokens[i]), "TOKEN_UNSUPPORTED"); genesisAddresses[i] = tokenSettings[supportedTokens.at(i)].genesis; } } function getTokenOracles(address[] calldata tokens) external view override returns (address[] memory oracleAddresses) { uint256 tokensLength = tokens.length; oracleAddresses = new address[](tokensLength); for (uint256 i = 0; i < tokensLength; i++) { require(supportedTokens.contains(tokens[i]), "TOKEN_UNSUPPORTED"); oracleAddresses[i] = tokenSettings[tokens[i]].oracle; } } function getAccountData(address account) external view override returns (AccountDataDetails[] memory data) { uint256 supportedTokensLength = supportedTokens.length(); data = new AccountDataDetails[](supportedTokensLength); for (uint256 i = 0; i < supportedTokensLength; i++) { address token = supportedTokens.at(i); AccountData memory accountTokenInfo = accountData[account]; if ( currentStage >= STAGES.STAGE_2 && accountTokenInfo.token != address(0) ) { ( uint256 effective, uint256 ineffective, uint256 actual ) = _getRateAdjustedAmounts( accountTokenInfo.currentBalance, token ); AccountDataDetails memory details = AccountDataDetails( token, accountTokenInfo.initialDeposit, accountTokenInfo.currentBalance, effective, ineffective, actual ); data[i] = details; } else { data[i] = AccountDataDetails( token, accountTokenInfo.initialDeposit, accountTokenInfo.currentBalance, 0, 0, 0 ); } } } function transferToTreasury() external override onlyOwner { require(_isLastLookComplete(), "CURRENT_STAGE_INVALID"); require(currentStage == STAGES.STAGE_2, "ONLY_TRANSFER_ONCE"); uint256 supportedTokensLength = supportedTokens.length(); TokenData[] memory tokens = new TokenData[](supportedTokensLength); for (uint256 i = 0; i < supportedTokensLength; i++) { address token = supportedTokens.at(i); uint256 balance = IERC20(token).balanceOf(address(this)); (uint256 effective, , ) = _getRateAdjustedAmounts(balance, token); tokens[i].token = token; tokens[i].amount = effective; IERC20(token).safeTransfer(treasury, effective); } currentStage = STAGES.STAGE_3; emit TreasuryTransfer(tokens); } function getRateAdjustedAmounts(uint256 balance, address token) external view override returns ( uint256, uint256, uint256 ) { return _getRateAdjustedAmounts(balance, token); } function getMaxTotalValue() external view override returns (uint256) { return maxTotalValue; } function _getRateAdjustedAmounts(uint256 balance, address token) internal view returns ( uint256, uint256, uint256 ) { require(currentStage >= STAGES.STAGE_2, "RATES_NOT_PUBLISHED"); RateData memory rateInfo = tokenRates[token]; uint256 effectiveTokenBalance = balance .mul(overSubscriptionRate.overNumerator) .div(overSubscriptionRate.overDenominator); uint256 ineffectiveTokenBalance = balance .mul( overSubscriptionRate.overDenominator.sub( overSubscriptionRate.overNumerator ) ) .div(overSubscriptionRate.overDenominator); uint256 actualReceived = effectiveTokenBalance .mul(rateInfo.denominator) .div(rateInfo.numerator); return (effectiveTokenBalance, ineffectiveTokenBalance, actualReceived); } function verifyDepositor( address participant, bytes32 root, bytes32[] memory proof ) internal pure returns (bool) { bytes32 leaf = keccak256((abi.encodePacked((participant)))); return MerkleProof.verify(proof, root, leaf); } function _isLastLookComplete() internal view returns (bool) { return block.number >= lastLookExpiration; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface AggregatorV3Interface { function decimals() external view returns ( uint8 ); function description() external view returns ( string memory ); function version() external view returns ( uint256 ); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData( uint80 _roundId ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; interface IDefiRound { enum STAGES {STAGE_1, STAGE_2, STAGE_3} struct AccountData { address token; // address of the allowed token deposited uint256 initialDeposit; // initial amount deposited of the token uint256 currentBalance; // current balance of the token that can be used to claim INSURE } struct AccountDataDetails { address token; // address of the allowed token deposited uint256 initialDeposit; // initial amount deposited of the token uint256 currentBalance; // current balance of the token that can be used to claim INSURE uint256 effectiveAmt; //Amount deposited that will be used towards INSURE uint256 ineffectiveAmt; //Amount deposited that will be either refunded or go to farming uint256 actualTokeReceived; //Amount of INSURE that will be received } struct TokenData { address token; uint256 amount; } struct SupportedTokenData { address token; address oracle; address genesis; uint256 maxLimit; } struct RateData { address token; uint256 numerator; uint256 denominator; } struct OversubscriptionRate { uint256 overNumerator; uint256 overDenominator; } event Deposited(address depositor, TokenData tokenInfo); event Withdrawn(address withdrawer, TokenData tokenInfo, bool asETH); event SupportedTokensAdded(SupportedTokenData[] tokenData); event RatesPublished(RateData[] ratesData); event GenesisTransfer(address user, uint256 amountTransferred); event AssetsFinalized(address claimer, address token, uint256 assetsMoved); event WhitelistConfigured(WhitelistSettings settings); event TreasuryTransfer(TokenData[] tokens); struct TokenValues { uint256 effectiveTokenValue; uint256 ineffectiveTokenValue; } struct WhitelistSettings { bool enabled; bytes32 root; } /// @notice Enable or disable the whitelist /// @param settings The root to use and whether to check the whitelist at all function configureWhitelist(WhitelistSettings calldata settings) external; /// @notice returns the current stage the contract is in /// @return stage the current stage the round contract is in function currentStage() external returns (STAGES stage); /// @notice deposits tokens into the round contract /// @param tokenData an array of token structs function deposit(TokenData calldata tokenData, bytes32[] memory proof) external payable; /// @notice total value held in the entire contract amongst all the assets /// @return value the value of all assets held function totalValue() external view returns (uint256 value); /// @notice Current Max Total Value /// @return value the max total value function getMaxTotalValue() external view returns (uint256 value); /// @notice returns the address of the treasury, when users claim this is where funds that are <= maxClaimableValue go /// @return treasuryAddress address of the treasury function treasury() external returns (address treasuryAddress); /// @notice the total supply held for a given token /// @param token the token to get the supply for /// @return amount the total supply for a given token function totalSupply(address token) external returns (uint256 amount); /* /// @notice withdraws tokens from the round contract. only callable when round 2 starts /// @param tokenData an array of token structs /// @param asEth flag to determine if provided WETH, that it should be withdrawn as ETH function withdraw(TokenData calldata tokenData, bool asEth) external; */ // /// @notice adds tokens to support // /// @param tokensToSupport an array of supported token structs function addSupportedTokens(SupportedTokenData[] calldata tokensToSupport) external; // /// @notice returns which tokens can be deposited // /// @return tokens tokens that are supported for deposit function getSupportedTokens() external view returns (address[] calldata tokens); /// @notice the oracle that will be used to denote how much the amounts deposited are worth in USD /// @param tokens an array of tokens /// @return oracleAddresses the an array of oracles corresponding to supported tokens function getTokenOracles(address[] calldata tokens) external view returns (address[] calldata oracleAddresses); /// @notice publishes rates for the tokens. Rates are always relative to 1 INSURE. Can only be called once within Stage 1 // prices can be published at any time /// @param ratesData an array of rate info structs function publishRates( RateData[] calldata ratesData, OversubscriptionRate memory overSubRate, uint256 lastLookDuration ) external; /// @notice return the published rates for the tokens /// @param tokens an array of tokens to get rates for /// @return rates an array of rates for the provided tokens function getRates(address[] calldata tokens) external view returns (RateData[] calldata rates); /// @notice determines the account value in USD amongst all the assets the user is invovled in /// @param account the account to look up /// @return value the value of the account in USD function accountBalance(address account) external view returns (uint256 value); /// @notice Moves excess assets to private farming or refunds them /// @dev uses the publishedRates, selected tokens, and amounts to determine what amount of INSURE is claimed /// when true oversubscribed amount will deposit to genesis, else oversubscribed amount is sent back to user function finalizeAssets() external; //// @notice returns what gensis pool a supported token is mapped to /// @param tokens array of addresses of supported tokens /// @return genesisAddresses array of genesis pools corresponding to supported tokens function getGenesisPools(address[] calldata tokens) external view returns (address[] memory genesisAddresses); /// @notice returns a list of AccountData for a provided account /// @param account the address of the account /// @return data an array of AccountData denoting what the status is for each of the tokens deposited (if any) function getAccountData(address account) external view returns (AccountDataDetails[] calldata data); /// @notice Allows the owner to transfer all swapped assets to the treasury /// @dev only callable by owner and if last look period is complete function transferToTreasury() external; /// @notice Given a balance, calculates how the the amount will be allocated between INSURE and Farming /// @dev Only allowed at stage 3 /// @param balance balance to divy up /// @param token token to pull the rates for function getRateAdjustedAmounts(uint256 balance, address token) external view returns ( uint256, uint256, uint256 ); } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface IWETH is IERC20Upgradeable { function deposit() external payable; function withdraw(uint256) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: 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 IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: UNLICENSED pragma solidity =0.6.11; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "./interfaces/IMerkleDistributor.sol"; contract MerkleDistributor is IMerkleDistributor{ address public immutable override token; bytes32 public immutable override merkleRoot; address public immutable treasury; uint256 public immutable expiry; // >0 if enabled // This is a packed array of booleans. mapping(uint256 => uint256) private claimedBitMap; constructor(address token_, bytes32 merkleRoot_, address treasury_, uint256 expiry_) public { token = token_; merkleRoot = merkleRoot_; treasury = treasury_; expiry = expiry_; } function isClaimed(uint256 index) public view override returns (bool) { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; uint256 claimedWord = claimedBitMap[claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } function _setClaimed(uint256 index) private { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; claimedBitMap[claimedWordIndex] = claimedBitMap[claimedWordIndex] | (1 << claimedBitIndex); } function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external override { require(!isClaimed(index), 'MerkleDistributor: Already claimed.'); require(expiry == 0 || block.timestamp < expiry,'MerkleDistributor: Expired.'); // Verify the merkle proof. bytes32 node = keccak256(abi.encodePacked(index, account, amount)); require(MerkleProof.verify(merkleProof, merkleRoot, node), 'MerkleDistributor: Invalid proof.'); // Mark it claimed and send the token. _setClaimed(index); require(IERC20(token).transfer(account, amount), 'MerkleDistributor: Transfer failed.'); emit Claimed(index, account, amount); } function salvage() external { require(expiry > 0 && block.timestamp >= expiry,'MerkleDistributor: Not expired.'); uint256 _remaining = IERC20(token).balanceOf(address(this)); IERC20(token).transfer(treasury, _remaining); } } // SPDX-License-Identifier: UNLICENSED pragma solidity >=0.5.0; // Allows anyone to claim a token if they exist in a merkle root. interface IMerkleDistributor { // Returns the address of the token distributed by this contract. function token() external view returns (address); // Returns the merkle root of the merkle tree containing account balances available to claim. function merkleRoot() external view returns (bytes32); // Returns true if the index has been marked claimed. function isClaimed(uint256 index) external view returns (bool); // Claim the given amount of the token to the given address. Reverts if the inputs are invalid. function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external; // This event is triggered whenever a call to #claim succeeds. event Claimed(uint256 index, address account, uint256 amount); } pragma solidity 0.6.11; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/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 `ERC20Mintable`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * 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 IERC20 { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; /** * @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 override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public override returns (bool) { _approve(msg.sender, spender, value); 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 `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _allowances[sender][msg.sender].sub(amount) ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve( msg.sender, spender, _allowances[msg.sender][spender].add(addedValue) ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve( msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destoys `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 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @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 value ) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve( account, msg.sender, _allowances[account][msg.sender].sub(amount) ); } } pragma solidity 0.6.11; import "./ERC20.sol"; contract TestERC20Mock is ERC20 { function mint(address _to, uint256 _amount) public { _mint(_to, _amount); } } pragma solidity 0.6.11; import "./TestERC20Mock.sol"; contract WETHMock is TestERC20Mock { string public name = "WETH"; string public symbol = "WETH"; uint8 public decimals = 18; } pragma solidity 0.6.11; import "./TestERC20Mock.sol"; contract USDCMock is TestERC20Mock { string public name = "USDC"; string public symbol = "USDC"; uint8 public decimals = 6; } pragma solidity 0.6.11; /*** *@title InsureToken *@author InsureDAO * SPDX-License-Identifier: MIT *@notice InsureDAO's governance token */ //libraries import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract InsureToken is IERC20 { event UpdateMiningParameters( uint256 time, uint256 rate, uint256 supply, int256 miningepoch ); event SetMinter(address minter); event SetAdmin(address admin); string public name; string public symbol; uint256 public constant decimals = 18; mapping(address => uint256) public override balanceOf; mapping(address => mapping(address => uint256)) allowances; uint256 public total_supply; address public minter; address public admin; //General constants uint256 constant YEAR = 86400 * 365; // Allocation within 5years: // ========== // * Team & Development: 24% // * Liquidity Mining: 40% // * Investors: 10% // * Foundation Treasury: 14% // * Community Treasury: 10% // ========== // // After 5years: // ========== // * Liquidity Mining: 40%~ (Mint fixed amount every year) // // Mint 2_800_000 INSURE every year. // 6th year: 1.32% inflation rate // 7th year: 1.30% inflation rate // 8th year: 1.28% infration rate // so on // ========== // Supply parameters uint256 constant INITIAL_SUPPLY = 126_000_000; //will be vested uint256 constant RATE_REDUCTION_TIME = YEAR; uint256[6] public RATES = [ (28_000_000 * 10**18) / YEAR, //INITIAL_RATE (22_400_000 * 10**18) / YEAR, (16_800_000 * 10**18) / YEAR, (11_200_000 * 10**18) / YEAR, (5_600_000 * 10**18) / YEAR, (2_800_000 * 10**18) / YEAR ]; uint256 constant RATE_DENOMINATOR = 10**18; uint256 constant INFLATION_DELAY = 86400; // Supply variables int256 public mining_epoch; uint256 public start_epoch_time; uint256 public rate; uint256 public start_epoch_supply; uint256 public emergency_minted; constructor(string memory _name, string memory _symbol) public { /*** * @notice Contract constructor * @param _name Token full name * @param _symbol Token symbol * @param _decimal will be 18 in the migration script. */ uint256 _init_supply = INITIAL_SUPPLY * RATE_DENOMINATOR; name = _name; symbol = _symbol; balanceOf[msg.sender] = _init_supply; total_supply = _init_supply; admin = msg.sender; emit Transfer(address(0), msg.sender, _init_supply); start_epoch_time = block.timestamp + INFLATION_DELAY - RATE_REDUCTION_TIME; mining_epoch = -1; rate = 0; start_epoch_supply = _init_supply; } function _update_mining_parameters() internal { /*** *@dev Update mining rate and supply at the start of the epoch * Any modifying mining call must also call this */ uint256 _rate = rate; uint256 _start_epoch_supply = start_epoch_supply; start_epoch_time += RATE_REDUCTION_TIME; mining_epoch += 1; if (mining_epoch == 0) { _rate = RATES[uint256(mining_epoch)]; } else if (mining_epoch < int256(6)) { _start_epoch_supply += RATES[uint256(mining_epoch) - 1] * YEAR; start_epoch_supply = _start_epoch_supply; _rate = RATES[uint256(mining_epoch)]; } else { _start_epoch_supply += RATES[5] * YEAR; start_epoch_supply = _start_epoch_supply; _rate = RATES[5]; } rate = _rate; emit UpdateMiningParameters( block.timestamp, _rate, _start_epoch_supply, mining_epoch ); } function update_mining_parameters() external { /*** * @notice Update mining rate and supply at the start of the epoch * @dev Callable by any address, but only once per epoch * Total supply becomes slightly larger if this function is called late */ require( block.timestamp >= start_epoch_time + RATE_REDUCTION_TIME, "dev: too soon!" ); _update_mining_parameters(); } function start_epoch_time_write() external returns (uint256) { /*** *@notice Get timestamp of the current mining epoch start * while simultaneously updating mining parameters *@return Timestamp of the epoch */ uint256 _start_epoch_time = start_epoch_time; if (block.timestamp >= _start_epoch_time + RATE_REDUCTION_TIME) { _update_mining_parameters(); return start_epoch_time; } else { return _start_epoch_time; } } function future_epoch_time_write() external returns (uint256) { /*** *@notice Get timestamp of the next mining epoch start * while simultaneously updating mining parameters *@return Timestamp of the next epoch */ uint256 _start_epoch_time = start_epoch_time; if (block.timestamp >= _start_epoch_time + RATE_REDUCTION_TIME) { _update_mining_parameters(); return start_epoch_time + RATE_REDUCTION_TIME; } else { return _start_epoch_time + RATE_REDUCTION_TIME; } } function _available_supply() internal view returns (uint256) { return start_epoch_supply + ((block.timestamp - start_epoch_time) * rate) + emergency_minted; } function available_supply() external view returns (uint256) { /*** *@notice Current number of tokens in existence (claimed or unclaimed) */ return _available_supply(); } function mintable_in_timeframe(uint256 start, uint256 end) external view returns (uint256) { /*** *@notice How much supply is mintable from start timestamp till end timestamp *@param start Start of the time interval (timestamp) *@param end End of the time interval (timestamp) *@return Tokens mintable from `start` till `end` */ require(start <= end, "dev: start > end"); uint256 _to_mint = 0; uint256 _current_epoch_time = start_epoch_time; uint256 _current_rate = rate; int256 _current_epoch = mining_epoch; // Special case if end is in future (not yet minted) epoch if (end > _current_epoch_time + RATE_REDUCTION_TIME) { _current_epoch_time += RATE_REDUCTION_TIME; if (_current_epoch < 5) { _current_rate = RATES[uint256(mining_epoch + int256(1))]; } else { _current_rate = RATES[5]; } } require( end <= _current_epoch_time + RATE_REDUCTION_TIME, "dev: too far in future" ); for (uint256 i = 0; i < 999; i++) { // InsureDAO will not work in 1000 years. if (end >= _current_epoch_time) { uint256 current_end = end; if (current_end > _current_epoch_time + RATE_REDUCTION_TIME) { current_end = _current_epoch_time + RATE_REDUCTION_TIME; } uint256 current_start = start; if ( current_start >= _current_epoch_time + RATE_REDUCTION_TIME ) { break; // We should never get here but what if... } else if (current_start < _current_epoch_time) { current_start = _current_epoch_time; } _to_mint += (_current_rate * (current_end - current_start)); if (start >= _current_epoch_time) { break; } } _current_epoch_time -= RATE_REDUCTION_TIME; if (_current_epoch < 5) { _current_rate = RATES[uint256(_current_epoch + int256(1))]; _current_epoch += 1; } else { _current_rate = RATES[5]; _current_epoch += 1; } assert(_current_rate <= RATES[0]); // This should never happen } return _to_mint; } function set_minter(address _minter) external { /*** *@notice Set the minter address *@dev Only callable once, when minter has not yet been set *@param _minter Address of the minter */ require(msg.sender == admin, "dev: admin only"); require( minter == address(0), "dev: can set the minter only once, at creation" ); minter = _minter; emit SetMinter(_minter); } function set_admin(address _admin) external { /*** *@notice Set the new admin. *@dev After all is set up, admin only can change the token name *@param _admin New admin address */ require(msg.sender == admin, "dev: admin only"); admin = _admin; emit SetAdmin(_admin); } function totalSupply() external view override returns (uint256) { /*** *@notice Total number of tokens in existence. */ return total_supply; } function allowance(address _owner, address _spender) external view override returns (uint256) { /*** *@notice 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 uint256 specifying the amount of tokens still available for the spender */ return allowances[_owner][_spender]; } function transfer(address _to, uint256 _value) external override returns (bool) { /*** *@notice Transfer `_value` tokens from `msg.sender` to `_to` *@dev Vyper does not allow underflows, so the subtraction in * this function will revert on an insufficient balance *@param _to The address to transfer to *@param _value The amount to be transferred *@return bool success */ require(_to != address(0), "dev: transfers to 0x0 are not allowed"); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom( address _from, address _to, uint256 _value ) external override returns (bool) { /*** * @notice Transfer `_value` tokens from `_from` to `_to` * @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 * @return bool success */ require(_from != address(0), "ERC20: transfer from the zero address"); require(_to != address(0), "ERC20: transfer to the zero address"); balanceOf[_from] -= _value; balanceOf[_to] += _value; allowances[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } function _approve( address owner, address spender, uint256 amount ) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function approve(address _spender, uint256 _value) external override returns (bool) { /** *@notice Approve `_spender` to transfer `_value` tokens on behalf of `msg.sender` *@param _spender The address which will spend the funds *@param _value The amount of tokens to be spent *@return bool success */ _approve(msg.sender, _spender, _value); return true; } function increaseAllowance(address _spender, uint256 addedValue) external returns (bool) { _approve( msg.sender, _spender, allowances[msg.sender][_spender] + addedValue ); return true; } function decreaseAllowance(address _spender, uint256 subtractedValue) external returns (bool) { uint256 currentAllowance = allowances[msg.sender][_spender]; require( currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero" ); _approve(msg.sender, _spender, currentAllowance - subtractedValue); return true; } function mint(address _to, uint256 _value) external returns (bool) { /*** *@notice Mint `_value` tokens and assign them to `_to` *@dev Emits a Transfer event originating from 0x00 *@param _to The account that will receive the created tokens *@param _value The amount that will be created *@return bool success */ require(msg.sender == minter, "dev: minter only"); require(_to != address(0), "dev: zero address"); _mint(_to, _value); return true; } function _mint(address _to, uint256 _value) internal { if (block.timestamp >= start_epoch_time + RATE_REDUCTION_TIME) { _update_mining_parameters(); } uint256 _total_supply = total_supply + _value; require( _total_supply <= _available_supply(), "dev: exceeds allowable mint amount" ); total_supply = _total_supply; balanceOf[_to] += _value; emit Transfer(address(0), _to, _value); } function burn(uint256 _value) external returns (bool) { /** *@notice Burn `_value` tokens belonging to `msg.sender` *@dev Emits a Transfer event with a destination of 0x00 *@param _value The amount that will be burned *@return bool success */ require( balanceOf[msg.sender] >= _value, "_value > balanceOf[msg.sender]" ); balanceOf[msg.sender] -= _value; total_supply -= _value; emit Transfer(msg.sender, address(0), _value); return true; } function set_name(string memory _name, string memory _symbol) external { /*** *@notice Change the token name and symbol to `_name` and `_symbol` *@dev Only callable by the admin account *@param _name New token name *@param _symbol New token symbol */ require(msg.sender == admin, "Only admin is allowed to change name"); name = _name; symbol = _symbol; } function emergency_mint(uint256 _amount, address _to) external returns (bool) { /*** * @notice Emergency minting only when CDS couldn't afford the insolvency. * @dev * @param _amountOut token amount needed. token is defiend whithin converter. * @param _to CDS address */ require(msg.sender == minter, "dev: minter only"); //mint emergency_minted += _amount; _mint(_to, _amount); return true; } }
General constants Allocation within 5years: ========== * Team & Development: 24% * Liquidity Mining: 40% * Investors: 10% * Foundation Treasury: 14% * Community Treasury: 10% ========== After 5years: ========== * Liquidity Mining: 40%~ (Mint fixed amount every year) Mint 2_800_000 INSURE every year. 6th year: 1.32% inflation rate 7th year: 1.30% inflation rate 8th year: 1.28% infration rate so on ========== Supply parameters Supply variables
contract InsureToken is IERC20 { event UpdateMiningParameters( uint256 time, uint256 rate, uint256 supply, int256 miningepoch ); event SetMinter(address minter); event SetAdmin(address admin); string public name; string public symbol; uint256 public constant decimals = 18; mapping(address => uint256) public override balanceOf; mapping(address => mapping(address => uint256)) allowances; uint256 public total_supply; address public minter; address public admin; uint256 constant YEAR = 86400 * 365; uint256 constant RATE_REDUCTION_TIME = YEAR; uint256[6] public RATES = [ (22_400_000 * 10**18) / YEAR, (16_800_000 * 10**18) / YEAR, (11_200_000 * 10**18) / YEAR, (5_600_000 * 10**18) / YEAR, (2_800_000 * 10**18) / YEAR ]; uint256 constant RATE_DENOMINATOR = 10**18; uint256 constant INFLATION_DELAY = 86400; int256 public mining_epoch; uint256 public start_epoch_time; uint256 public rate; uint256 public start_epoch_supply; uint256 public emergency_minted; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; constructor(string memory _name, string memory _symbol) public { uint256 _init_supply = INITIAL_SUPPLY * RATE_DENOMINATOR; name = _name; symbol = _symbol; balanceOf[msg.sender] = _init_supply; total_supply = _init_supply; admin = msg.sender; emit Transfer(address(0), msg.sender, _init_supply); start_epoch_time = block.timestamp + INFLATION_DELAY - RATE_REDUCTION_TIME; mining_epoch = -1; rate = 0; start_epoch_supply = _init_supply; } function _update_mining_parameters() internal { uint256 _rate = rate; uint256 _start_epoch_supply = start_epoch_supply; start_epoch_time += RATE_REDUCTION_TIME; mining_epoch += 1; if (mining_epoch == 0) { _rate = RATES[uint256(mining_epoch)]; _start_epoch_supply += RATES[uint256(mining_epoch) - 1] * YEAR; start_epoch_supply = _start_epoch_supply; _rate = RATES[uint256(mining_epoch)]; _start_epoch_supply += RATES[5] * YEAR; start_epoch_supply = _start_epoch_supply; _rate = RATES[5]; } rate = _rate; emit UpdateMiningParameters( block.timestamp, _rate, _start_epoch_supply, mining_epoch ); } function _update_mining_parameters() internal { uint256 _rate = rate; uint256 _start_epoch_supply = start_epoch_supply; start_epoch_time += RATE_REDUCTION_TIME; mining_epoch += 1; if (mining_epoch == 0) { _rate = RATES[uint256(mining_epoch)]; _start_epoch_supply += RATES[uint256(mining_epoch) - 1] * YEAR; start_epoch_supply = _start_epoch_supply; _rate = RATES[uint256(mining_epoch)]; _start_epoch_supply += RATES[5] * YEAR; start_epoch_supply = _start_epoch_supply; _rate = RATES[5]; } rate = _rate; emit UpdateMiningParameters( block.timestamp, _rate, _start_epoch_supply, mining_epoch ); } } else if (mining_epoch < int256(6)) { } else { function update_mining_parameters() external { require( block.timestamp >= start_epoch_time + RATE_REDUCTION_TIME, "dev: too soon!" ); _update_mining_parameters(); } function start_epoch_time_write() external returns (uint256) { uint256 _start_epoch_time = start_epoch_time; if (block.timestamp >= _start_epoch_time + RATE_REDUCTION_TIME) { _update_mining_parameters(); return start_epoch_time; return _start_epoch_time; } } function start_epoch_time_write() external returns (uint256) { uint256 _start_epoch_time = start_epoch_time; if (block.timestamp >= _start_epoch_time + RATE_REDUCTION_TIME) { _update_mining_parameters(); return start_epoch_time; return _start_epoch_time; } } } else { function future_epoch_time_write() external returns (uint256) { uint256 _start_epoch_time = start_epoch_time; if (block.timestamp >= _start_epoch_time + RATE_REDUCTION_TIME) { _update_mining_parameters(); return start_epoch_time + RATE_REDUCTION_TIME; return _start_epoch_time + RATE_REDUCTION_TIME; } } function future_epoch_time_write() external returns (uint256) { uint256 _start_epoch_time = start_epoch_time; if (block.timestamp >= _start_epoch_time + RATE_REDUCTION_TIME) { _update_mining_parameters(); return start_epoch_time + RATE_REDUCTION_TIME; return _start_epoch_time + RATE_REDUCTION_TIME; } } } else { function _available_supply() internal view returns (uint256) { return start_epoch_supply + ((block.timestamp - start_epoch_time) * rate) + emergency_minted; } function available_supply() external view returns (uint256) { return _available_supply(); } function mintable_in_timeframe(uint256 start, uint256 end) external view returns (uint256) { require(start <= end, "dev: start > end"); uint256 _to_mint = 0; uint256 _current_epoch_time = start_epoch_time; uint256 _current_rate = rate; int256 _current_epoch = mining_epoch; if (end > _current_epoch_time + RATE_REDUCTION_TIME) { _current_epoch_time += RATE_REDUCTION_TIME; if (_current_epoch < 5) { _current_rate = RATES[uint256(mining_epoch + int256(1))]; _current_rate = RATES[5]; } } require( end <= _current_epoch_time + RATE_REDUCTION_TIME, "dev: too far in future" ); for (uint256 i = 0; i < 999; i++) { if (end >= _current_epoch_time) { uint256 current_end = end; if (current_end > _current_epoch_time + RATE_REDUCTION_TIME) { current_end = _current_epoch_time + RATE_REDUCTION_TIME; } uint256 current_start = start; if ( current_start >= _current_epoch_time + RATE_REDUCTION_TIME ) { current_start = _current_epoch_time; } _to_mint += (_current_rate * (current_end - current_start)); if (start >= _current_epoch_time) { break; } } _current_epoch_time -= RATE_REDUCTION_TIME; if (_current_epoch < 5) { _current_rate = RATES[uint256(_current_epoch + int256(1))]; _current_epoch += 1; _current_rate = RATES[5]; _current_epoch += 1; } } return _to_mint; } function mintable_in_timeframe(uint256 start, uint256 end) external view returns (uint256) { require(start <= end, "dev: start > end"); uint256 _to_mint = 0; uint256 _current_epoch_time = start_epoch_time; uint256 _current_rate = rate; int256 _current_epoch = mining_epoch; if (end > _current_epoch_time + RATE_REDUCTION_TIME) { _current_epoch_time += RATE_REDUCTION_TIME; if (_current_epoch < 5) { _current_rate = RATES[uint256(mining_epoch + int256(1))]; _current_rate = RATES[5]; } } require( end <= _current_epoch_time + RATE_REDUCTION_TIME, "dev: too far in future" ); for (uint256 i = 0; i < 999; i++) { if (end >= _current_epoch_time) { uint256 current_end = end; if (current_end > _current_epoch_time + RATE_REDUCTION_TIME) { current_end = _current_epoch_time + RATE_REDUCTION_TIME; } uint256 current_start = start; if ( current_start >= _current_epoch_time + RATE_REDUCTION_TIME ) { current_start = _current_epoch_time; } _to_mint += (_current_rate * (current_end - current_start)); if (start >= _current_epoch_time) { break; } } _current_epoch_time -= RATE_REDUCTION_TIME; if (_current_epoch < 5) { _current_rate = RATES[uint256(_current_epoch + int256(1))]; _current_epoch += 1; _current_rate = RATES[5]; _current_epoch += 1; } } return _to_mint; } function mintable_in_timeframe(uint256 start, uint256 end) external view returns (uint256) { require(start <= end, "dev: start > end"); uint256 _to_mint = 0; uint256 _current_epoch_time = start_epoch_time; uint256 _current_rate = rate; int256 _current_epoch = mining_epoch; if (end > _current_epoch_time + RATE_REDUCTION_TIME) { _current_epoch_time += RATE_REDUCTION_TIME; if (_current_epoch < 5) { _current_rate = RATES[uint256(mining_epoch + int256(1))]; _current_rate = RATES[5]; } } require( end <= _current_epoch_time + RATE_REDUCTION_TIME, "dev: too far in future" ); for (uint256 i = 0; i < 999; i++) { if (end >= _current_epoch_time) { uint256 current_end = end; if (current_end > _current_epoch_time + RATE_REDUCTION_TIME) { current_end = _current_epoch_time + RATE_REDUCTION_TIME; } uint256 current_start = start; if ( current_start >= _current_epoch_time + RATE_REDUCTION_TIME ) { current_start = _current_epoch_time; } _to_mint += (_current_rate * (current_end - current_start)); if (start >= _current_epoch_time) { break; } } _current_epoch_time -= RATE_REDUCTION_TIME; if (_current_epoch < 5) { _current_rate = RATES[uint256(_current_epoch + int256(1))]; _current_epoch += 1; _current_rate = RATES[5]; _current_epoch += 1; } } return _to_mint; } } else { function mintable_in_timeframe(uint256 start, uint256 end) external view returns (uint256) { require(start <= end, "dev: start > end"); uint256 _to_mint = 0; uint256 _current_epoch_time = start_epoch_time; uint256 _current_rate = rate; int256 _current_epoch = mining_epoch; if (end > _current_epoch_time + RATE_REDUCTION_TIME) { _current_epoch_time += RATE_REDUCTION_TIME; if (_current_epoch < 5) { _current_rate = RATES[uint256(mining_epoch + int256(1))]; _current_rate = RATES[5]; } } require( end <= _current_epoch_time + RATE_REDUCTION_TIME, "dev: too far in future" ); for (uint256 i = 0; i < 999; i++) { if (end >= _current_epoch_time) { uint256 current_end = end; if (current_end > _current_epoch_time + RATE_REDUCTION_TIME) { current_end = _current_epoch_time + RATE_REDUCTION_TIME; } uint256 current_start = start; if ( current_start >= _current_epoch_time + RATE_REDUCTION_TIME ) { current_start = _current_epoch_time; } _to_mint += (_current_rate * (current_end - current_start)); if (start >= _current_epoch_time) { break; } } _current_epoch_time -= RATE_REDUCTION_TIME; if (_current_epoch < 5) { _current_rate = RATES[uint256(_current_epoch + int256(1))]; _current_epoch += 1; _current_rate = RATES[5]; _current_epoch += 1; } } return _to_mint; } function mintable_in_timeframe(uint256 start, uint256 end) external view returns (uint256) { require(start <= end, "dev: start > end"); uint256 _to_mint = 0; uint256 _current_epoch_time = start_epoch_time; uint256 _current_rate = rate; int256 _current_epoch = mining_epoch; if (end > _current_epoch_time + RATE_REDUCTION_TIME) { _current_epoch_time += RATE_REDUCTION_TIME; if (_current_epoch < 5) { _current_rate = RATES[uint256(mining_epoch + int256(1))]; _current_rate = RATES[5]; } } require( end <= _current_epoch_time + RATE_REDUCTION_TIME, "dev: too far in future" ); for (uint256 i = 0; i < 999; i++) { if (end >= _current_epoch_time) { uint256 current_end = end; if (current_end > _current_epoch_time + RATE_REDUCTION_TIME) { current_end = _current_epoch_time + RATE_REDUCTION_TIME; } uint256 current_start = start; if ( current_start >= _current_epoch_time + RATE_REDUCTION_TIME ) { current_start = _current_epoch_time; } _to_mint += (_current_rate * (current_end - current_start)); if (start >= _current_epoch_time) { break; } } _current_epoch_time -= RATE_REDUCTION_TIME; if (_current_epoch < 5) { _current_rate = RATES[uint256(_current_epoch + int256(1))]; _current_epoch += 1; _current_rate = RATES[5]; _current_epoch += 1; } } return _to_mint; } function mintable_in_timeframe(uint256 start, uint256 end) external view returns (uint256) { require(start <= end, "dev: start > end"); uint256 _to_mint = 0; uint256 _current_epoch_time = start_epoch_time; uint256 _current_rate = rate; int256 _current_epoch = mining_epoch; if (end > _current_epoch_time + RATE_REDUCTION_TIME) { _current_epoch_time += RATE_REDUCTION_TIME; if (_current_epoch < 5) { _current_rate = RATES[uint256(mining_epoch + int256(1))]; _current_rate = RATES[5]; } } require( end <= _current_epoch_time + RATE_REDUCTION_TIME, "dev: too far in future" ); for (uint256 i = 0; i < 999; i++) { if (end >= _current_epoch_time) { uint256 current_end = end; if (current_end > _current_epoch_time + RATE_REDUCTION_TIME) { current_end = _current_epoch_time + RATE_REDUCTION_TIME; } uint256 current_start = start; if ( current_start >= _current_epoch_time + RATE_REDUCTION_TIME ) { current_start = _current_epoch_time; } _to_mint += (_current_rate * (current_end - current_start)); if (start >= _current_epoch_time) { break; } } _current_epoch_time -= RATE_REDUCTION_TIME; if (_current_epoch < 5) { _current_rate = RATES[uint256(_current_epoch + int256(1))]; _current_epoch += 1; _current_rate = RATES[5]; _current_epoch += 1; } } return _to_mint; } function mintable_in_timeframe(uint256 start, uint256 end) external view returns (uint256) { require(start <= end, "dev: start > end"); uint256 _to_mint = 0; uint256 _current_epoch_time = start_epoch_time; uint256 _current_rate = rate; int256 _current_epoch = mining_epoch; if (end > _current_epoch_time + RATE_REDUCTION_TIME) { _current_epoch_time += RATE_REDUCTION_TIME; if (_current_epoch < 5) { _current_rate = RATES[uint256(mining_epoch + int256(1))]; _current_rate = RATES[5]; } } require( end <= _current_epoch_time + RATE_REDUCTION_TIME, "dev: too far in future" ); for (uint256 i = 0; i < 999; i++) { if (end >= _current_epoch_time) { uint256 current_end = end; if (current_end > _current_epoch_time + RATE_REDUCTION_TIME) { current_end = _current_epoch_time + RATE_REDUCTION_TIME; } uint256 current_start = start; if ( current_start >= _current_epoch_time + RATE_REDUCTION_TIME ) { current_start = _current_epoch_time; } _to_mint += (_current_rate * (current_end - current_start)); if (start >= _current_epoch_time) { break; } } _current_epoch_time -= RATE_REDUCTION_TIME; if (_current_epoch < 5) { _current_rate = RATES[uint256(_current_epoch + int256(1))]; _current_epoch += 1; _current_rate = RATES[5]; _current_epoch += 1; } } return _to_mint; } } else if (current_start < _current_epoch_time) { function mintable_in_timeframe(uint256 start, uint256 end) external view returns (uint256) { require(start <= end, "dev: start > end"); uint256 _to_mint = 0; uint256 _current_epoch_time = start_epoch_time; uint256 _current_rate = rate; int256 _current_epoch = mining_epoch; if (end > _current_epoch_time + RATE_REDUCTION_TIME) { _current_epoch_time += RATE_REDUCTION_TIME; if (_current_epoch < 5) { _current_rate = RATES[uint256(mining_epoch + int256(1))]; _current_rate = RATES[5]; } } require( end <= _current_epoch_time + RATE_REDUCTION_TIME, "dev: too far in future" ); for (uint256 i = 0; i < 999; i++) { if (end >= _current_epoch_time) { uint256 current_end = end; if (current_end > _current_epoch_time + RATE_REDUCTION_TIME) { current_end = _current_epoch_time + RATE_REDUCTION_TIME; } uint256 current_start = start; if ( current_start >= _current_epoch_time + RATE_REDUCTION_TIME ) { current_start = _current_epoch_time; } _to_mint += (_current_rate * (current_end - current_start)); if (start >= _current_epoch_time) { break; } } _current_epoch_time -= RATE_REDUCTION_TIME; if (_current_epoch < 5) { _current_rate = RATES[uint256(_current_epoch + int256(1))]; _current_epoch += 1; _current_rate = RATES[5]; _current_epoch += 1; } } return _to_mint; } function mintable_in_timeframe(uint256 start, uint256 end) external view returns (uint256) { require(start <= end, "dev: start > end"); uint256 _to_mint = 0; uint256 _current_epoch_time = start_epoch_time; uint256 _current_rate = rate; int256 _current_epoch = mining_epoch; if (end > _current_epoch_time + RATE_REDUCTION_TIME) { _current_epoch_time += RATE_REDUCTION_TIME; if (_current_epoch < 5) { _current_rate = RATES[uint256(mining_epoch + int256(1))]; _current_rate = RATES[5]; } } require( end <= _current_epoch_time + RATE_REDUCTION_TIME, "dev: too far in future" ); for (uint256 i = 0; i < 999; i++) { if (end >= _current_epoch_time) { uint256 current_end = end; if (current_end > _current_epoch_time + RATE_REDUCTION_TIME) { current_end = _current_epoch_time + RATE_REDUCTION_TIME; } uint256 current_start = start; if ( current_start >= _current_epoch_time + RATE_REDUCTION_TIME ) { current_start = _current_epoch_time; } _to_mint += (_current_rate * (current_end - current_start)); if (start >= _current_epoch_time) { break; } } _current_epoch_time -= RATE_REDUCTION_TIME; if (_current_epoch < 5) { _current_rate = RATES[uint256(_current_epoch + int256(1))]; _current_epoch += 1; _current_rate = RATES[5]; _current_epoch += 1; } } return _to_mint; } } else { function set_minter(address _minter) external { require(msg.sender == admin, "dev: admin only"); require( minter == address(0), "dev: can set the minter only once, at creation" ); minter = _minter; emit SetMinter(_minter); } function set_admin(address _admin) external { require(msg.sender == admin, "dev: admin only"); admin = _admin; emit SetAdmin(_admin); } function totalSupply() external view override returns (uint256) { return total_supply; } function allowance(address _owner, address _spender) external view override returns (uint256) { return allowances[_owner][_spender]; } function transfer(address _to, uint256 _value) external override returns (bool) { require(_to != address(0), "dev: transfers to 0x0 are not allowed"); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom( address _from, address _to, uint256 _value ) external override returns (bool) { require(_from != address(0), "ERC20: transfer from the zero address"); require(_to != address(0), "ERC20: transfer to the zero address"); balanceOf[_from] -= _value; balanceOf[_to] += _value; allowances[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; } function _approve( address owner, address spender, uint256 amount ) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function approve(address _spender, uint256 _value) external override returns (bool) { _approve(msg.sender, _spender, _value); return true; } function increaseAllowance(address _spender, uint256 addedValue) external returns (bool) { _approve( msg.sender, _spender, allowances[msg.sender][_spender] + addedValue ); return true; } function decreaseAllowance(address _spender, uint256 subtractedValue) external returns (bool) { uint256 currentAllowance = allowances[msg.sender][_spender]; require( currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero" ); _approve(msg.sender, _spender, currentAllowance - subtractedValue); return true; } function mint(address _to, uint256 _value) external returns (bool) { require(msg.sender == minter, "dev: minter only"); require(_to != address(0), "dev: zero address"); _mint(_to, _value); return true; } function _mint(address _to, uint256 _value) internal { if (block.timestamp >= start_epoch_time + RATE_REDUCTION_TIME) { _update_mining_parameters(); } uint256 _total_supply = total_supply + _value; require( _total_supply <= _available_supply(), "dev: exceeds allowable mint amount" ); total_supply = _total_supply; balanceOf[_to] += _value; emit Transfer(address(0), _to, _value); } function _mint(address _to, uint256 _value) internal { if (block.timestamp >= start_epoch_time + RATE_REDUCTION_TIME) { _update_mining_parameters(); } uint256 _total_supply = total_supply + _value; require( _total_supply <= _available_supply(), "dev: exceeds allowable mint amount" ); total_supply = _total_supply; balanceOf[_to] += _value; emit Transfer(address(0), _to, _value); } function burn(uint256 _value) external returns (bool) { require( balanceOf[msg.sender] >= _value, "_value > balanceOf[msg.sender]" ); balanceOf[msg.sender] -= _value; total_supply -= _value; emit Transfer(msg.sender, address(0), _value); return true; } function set_name(string memory _name, string memory _symbol) external { require(msg.sender == admin, "Only admin is allowed to change name"); name = _name; symbol = _symbol; } function emergency_mint(uint256 _amount, address _to) external returns (bool) { require(msg.sender == minter, "dev: minter only"); emergency_minted += _amount; _mint(_to, _amount); return true; } }
13,108,756
[ 1, 12580, 6810, 24242, 3470, 1381, 29391, 30, 422, 1432, 225, 10434, 473, 1505, 11284, 30, 4248, 9, 225, 511, 18988, 24237, 5444, 310, 30, 8063, 9, 225, 5454, 395, 1383, 30, 1728, 9, 225, 31289, 399, 266, 345, 22498, 30, 5045, 9, 225, 16854, 13352, 399, 266, 345, 22498, 30, 1728, 9, 422, 1432, 7360, 1381, 29391, 30, 422, 1432, 225, 511, 18988, 24237, 5444, 310, 30, 8063, 9, 98, 261, 49, 474, 5499, 3844, 3614, 3286, 13, 490, 474, 576, 67, 17374, 67, 3784, 2120, 55, 4830, 3614, 3286, 18, 1666, 451, 3286, 30, 404, 18, 1578, 9, 13947, 367, 4993, 2371, 451, 3286, 30, 404, 18, 5082, 9, 13947, 367, 4993, 1725, 451, 3286, 30, 404, 18, 6030, 9, 316, 4840, 367, 4993, 1427, 603, 422, 1432, 3425, 1283, 1472, 3425, 1283, 3152, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 657, 2055, 1345, 353, 467, 654, 39, 3462, 288, 203, 565, 871, 2315, 2930, 310, 2402, 12, 203, 3639, 2254, 5034, 813, 16, 203, 3639, 2254, 5034, 4993, 16, 203, 3639, 2254, 5034, 14467, 16, 203, 3639, 509, 5034, 1131, 310, 12015, 203, 565, 11272, 203, 565, 871, 1000, 49, 2761, 12, 2867, 1131, 387, 1769, 203, 565, 871, 1000, 4446, 12, 2867, 3981, 1769, 203, 203, 565, 533, 1071, 508, 31, 203, 565, 533, 1071, 3273, 31, 203, 565, 2254, 5034, 1071, 5381, 15105, 273, 6549, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 3849, 11013, 951, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 1699, 6872, 31, 203, 565, 2254, 5034, 1071, 2078, 67, 2859, 1283, 31, 203, 203, 565, 1758, 1071, 1131, 387, 31, 203, 565, 1758, 1071, 3981, 31, 203, 203, 565, 2254, 5034, 5381, 16145, 273, 21451, 380, 21382, 31, 203, 203, 203, 565, 2254, 5034, 5381, 534, 1777, 67, 5879, 27035, 67, 4684, 273, 16145, 31, 203, 565, 2254, 5034, 63, 26, 65, 1071, 534, 1777, 55, 273, 306, 203, 3639, 261, 3787, 67, 16010, 67, 3784, 380, 1728, 636, 2643, 13, 342, 16145, 16, 203, 3639, 261, 2313, 67, 17374, 67, 3784, 380, 1728, 636, 2643, 13, 342, 16145, 16, 203, 3639, 261, 2499, 67, 6976, 67, 3784, 380, 1728, 636, 2643, 13, 342, 16145, 16, 203, 3639, 261, 25, 67, 28133, 67, 3784, 380, 1728, 636, 2643, 13, 342, 16145, 16, 203, 3639, 261, 22, 2 ]
./full_match/1/0x9FF1AcABb7E9D4Daf9F1458B9138066fa0cCcd3F/sources/contracts/HaloWalletGenesisPass.sol
0. Whether the specified activity is configured 1. Check if or not in active period 2. Verify that the current user has not claimed 3. Check current minted amount <= MAX_SUPPLY 4. Check minting is still possible during the current active period 5. Merkle verification All checks passed --- mint nft
function claimPass( bytes32[] calldata proof, ) external callerIsUser nonReentrant whenNotPaused { require( proof.length > 0 && mintParameters[mintType].merkleRoot != 0x0, "Not correct parameter" ); require( block.timestamp >= mintParameters[mintType].startTimestamp && block.timestamp <= mintParameters[mintType].endTimestamp, "Not in claim period" ); require(!claimed[msg.sender], "Caller already claimed"); require(currentIndex < MAX_SUPPLY, "Exceeded max supply"); require( currentIndex < mintParameters[mintType].maxTokenId, "Exceeded max amount of this period" ); require( MerkleProof.verify( proof, mintParameters[mintType].merkleRoot, keccak256(abi.encodePacked(msg.sender)) ), "Not in the allowlist" ); claimed[msg.sender] = true; _safeMint(msg.sender, ++currentIndex); }
9,671,467
[ 1, 20, 18, 17403, 326, 1269, 5728, 353, 4351, 404, 18, 2073, 309, 578, 486, 316, 2695, 3879, 576, 18, 8553, 716, 326, 783, 729, 711, 486, 7516, 329, 890, 18, 2073, 783, 312, 474, 329, 3844, 1648, 4552, 67, 13272, 23893, 1059, 18, 2073, 312, 474, 310, 353, 4859, 3323, 4982, 326, 783, 2695, 3879, 1381, 18, 31827, 11805, 4826, 4271, 2275, 9948, 312, 474, 290, 1222, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6433, 12, 203, 3639, 1731, 1578, 8526, 745, 892, 14601, 16, 203, 565, 262, 3903, 4894, 2520, 1299, 1661, 426, 8230, 970, 1347, 1248, 28590, 288, 203, 3639, 2583, 12, 203, 5411, 14601, 18, 2469, 405, 374, 597, 312, 474, 2402, 63, 81, 474, 559, 8009, 6592, 15609, 2375, 480, 374, 92, 20, 16, 203, 5411, 315, 1248, 3434, 1569, 6, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 203, 5411, 1203, 18, 5508, 1545, 312, 474, 2402, 63, 81, 474, 559, 8009, 1937, 4921, 597, 203, 7734, 1203, 18, 5508, 1648, 312, 474, 2402, 63, 81, 474, 559, 8009, 409, 4921, 16, 203, 5411, 315, 1248, 316, 7516, 3879, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 5, 14784, 329, 63, 3576, 18, 15330, 6487, 315, 11095, 1818, 7516, 329, 8863, 203, 203, 3639, 2583, 12, 2972, 1016, 411, 4552, 67, 13272, 23893, 16, 315, 10069, 943, 14467, 8863, 203, 203, 3639, 2583, 12, 203, 5411, 17032, 411, 312, 474, 2402, 63, 81, 474, 559, 8009, 1896, 1345, 548, 16, 203, 5411, 315, 10069, 943, 3844, 434, 333, 3879, 6, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 203, 5411, 31827, 20439, 18, 8705, 12, 203, 7734, 14601, 16, 203, 7734, 312, 474, 2402, 63, 81, 474, 559, 8009, 6592, 15609, 2375, 16, 203, 7734, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 3576, 18, 15330, 3719, 203, 5411, 262, 16, 203, 5411, 315, 1248, 316, 326, 1699, 1098, 6, 203, 3639, 11272, 203, 203, 3639, 7516, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-10-01 */ // SPDX-License-Identifier: No License (None) pragma solidity ^0.8.0; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". * * Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/ownership/Ownable.sol * This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts * when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the * build/artifacts folder) as well as the vanilla Ownable implementation from an openzeppelin version. */ abstract contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(),"Not Owner"); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0),"Zero address not allowed"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface IGatewayVault { function vaultTransfer(address token, address recipient, uint256 amount) external returns (bool); function vaultApprove(address token, address spender, uint256 amount) external returns (bool); } interface IDegen { enum OrderType {EthForTokens, TokensForEth, TokensForTokens} function callbackCrossExchange(OrderType orderType, address[] memory path, uint256 assetInOffered, address user, uint256 dexId, uint256[] memory distribution, uint256 deadline) external returns(bool); } interface IBEP20 { function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function transfer(address recipient, uint256 amount) external returns (bool); function mint(address to, uint256 amount) external returns (bool); function burnFrom(address account, uint256 amount) external returns(bool); } contract DegenBridge is Ownable { address public USDT = address(0); uint256 _nonce = 0; mapping(uint256 => bool) public nonceProcessed; mapping(uint256 => IDegen.OrderType) private _orderType; address public system; // system address may change fee amount bool public paused; address public gatewayVault; // GatewayVault contract address public degenContract; event SwapRequest( address indexed tokenA, address indexed tokenB, address indexed user, uint256 amount, uint256 crossOrderType, uint256 nonce, uint256 dexId, uint256[] distribution, uint256 deadline ); // event ClaimRequest(address indexed tokenA, address indexed tokenB, address indexed user, uint256 amount); event ClaimApprove( address indexed tokenA, address indexed tokenB, address indexed user, uint256 amount, uint256 crossOrderType, uint256 dexId, uint256[] distribution, uint256 deadline ); modifier notPaused() { require(!paused,"Swap paused"); _; } /** * @dev Throws if called by any account other than the system. */ modifier onlySystem() { require(msg.sender == system || owner() == msg.sender,"Caller is not the system"); _; } constructor (address _system, address _gatewayVault, address _usdt) { system = _system; gatewayVault = _gatewayVault; USDT = _usdt; _orderType[0] = IDegen.OrderType.TokensForTokens; _orderType[1] = IDegen.OrderType.TokensForEth; _orderType[2] = IDegen.OrderType.TokensForTokens; _orderType[3] = IDegen.OrderType.TokensForEth; } function setDegenContract(address _degenContract) external onlyOwner returns(bool) { degenContract = _degenContract; return true; } function setSystem(address _system) external onlyOwner returns(bool) { system = _system; return true; } function setUSDT(address _usdt) external onlyOwner returns(bool) { USDT = _usdt; return true; } function setPause(bool pause) external onlyOwner returns(bool) { paused = pause; return true; } function getTransactionStatus(uint256 nonce) external view returns (bool){ return nonceProcessed[nonce]; } //user should approve tokens transfer before calling this function. // for local swap (tokens on the same chain): pair = address(1) when TokenA = JNTR, and address(2) when TokenB = JNTR function swap(address tokenA, address tokenB, uint256 amount, address user, uint256 crossOrderType, uint256 dexId, uint256[] memory distribution, uint256 deadline) external payable notPaused returns (bool) { require(msg.sender == degenContract, "Only Degen"); require(amount != 0, "Zero amount"); require(gatewayVault != address(0), "No vault address"); require(deadline >= block.timestamp, "EXPIRED: Deadline for bridge transaction already passed."); IBEP20(tokenA).transferFrom(msg.sender, gatewayVault, amount); _nonce = _nonce+1; emit SwapRequest(tokenA, tokenB, user, amount, crossOrderType, _nonce, dexId, distribution, deadline); return true; } function claimTokenBehalf(address[] memory path, address user, uint256 amount, uint256 crossOrderType, uint256 nonce, uint256 dexId, uint256[] memory distribution, uint256 deadline) external onlySystem notPaused returns (bool) { require(!nonceProcessed[nonce], "Exchange already processed"); _claim(path, user, amount, crossOrderType, dexId, distribution, deadline); nonceProcessed[nonce] = true; return true; } function _claim (address[] memory path, address user, uint256 amount, uint256 crossOrderType, uint256 dexId, uint256[] memory distribution, uint256 deadline) internal returns(bool) { require(deadline >= block.timestamp, "EXPIRED: Deadline for claim transaction already passed."); if(path[path.length-1] == USDT) { IGatewayVault(gatewayVault).vaultTransfer(USDT, user, amount); } else { IGatewayVault(gatewayVault).vaultTransfer(USDT, degenContract, amount); IDegen(degenContract).callbackCrossExchange(_orderType[crossOrderType], path, amount, user, dexId, distribution, deadline); } emit ClaimApprove(path[0], path[path.length-1], user, amount, crossOrderType, dexId, distribution, deadline); // emit ClaimRequest(tokenA, tokenB, user,amount); return true; } }
* @title Ownable @dev The Ownable contract has an owner address, and provides basic authorization control functions, this simplifies the implementation of "user permissions". This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the build/artifacts folder) as well as the vanilla Ownable implementation from an openzeppelin version./
abstract contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); pragma solidity ^0.8.0; constructor () { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner(),"Not Owner"); _; } function isOwner() public view returns (bool) { return msg.sender == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { require(newOwner != address(0),"Zero address not allowed"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
1,979,201
[ 1, 5460, 429, 225, 1021, 14223, 6914, 6835, 711, 392, 3410, 1758, 16, 471, 8121, 5337, 6093, 3325, 4186, 16, 333, 9330, 5032, 326, 4471, 434, 315, 1355, 4371, 9654, 1220, 6835, 353, 9268, 2674, 471, 17657, 628, 326, 2282, 358, 4543, 927, 7690, 316, 326, 7743, 16259, 1347, 326, 729, 10095, 279, 998, 538, 17, 2941, 6835, 261, 19056, 22755, 4492, 14119, 333, 6835, 358, 506, 7743, 471, 3096, 358, 326, 1361, 19, 30347, 3009, 13, 487, 5492, 487, 326, 331, 26476, 14223, 6914, 4471, 628, 392, 1696, 94, 881, 84, 292, 267, 1177, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 17801, 6835, 14223, 6914, 288, 203, 565, 1758, 3238, 389, 8443, 31, 203, 203, 565, 871, 14223, 9646, 5310, 1429, 4193, 12, 2867, 8808, 2416, 5541, 16, 1758, 8808, 394, 5541, 1769, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 565, 3885, 1832, 288, 203, 3639, 389, 8443, 273, 1234, 18, 15330, 31, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 12, 2867, 12, 20, 3631, 389, 8443, 1769, 203, 565, 289, 203, 203, 565, 445, 3410, 1435, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 389, 8443, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 291, 5541, 9334, 6, 1248, 16837, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 353, 5541, 1435, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 1234, 18, 15330, 422, 389, 8443, 31, 203, 565, 289, 203, 203, 565, 445, 1654, 8386, 5460, 12565, 1435, 1071, 1338, 5541, 288, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 24899, 8443, 16, 1758, 12, 20, 10019, 203, 3639, 389, 8443, 273, 1758, 12, 20, 1769, 203, 565, 289, 203, 203, 565, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 1071, 1338, 5541, 288, 203, 3639, 389, 13866, 5460, 12565, 12, 2704, 5541, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 13866, 5460, 12565, 12, 2867, 394, 5541, 13, 2713, 288, 203, 3639, 2583, 12, 2704, 5541, 480, 1758, 12, 20, 3631, 6, 7170, 1758, 486, 2935, 2 ]
pragma solidity >=0.5.7; // Copyright BigchainDB GmbH and Ocean Protocol contributors // SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) // Code is Apache-2.0 and docs are CC-BY-4.0 import "../../interfaces/IERC20Template.sol"; import "../../interfaces/IFactoryRouter.sol"; import "OpenZeppelin/[email protected]/contracts/utils/math/SafeMath.sol"; /** * @title FixedRateExchange * @dev FixedRateExchange is a fixed rate exchange Contract * Marketplaces uses this contract to allow consumers * exchanging datatokens with ocean token using a fixed * exchange rate. */ contract FixedRateExchange { using SafeMath for uint256; uint256 private constant BASE = 10**18; address public router; address public opfCollector; struct Exchange { bool active; address exchangeOwner; address dataToken; address baseToken; uint256 fixedRate; uint256 dtDecimals; uint256 btDecimals; uint256 dtBalance; uint256 btBalance; uint256 marketFee; address marketFeeCollector; uint256 marketFeeAvailable; uint256 oceanFeeAvailable; bool withMint; address allowedSwapper; } // maps an exchangeId to an exchange mapping(bytes32 => Exchange) private exchanges; bytes32[] private exchangeIds; modifier onlyActiveExchange(bytes32 exchangeId) { require( //exchanges[exchangeId].fixedRate != 0 && exchanges[exchangeId].active == true, "FixedRateExchange: Exchange does not exist!" ); _; } modifier onlyExchangeOwner(bytes32 exchangeId) { require( exchanges[exchangeId].exchangeOwner == msg.sender, "FixedRateExchange: invalid exchange owner" ); _; } modifier onlyRouter() { require(msg.sender == router, "FixedRateExchange: only router"); _; } event ExchangeCreated( bytes32 indexed exchangeId, address indexed baseToken, address indexed dataToken, address exchangeOwner, uint256 fixedRate ); event ExchangeRateChanged( bytes32 indexed exchangeId, address indexed exchangeOwner, uint256 newRate ); //triggered when the withMint state is changed event ExchangeMintStateChanged( bytes32 indexed exchangeId, address indexed exchangeOwner, bool withMint ); event ExchangeActivated( bytes32 indexed exchangeId, address indexed exchangeOwner ); event ExchangeDeactivated( bytes32 indexed exchangeId, address indexed exchangeOwner ); event ExchangeAllowedSwapperChanged( bytes32 indexed exchangeId, address indexed allowedSwapper ); event Swapped( bytes32 indexed exchangeId, address indexed by, uint256 baseTokenSwappedAmount, uint256 dataTokenSwappedAmount, address tokenOutAddress, uint256 marketFeeAmount, uint256 oceanFeeAmount ); event TokenCollected( bytes32 indexed exchangeId, address indexed to, address indexed token, uint256 amount ); event OceanFeeCollected( bytes32 indexed exchangeId, address indexed feeToken, uint256 feeAmount ); event MarketFeeCollected( bytes32 indexed exchangeId, address indexed feeToken, uint256 feeAmount ); constructor(address _router, address _opfCollector) { require(_router != address(0), "FixedRateExchange: Wrong Router address"); require(_opfCollector != address(0), "FixedRateExchange: Wrong OPF address"); router = _router; opfCollector = _opfCollector; } function getOPFFee(address basetokenAddress) public view returns (uint) { return IFactoryRouter(router).getOPFFee(basetokenAddress); } /** * @dev create * creates new exchange pairs between base token * (ocean token) and data tokens. * dataToken refers to a data token contract address * addresses - array of addresses with the following struct: * [0] - baseToken * [1] - owner * [2] - marketFeeCollector * [3] - allowedSwapper - if != address(0), only that is allowed to swap (used for ERC20Enterprise) * uints - array of uints with the following struct: * [0] - baseTokenDecimals * [1] - dataTokenDecimals * [2] - fixedRate * [3] - marketFee * [4] - withMint */ function createWithDecimals( address dataToken, address[] memory addresses, uint256[] memory uints ) public onlyRouter returns (bytes32 exchangeId) { require( addresses[0] != address(0), "FixedRateExchange: Invalid basetoken, zero address" ); require( dataToken != address(0), "FixedRateExchange: Invalid datatoken, zero address" ); require( addresses[0] != dataToken, "FixedRateExchange: Invalid datatoken, equals basetoken" ); require( uints[2] != 0, "FixedRateExchange: Invalid exchange rate value" ); exchangeId = generateExchangeId(addresses[0], dataToken, addresses[1]); require( exchanges[exchangeId].fixedRate == 0, "FixedRateExchange: Exchange already exists!" ); bool withMint=true; if(uints[4] == 0) withMint = false; exchanges[exchangeId] = Exchange({ active: true, exchangeOwner: addresses[1], dataToken: dataToken, baseToken: addresses[0], fixedRate: uints[2], dtDecimals: uints[1], btDecimals: uints[0], dtBalance: 0, btBalance: 0, marketFee: uints[3], marketFeeCollector: addresses[2], marketFeeAvailable: 0, oceanFeeAvailable: 0, withMint: withMint, allowedSwapper: addresses[3] }); exchangeIds.push(exchangeId); emit ExchangeCreated( exchangeId, addresses[0], // dataToken, addresses[1], uints[2] ); emit ExchangeActivated(exchangeId, addresses[1]); emit ExchangeAllowedSwapperChanged(exchangeId, addresses[3]); } /** * @dev generateExchangeId * creates unique exchange identifier for two token pairs. * @param baseToken refers to a ocean token contract address * @param dataToken refers to a data token contract address * @param exchangeOwner exchange owner address */ function generateExchangeId( address baseToken, address dataToken, address exchangeOwner ) public pure returns (bytes32) { return keccak256(abi.encode(baseToken, dataToken, exchangeOwner)); } /** * @dev CalcInGivenOut * Calculates how many basetokens are needed to get specifyed amount of datatokens * @param exchangeId a unique exchange idnetifier * @param dataTokenAmount the amount of data tokens to be exchanged */ function calcBaseInGivenOutDT(bytes32 exchangeId, uint256 dataTokenAmount) public view onlyActiveExchange(exchangeId) returns ( uint256 baseTokenAmount, uint256 baseTokenAmountBeforeFee, uint256 oceanFeeAmount, uint256 marketFeeAmount ) { baseTokenAmountBeforeFee = dataTokenAmount .mul(exchanges[exchangeId].fixedRate) .div(BASE) .mul(10**exchanges[exchangeId].btDecimals) .div(10**exchanges[exchangeId].dtDecimals); oceanFeeAmount; if (getOPFFee(exchanges[exchangeId].baseToken) != 0) { oceanFeeAmount = baseTokenAmountBeforeFee .mul(getOPFFee(exchanges[exchangeId].baseToken)) .div(BASE); } marketFeeAmount = baseTokenAmountBeforeFee .mul(exchanges[exchangeId].marketFee) .div(BASE); baseTokenAmount = baseTokenAmountBeforeFee.add(marketFeeAmount).add( oceanFeeAmount ); } /** * @dev CalcInGivenOut * Calculates how many basetokens are needed to get specifyed amount of datatokens * @param exchangeId a unique exchange idnetifier * @param dataTokenAmount the amount of data tokens to be exchanged */ function calcBaseOutGivenInDT(bytes32 exchangeId, uint256 dataTokenAmount) public view onlyActiveExchange(exchangeId) returns ( uint256 baseTokenAmount, uint256 baseTokenAmountBeforeFee, uint256 oceanFeeAmount, uint256 marketFeeAmount ) { baseTokenAmountBeforeFee = dataTokenAmount .mul(exchanges[exchangeId].fixedRate) .div(BASE) .mul(10**exchanges[exchangeId].btDecimals) .div(10**exchanges[exchangeId].dtDecimals); oceanFeeAmount; if (getOPFFee(exchanges[exchangeId].baseToken) != 0) { oceanFeeAmount = baseTokenAmountBeforeFee .mul(getOPFFee(exchanges[exchangeId].baseToken)) .div(BASE); } marketFeeAmount = baseTokenAmountBeforeFee .mul(exchanges[exchangeId].marketFee) .div(BASE); baseTokenAmount = baseTokenAmountBeforeFee.sub(marketFeeAmount).sub( oceanFeeAmount ); } /** * @dev swap * atomic swap between two registered fixed rate exchange. * @param exchangeId a unique exchange idnetifier * @param dataTokenAmount the amount of data tokens to be exchanged * @param maxBaseTokenAmount maximum amount of base tokens to pay */ function buyDT(bytes32 exchangeId, uint256 dataTokenAmount, uint256 maxBaseTokenAmount) external onlyActiveExchange(exchangeId) { require( dataTokenAmount != 0, "FixedRateExchange: zero data token amount" ); if(exchanges[exchangeId].allowedSwapper != address(0)){ require( exchanges[exchangeId].allowedSwapper == msg.sender, "FixedRateExchange: This address is not allowed to swap" ); } ( uint256 baseTokenAmount, uint256 baseTokenAmountBeforeFee, uint256 oceanFeeAmount, uint256 marketFeeAmount ) = calcBaseInGivenOutDT(exchangeId, dataTokenAmount); require( baseTokenAmount <= maxBaseTokenAmount, "FixedRateExchange: Too many base tokens" ); // we account fees , fees are always collected in basetoken exchanges[exchangeId].oceanFeeAvailable = exchanges[exchangeId] .oceanFeeAvailable .add(oceanFeeAmount); exchanges[exchangeId].marketFeeAvailable = exchanges[exchangeId] .marketFeeAvailable .add(marketFeeAmount); require( IERC20Template(exchanges[exchangeId].baseToken).transferFrom( msg.sender, address(this), // we send basetoken to this address, then exchange owner can withdraw baseTokenAmount ), "FixedRateExchange: transferFrom failed in the baseToken contract" ); exchanges[exchangeId].btBalance = (exchanges[exchangeId].btBalance).add( baseTokenAmountBeforeFee ); if (dataTokenAmount > exchanges[exchangeId].dtBalance) { //first, let's try to mint if(exchanges[exchangeId].withMint && IERC20Template(exchanges[exchangeId].dataToken).isMinter(address(this))) { IERC20Template(exchanges[exchangeId].dataToken).mint(msg.sender,dataTokenAmount); } else{ require( IERC20Template(exchanges[exchangeId].dataToken).transferFrom( exchanges[exchangeId].exchangeOwner, msg.sender, dataTokenAmount ), "FixedRateExchange: transferFrom failed in the dataToken contract" ); } } else { exchanges[exchangeId].dtBalance = (exchanges[exchangeId].dtBalance) .sub(dataTokenAmount); IERC20Template(exchanges[exchangeId].dataToken).transfer( msg.sender, dataTokenAmount ); } emit Swapped( exchangeId, msg.sender, baseTokenAmount, dataTokenAmount, exchanges[exchangeId].dataToken, marketFeeAmount, oceanFeeAmount ); } /** * @dev swap * atomic swap between two registered fixed rate exchange. * @param exchangeId a unique exchange idnetifier * @param dataTokenAmount the amount of data tokens to be exchanged * @param minBaseTokenAmount minimum amount of base tokens to cash in */ function sellDT(bytes32 exchangeId, uint256 dataTokenAmount, uint256 minBaseTokenAmount) external onlyActiveExchange(exchangeId) { require( dataTokenAmount != 0, "FixedRateExchange: zero data token amount" ); if(exchanges[exchangeId].allowedSwapper != address(0)){ require( exchanges[exchangeId].allowedSwapper == msg.sender, "FixedRateExchange: This address is not allowed to swap" ); } ( uint256 baseTokenAmount, uint256 baseTokenAmountBeforeFee, uint256 oceanFeeAmount, uint256 marketFeeAmount ) = calcBaseOutGivenInDT(exchangeId, dataTokenAmount); require( baseTokenAmount >= minBaseTokenAmount, "FixedRateExchange: Too few base tokens" ); // we account fees , fees are always collected in basetoken exchanges[exchangeId].oceanFeeAvailable = exchanges[exchangeId] .oceanFeeAvailable .add(oceanFeeAmount); exchanges[exchangeId].marketFeeAvailable = exchanges[exchangeId] .marketFeeAvailable .add(marketFeeAmount); require( IERC20Template(exchanges[exchangeId].dataToken).transferFrom( msg.sender, address(this), dataTokenAmount ), "FixedRateExchange: transferFrom failed in the dataToken contract" ); exchanges[exchangeId].dtBalance = (exchanges[exchangeId].dtBalance).add( dataTokenAmount ); if (baseTokenAmount > exchanges[exchangeId].btBalance) { require( IERC20Template(exchanges[exchangeId].baseToken).transferFrom( exchanges[exchangeId].exchangeOwner, msg.sender, baseTokenAmount ), "FixedRateExchange: transferFrom failed in the baseToken contract" ); } else { exchanges[exchangeId].btBalance = (exchanges[exchangeId].btBalance) .sub(baseTokenAmountBeforeFee); IERC20Template(exchanges[exchangeId].baseToken).transfer( msg.sender, baseTokenAmount ); } emit Swapped( exchangeId, msg.sender, baseTokenAmount, dataTokenAmount, exchanges[exchangeId].baseToken, marketFeeAmount, oceanFeeAmount ); } function collectBT(bytes32 exchangeId) external onlyExchangeOwner(exchangeId) { uint256 amount = exchanges[exchangeId].btBalance; exchanges[exchangeId].btBalance = 0; IERC20Template(exchanges[exchangeId].baseToken).transfer( exchanges[exchangeId].exchangeOwner, amount ); emit TokenCollected( exchangeId, exchanges[exchangeId].exchangeOwner, exchanges[exchangeId].baseToken, amount ); } function collectDT(bytes32 exchangeId) external onlyExchangeOwner(exchangeId) { uint256 amount = exchanges[exchangeId].dtBalance; exchanges[exchangeId].dtBalance = 0; IERC20Template(exchanges[exchangeId].dataToken).transfer( exchanges[exchangeId].exchangeOwner, amount ); emit TokenCollected( exchangeId, exchanges[exchangeId].exchangeOwner, exchanges[exchangeId].dataToken, amount ); } function collectMarketFee(bytes32 exchangeId) external { // anyone call call this function, because funds are sent to the correct address uint256 amount = exchanges[exchangeId].marketFeeAvailable; exchanges[exchangeId].marketFeeAvailable = 0; IERC20Template(exchanges[exchangeId].baseToken).transfer( exchanges[exchangeId].marketFeeCollector, amount ); emit MarketFeeCollected( exchangeId, exchanges[exchangeId].baseToken, amount ); } function collectOceanFee(bytes32 exchangeId) external { // anyone call call this function, because funds are sent to the correct address uint256 amount = exchanges[exchangeId].oceanFeeAvailable; exchanges[exchangeId].oceanFeeAvailable = 0; IERC20Template(exchanges[exchangeId].baseToken).transfer( opfCollector, amount ); emit OceanFeeCollected( exchangeId, exchanges[exchangeId].baseToken, amount ); } function updateMarketFeeCollector( bytes32 exchangeId, address _newMarketCollector ) external { require( msg.sender == exchanges[exchangeId].marketFeeCollector, "not marketFeeCollector" ); exchanges[exchangeId].marketFeeCollector = _newMarketCollector; } function updateMarketFee( bytes32 exchangeId, uint256 _newMarketFee ) external { require( msg.sender == exchanges[exchangeId].marketFeeCollector, "not marketFeeCollector" ); exchanges[exchangeId].marketFee = _newMarketFee; } /** * @dev getNumberOfExchanges * gets the total number of registered exchanges * @return total number of registered exchange IDs */ function getNumberOfExchanges() external view returns (uint256) { return exchangeIds.length; } /** * @dev setRate * changes the fixed rate for an exchange with a new rate * @param exchangeId a unique exchange idnetifier * @param newRate new fixed rate value */ function setRate(bytes32 exchangeId, uint256 newRate) external onlyExchangeOwner(exchangeId) { require(newRate != 0, "FixedRateExchange: Ratio must be >0"); exchanges[exchangeId].fixedRate = newRate; emit ExchangeRateChanged(exchangeId, msg.sender, newRate); } /** * @dev toggleMintState * toggle withMint state * @param exchangeId a unique exchange idnetifier * @param withMint new value */ function toggleMintState(bytes32 exchangeId, bool withMint) external onlyExchangeOwner(exchangeId) { exchanges[exchangeId].withMint = withMint; emit ExchangeMintStateChanged(exchangeId, msg.sender, withMint); } /** * @dev toggleExchangeState * toggles the active state of an existing exchange * @param exchangeId a unique exchange identifier */ function toggleExchangeState(bytes32 exchangeId) external onlyExchangeOwner(exchangeId) { if (exchanges[exchangeId].active) { exchanges[exchangeId].active = false; emit ExchangeDeactivated(exchangeId, msg.sender); } else { exchanges[exchangeId].active = true; emit ExchangeActivated(exchangeId, msg.sender); } } /** * @dev setAllowedSwapper * Sets a new allowedSwapper * @param exchangeId a unique exchange identifier * @param newAllowedSwapper refers to the new allowedSwapper */ function setAllowedSwapper(bytes32 exchangeId, address newAllowedSwapper) external onlyExchangeOwner(exchangeId) { exchanges[exchangeId].allowedSwapper = newAllowedSwapper; emit ExchangeAllowedSwapperChanged(exchangeId, newAllowedSwapper); } /** * @dev getRate * gets the current fixed rate for an exchange * @param exchangeId a unique exchange idnetifier * @return fixed rate value */ function getRate(bytes32 exchangeId) external view returns (uint256) { return exchanges[exchangeId].fixedRate; } /** * @dev getSupply * gets the current supply of datatokens in an fixed * rate exchagne * @param exchangeId the exchange ID * @return supply */ function getDTSupply(bytes32 exchangeId) public view returns (uint256 supply) { if (exchanges[exchangeId].active == false) supply = 0; else if (exchanges[exchangeId].withMint == true && IERC20Template(exchanges[exchangeId].dataToken).isMinter(address(this))){ supply = IERC20Template(exchanges[exchangeId].dataToken).cap() - IERC20Template(exchanges[exchangeId].dataToken).totalSupply(); } else { uint256 balance = IERC20Template(exchanges[exchangeId].dataToken) .balanceOf(exchanges[exchangeId].exchangeOwner); uint256 allowance = IERC20Template(exchanges[exchangeId].dataToken) .allowance(exchanges[exchangeId].exchangeOwner, address(this)); if (balance < allowance) supply = balance.add(exchanges[exchangeId].dtBalance); else supply = allowance.add(exchanges[exchangeId].dtBalance); } } /** * @dev getSupply * gets the current supply of datatokens in an fixed * rate exchagne * @param exchangeId the exchange ID * @return supply */ function getBTSupply(bytes32 exchangeId) public view returns (uint256 supply) { if (exchanges[exchangeId].active == false) supply = 0; else { uint256 balance = IERC20Template(exchanges[exchangeId].baseToken) .balanceOf(exchanges[exchangeId].exchangeOwner); uint256 allowance = IERC20Template(exchanges[exchangeId].baseToken) .allowance(exchanges[exchangeId].exchangeOwner, address(this)); if (balance < allowance) supply = balance.add(exchanges[exchangeId].btBalance); else supply = allowance.add(exchanges[exchangeId].btBalance); } } // /** // * @dev getExchange // * gets all the exchange details // * @param exchangeId a unique exchange idnetifier // * @return all the exchange details including the exchange Owner // * the dataToken contract address, the base token address, the // * fixed rate, whether the exchange is active and the supply or the // * the current data token liquidity. // */ function getExchange(bytes32 exchangeId) external view returns ( address exchangeOwner, address dataToken, uint256 dtDecimals, address baseToken, uint256 btDecimals, uint256 fixedRate, bool active, uint256 dtSupply, uint256 btSupply, uint256 dtBalance, uint256 btBalance, bool withMint // address allowedSwapper ) { Exchange memory exchange = exchanges[exchangeId]; exchangeOwner = exchange.exchangeOwner; dataToken = exchange.dataToken; dtDecimals = exchange.dtDecimals; baseToken = exchange.baseToken; btDecimals = exchange.btDecimals; fixedRate = exchange.fixedRate; active = exchange.active; dtSupply = getDTSupply(exchangeId); btSupply = getBTSupply(exchangeId); dtBalance = exchange.dtBalance; btBalance = exchange.btBalance; withMint = exchange.withMint; // allowedSwapper = exchange.allowedSwapper; } // /** // * @dev getAllowedSwapper // * gets allowedSwapper // * @param exchangeId a unique exchange idnetifier // * @return address of allowedSwapper // */ function getAllowedSwapper(bytes32 exchangeId) external view returns ( address allowedSwapper ) { Exchange memory exchange = exchanges[exchangeId]; allowedSwapper = exchange.allowedSwapper; } function getFeesInfo(bytes32 exchangeId) external view returns ( uint256 marketFee, address marketFeeCollector, uint256 opfFee, uint256 marketFeeAvailable, uint256 oceanFeeAvailable ) { Exchange memory exchange = exchanges[exchangeId]; marketFee = exchange.marketFee; marketFeeCollector = exchange.marketFeeCollector; opfFee = getOPFFee(exchanges[exchangeId].baseToken); marketFeeAvailable = exchange.marketFeeAvailable; oceanFeeAvailable = exchange.oceanFeeAvailable; } /** * @dev getExchanges * gets all the exchanges list * @return a list of all registered exchange Ids */ function getExchanges() external view returns (bytes32[] memory) { return exchangeIds; } /** * @dev isActive * checks whether exchange is active * @param exchangeId a unique exchange idnetifier * @return true if exchange is true, otherwise returns false */ function isActive(bytes32 exchangeId) external view returns (bool) { return exchanges[exchangeId].active; } }
* @dev getSupply gets the current supply of datatokens in an fixed rate exchagne @param exchangeId the exchange ID @return supply/
function getDTSupply(bytes32 exchangeId) public view returns (uint256 supply) { if (exchanges[exchangeId].active == false) supply = 0; else if (exchanges[exchangeId].withMint == true && IERC20Template(exchanges[exchangeId].dataToken).isMinter(address(this))){ supply = IERC20Template(exchanges[exchangeId].dataToken).cap() - IERC20Template(exchanges[exchangeId].dataToken).totalSupply(); } else { uint256 balance = IERC20Template(exchanges[exchangeId].dataToken) .balanceOf(exchanges[exchangeId].exchangeOwner); uint256 allowance = IERC20Template(exchanges[exchangeId].dataToken) .allowance(exchanges[exchangeId].exchangeOwner, address(this)); if (balance < allowance) supply = balance.add(exchanges[exchangeId].dtBalance); else supply = allowance.add(exchanges[exchangeId].dtBalance); } }
2,471,888
[ 1, 588, 3088, 1283, 1377, 5571, 326, 783, 14467, 434, 1150, 270, 3573, 316, 392, 5499, 1377, 4993, 431, 343, 346, 4644, 282, 7829, 548, 326, 7829, 1599, 327, 14467, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2343, 56, 3088, 1283, 12, 3890, 1578, 7829, 548, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 14467, 13, 203, 565, 288, 203, 3639, 309, 261, 338, 6329, 63, 16641, 548, 8009, 3535, 422, 629, 13, 14467, 273, 374, 31, 203, 3639, 469, 309, 261, 338, 6329, 63, 16641, 548, 8009, 1918, 49, 474, 422, 638, 203, 3639, 597, 467, 654, 39, 3462, 2283, 12, 338, 6329, 63, 16641, 548, 8009, 892, 1345, 2934, 291, 49, 2761, 12, 2867, 12, 2211, 3719, 15329, 203, 5411, 14467, 273, 467, 654, 39, 3462, 2283, 12, 338, 6329, 63, 16641, 548, 8009, 892, 1345, 2934, 5909, 1435, 7010, 5411, 300, 467, 654, 39, 3462, 2283, 12, 338, 6329, 63, 16641, 548, 8009, 892, 1345, 2934, 4963, 3088, 1283, 5621, 203, 3639, 289, 203, 3639, 469, 288, 203, 5411, 2254, 5034, 11013, 273, 467, 654, 39, 3462, 2283, 12, 338, 6329, 63, 16641, 548, 8009, 892, 1345, 13, 203, 7734, 263, 12296, 951, 12, 338, 6329, 63, 16641, 548, 8009, 16641, 5541, 1769, 203, 5411, 2254, 5034, 1699, 1359, 273, 467, 654, 39, 3462, 2283, 12, 338, 6329, 63, 16641, 548, 8009, 892, 1345, 13, 203, 7734, 263, 5965, 1359, 12, 338, 6329, 63, 16641, 548, 8009, 16641, 5541, 16, 1758, 12, 2211, 10019, 203, 5411, 309, 261, 12296, 411, 1699, 1359, 13, 203, 7734, 14467, 273, 11013, 18, 1289, 12, 338, 6329, 63, 16641, 548, 8009, 7510, 13937, 1769, 203, 5411, 469, 14467, 273, 1699, 1359, 18, 1289, 12, 338, 2 ]
pragma solidity ^0.5.0; contract Auction { // Create a structure to store information about an item in the auction house struct Item{ string item_name; // name string item_desc; // description uint base_price; // start price uint min_increment; // minimum increment for a bid uint auction_price; // current price of item } // Declaring global variables for the contract, we assume 4 as the number of items, this number can be adjusted uint constant itemCount = 4; uint[itemCount] public arrayForItems; uint public itemId = 0; // Creating hash tables for storing information mapping(uint => Item) public items; // item hash table mapping(uint => address) public highestBidders; // highest bidders hash table // Declaring events which help us use ethereum's logging facility event BidEvent(uint _itemId, uint indexed _bidAmt); // Constructor constructor() public { addItem("Adam’s Python Monster truck", "When you have a big brain, you need a big truck!", 100, 2, 100); addItem("Steve's Subaru Wagon", "Made for Nerds that love adventures.", 50,1, 50); addItem("Nenita's G Wagon", "Stylish,Functional, Expensive!", 150, 35, 150); addItem("Benny's Porsche", "For distinguished developers.", 1000, 100, 1000); } // Function to add items and highest bidders, incrementing itemCount (itemCount starts at 0) function addItem (string memory _name, string memory _desc, uint _baseValue, uint _increment, uint _startPrice) private { items[itemId] = Item(_name, _desc, _baseValue, _increment,_startPrice); highestBidders[itemId] = address(0); itemId ++; } // Function to get item count function getItemCount () public pure returns (uint) { return itemCount; } // Function to get the name of an item using its item id function getItemName (uint _itemId) public view returns (string memory) { require(_itemId >= 0 && _itemId < itemCount, "Item does not exist"); // the item id must be greater than 0 but less or equal to the total count return items[_itemId].item_name; } // Function to get the highest current price of an item using its item id function getItemPrice (uint _itemId) public view returns (uint) { require(_itemId >= 0 && _itemId < itemCount, "Item does not exist"); // the item id must be greater than 0 but less or equal to the total count return items[_itemId].auction_price; } // Function to get the min_increment of an item using its item id function getItemIncrement (uint _itemId) public view returns (uint) { require(_itemId >= 0 && _itemId < itemCount, "Item does not exist"); // the item id must be greater than 0 but less or equal to the total count return items[_itemId].min_increment; } // Function to get percent increase in value over original listing price function getPercentIncrease (uint _itemId) public view returns (uint) { uint auctionPrice = items[_itemId].auction_price; uint basePrice = items[_itemId].base_price; uint percentIncrease = (auctionPrice - basePrice)*100/basePrice; return percentIncrease; } // Function to get numerical information for all items in the auction as an array function getArrayOfNumericalInformation (uint num) public view returns (uint[itemCount] memory) { uint[itemCount] memory arrayOfNumbers; for (uint i=0;i < itemCount; i++) { if (num == 1) { arrayOfNumbers[i] = this.getItemPrice(i); } else if (num == 2) { arrayOfNumbers[i] = this.getPercentIncrease(i); } else if (num == 3) { arrayOfNumbers[i] = this.getItemIncrement(i); } } return arrayOfNumbers; } // Function to get array of prices of all items in auction as an array function getArrayOfPrices () public view returns (uint[itemCount] memory) { return this.getArrayOfNumericalInformation(1); } // Function to get array of increase in percentages of all items in auction as an array function getArrayOfIncreases () public view returns (uint[itemCount] memory) { return this.getArrayOfNumericalInformation(2); } // Function to get array of increments of all items in auction as an array function getArrayOfIncrements () public view returns (uint[itemCount] memory) { return this.getArrayOfNumericalInformation(3); } // Function to get the array of highest bidders function getHighestBidders () public view returns (address[itemCount] memory) { address[itemCount] memory arrayOfBidders; for (uint i=0;i < itemCount; i++) { arrayOfBidders[i] = highestBidders[i]; } return arrayOfBidders; } // Function to place a bid function placeBid (uint _itemId, uint _bidAmt) public returns (uint) { // Requirements require(_itemId >= 0 && _itemId < itemCount, "Bidding on an invalid item"); // the item id must be greater than 0 but less than the total count require(check_bid (_itemId, _bidAmt),"Bid is lower or equal to the highest bid value"); // the bid should be higher or equal to the current require(check_increment (_itemId, _bidAmt),"Bid is not enough based on minimum increment"); // make sure that the increment is greater than or equal to the minimum increment for the auction item require(check_highest_bidder(_itemId, msg.sender), "Person bidding is the highest bidder"); // make sure that person bidding isn't already highest bidder items[_itemId].auction_price = _bidAmt; // replace the current price with the new bid amount highestBidders[_itemId] = msg.sender; // replace the highest bidder for that item id with the new highest bidder emit BidEvent(_itemId, _bidAmt); // logs the bid event on ethereum EVM return _itemId; // return the item back } // Function to check if the bid is greater than highest bid function check_bid (uint _itemId, uint _bidAmt) public view returns (bool) { if (_bidAmt > items[_itemId].auction_price) return true; else return false; } // Function to check if the difference is greater to minimum increment value function check_increment (uint _itemId, uint _bidAmt) public view returns (bool) { uint diff; diff = _bidAmt - items[_itemId].auction_price; if (diff >= items[_itemId].min_increment) return true; else return false; } // Function to check if person bidding is the highest bidder function check_highest_bidder (uint _itemId, address person_wallet) public view returns (bool) { if (person_wallet == highestBidders[_itemId]) { return false; } else { return true; } } }
Function to add items and highest bidders, incrementing itemCount (itemCount starts at 0)
function addItem (string memory _name, string memory _desc, uint _baseValue, uint _increment, uint _startPrice) private { items[itemId] = Item(_name, _desc, _baseValue, _increment,_startPrice); highestBidders[itemId] = address(0); itemId ++; }
12,872,541
[ 1, 2083, 358, 527, 1516, 471, 9742, 324, 1873, 414, 16, 5504, 310, 761, 1380, 261, 1726, 1380, 2542, 622, 374, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 15009, 261, 1080, 3778, 389, 529, 16, 533, 3778, 389, 5569, 16, 2254, 389, 1969, 620, 16, 2254, 389, 15016, 16, 2254, 389, 1937, 5147, 13, 3238, 288, 3196, 203, 202, 202, 3319, 63, 1726, 548, 65, 273, 4342, 24899, 529, 16, 389, 5569, 16, 389, 1969, 620, 16, 389, 15016, 16, 67, 1937, 5147, 1769, 203, 202, 202, 8766, 395, 38, 1873, 414, 63, 1726, 548, 65, 273, 1758, 12, 20, 1769, 203, 202, 202, 1726, 548, 965, 31, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; contract CrossAssetSwap { // bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26; // bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; /* struct ERC20Details { address[] tokenAddrs; uint256[] amounts; } struct ERC721Details { address[] tokenAddrs; uint256[] ids; } struct ERC1155Details { address[] tokenAddrs; uint256[] ids; uint256[] amounts; } */ // swaps any combination of ERC-20/721/1155 // User needs to approve assets before invoking swap /* function swap( ERC20Details calldata inputERC20s, ERC721Details calldata inputERC721s, ERC1155Details calldata inputERC1155s, ERC20Details calldata outputERC20s, ERC721Details calldata outputERC721s, ERC1155Details calldata outputERC1155s ) external { // transfer ERC20 tokens from the sender to this contract // WARNING: It is assumed that the ERC20 token addresses are NOT malicious for (uint256 i = 0; i < inputERC20s.tokenAddrs.length; i++) { IERC20(inputERC20s.tokenAddrs[i]).transferFrom( msg.sender, address(this), inputERC20s.amounts[i] ); } // transfer ERC721 tokens from the sender to this contract // WARNING: It is assumed that the ERC721 token addresses are NOT malicious for (uint256 i = 0; i < inputERC721s.tokenAddrs.length; i++) { IERC721(inputERC721s.tokenAddrs[i]).transferFrom( msg.sender, address(this), inputERC721s.ids[i] ); } // transfer ERC1155 tokens from the sender to this contract // WARNING: It is assumed that the ERC1155 token addresses are NOT malicious for (uint256 i = 0; i < inputERC1155s.tokenAddrs.length; i++) { IERC1155(inputERC1155s.tokenAddrs[i]).safeBatchTransferFrom( msg.sender, address(this), inputERC1155s.ids[i], inputERC1155s.amounts[i], "" ); } } */ }
transfer ERC721 tokens from the sender to this contract WARNING: It is assumed that the ERC721 token addresses are NOT malicious
for (uint256 i = 0; i < inputERC721s.tokenAddrs.length; i++) { IERC721(inputERC721s.tokenAddrs[i]).transferFrom( msg.sender, address(this), inputERC721s.ids[i] ); }
2,540,871
[ 1, 13866, 4232, 39, 27, 5340, 2430, 628, 326, 5793, 358, 333, 6835, 9744, 30, 2597, 353, 12034, 716, 326, 4232, 39, 27, 5340, 1147, 6138, 854, 4269, 27431, 28728, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 810, 654, 39, 27, 5340, 87, 18, 2316, 13811, 18, 2469, 31, 277, 27245, 288, 203, 5411, 467, 654, 39, 27, 5340, 12, 2630, 654, 39, 27, 5340, 87, 18, 2316, 13811, 63, 77, 65, 2934, 13866, 1265, 12, 203, 7734, 1234, 18, 15330, 16, 203, 7734, 1758, 12, 2211, 3631, 203, 7734, 810, 654, 39, 27, 5340, 87, 18, 2232, 63, 77, 65, 203, 5411, 11272, 203, 3639, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// namehash("hatch.eth") bytes32 constant nodehashHatch = 0x54e801acbb1a4f9d2f51dae289e38bc712f13d4dca03b5321203b74e9869a091; bytes32 constant nodehashReverse = 0x91d1777781884d03a6757a803996e38de2a42967fb37eeaca72729271025a9e2; // dnsEncode("hatch.eth") string constant dnsHatch = "\x05hatch\x03eth\x00"; interface ReverseRegistrar { function setName(string memory name) external returns (bytes32); } interface Resolver { function addr(bytes32 nodehash) external view returns (address); } interface ResolverMulticoin { function addr(bytes32 nodehash, uint coinType) external view returns (address); } interface AbstractENS { function owner(bytes32 nodehash) external view returns (address); function resolver(bytes32) external view returns (address); } function _keccak(uint offset, uint length, bytes memory data) view returns (bytes32 result) { assembly { result := keccak256(add(offset, add(data, 32)), length) } } function _namehash(uint offset, bytes memory dnsName) view returns (bytes32) { require(offset < dnsName.length); uint8 length = uint8(dnsName[offset]); if (length == 0) { return 0; } uint start = offset + 1; uint end = start + length; return keccak256(abi.encodePacked( _namehash(end, dnsName), _keccak(start, length, dnsName) )); } function namehash(bytes memory dnsName) view returns (bytes32) { return _namehash(0, dnsName); } // A Nook is a permanent wallet deployed by a Proxy. It is counterfactually // deployed, so its address can be used to store ether by a proxy, for // example if the proxy self-destructs. At any point a Proxy may call reclaim // to receive its ether back. contract NookWallet { address payable public immutable owner; constructor() { owner = payable(msg.sender); reclaim(); } // Forwards all funds in this Nook to its Proxy function reclaim() public { require(msg.sender == owner); owner.send(address(this).balance); } // Allow receiving funds receive() external payable { } } // The proxy is a smart contract wallet contract Proxy { address public immutable ens; bytes32 public immutable nodehash; constructor(address _ens, bytes32 _nodehash) { ens = _ens; nodehash = _nodehash; } function nookAddress() public view returns (address payable nook) { return payable(address(uint160(uint256(keccak256(abi.encodePacked( bytes1(0xff), address(this), nodehash, keccak256(type(NookWallet).creationCode) )))))); } function reclaimNook() external returns (address) { address payable nook = nookAddress(); if (nook.codehash == 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470) { // If the nook isn't deployed, deploy it (which forwards all funds to this) new NookWallet{ salt: nodehash }(); } else { // Otherwise, call reclaim NookWallet(nook).reclaim(); } return nook; } function execute(address target, bytes calldata data, uint value) public returns (bool status, bytes memory result) { // Owner the controller can call this require(AbstractENS(ens).owner(nodehash) == msg.sender, "not authorized"); // We use assembly so we can call EOAs assembly { status := call(gas(), target, value, data.offset, data.length, 0, 0) result := mload(0x40) mstore(0x40, add(result, and(add(add(returndatasize(), 0x20), 0x1f), not(0x1f)))) mstore(result, returndatasize()) returndatacopy(add(result, 32), 0, returndatasize()) } } function executeMulitple(address[] calldata targets, bytes[] calldata datas, uint[] calldata values) external returns (bool[] memory statuses, bytes[] memory results) { require(targets.length == datas.length); require(targets.length == values.length); statuses = new bool[](targets.length); results = new bytes[](targets.length); for (uint i = 0; i < targets.length; i++) { (bool status, bytes memory result) = execute(targets[i], datas[i], values[i]); statuses[i] = status; results[i] = result; } } function remove() external { // Owner the controller can call this require(AbstractENS(ens).owner(nodehash) == msg.sender, "not authorized"); // Send all funds (at the conclusion of this tx) to the nook // address, which can be counter-factually deployed later selfdestruct(nookAddress()); } // Allow receiving funds receive() external payable { } } contract HatchMaker { address immutable ens; event DeployedProxy(bytes indexed indexedName, bytes dnsName, address owner); constructor(address _ens) { ens = _ens; // Set the reverse record address reverseRegistrar = AbstractENS(ens).owner(nodehashReverse); ReverseRegistrar(reverseRegistrar).setName("hatch.eth"); } function _addressForNodehash(bytes32 nodehash) internal view returns (address) { return address(uint160(uint256(keccak256(abi.encodePacked( bytes1(0xff), address(this), nodehash, keccak256(abi.encodePacked( type(Proxy).creationCode, bytes32(uint(uint160(ens))), nodehash )) ))))); } function addressForName(bytes calldata dnsName) public view returns (address) { return _addressForNodehash(namehash(dnsName)); } function deployProxy(bytes calldata dnsName) external returns (address) { bytes32 nodehash = namehash(dnsName); Proxy proxy = new Proxy{ salt: nodehash }(ens, nodehash); emit DeployedProxy(dnsName, dnsName, address(proxy)); return address(proxy); } // Returns the Proxy for addr calls, and forwards all other requests // to the name's resolver function resolve(bytes calldata dnsName, bytes calldata data) external view returns (bytes memory) { bytes4 sel = bytes4(data[0:4]); // Handle the hatch.eth root if (keccak256(dnsName) == keccak256(bytes(dnsHatch)) && data.length >= 36) { // [ bytes4:selector ][ bytes32:namehash("hatch.eth") ] require(bytes32(data[4:36]) == nodehashHatch); // [ bytes4:selectoraddr(bytes32) ][ bytes32:namehash("hatch.eth") ] if (data.length == 36 && sel == Resolver.addr.selector) { return abi.encode(address(this)); } // [ bytes4:selectoraddr(bytes32) ][ bytes32:namehash("hatch.eth") ][ uint:60 ] if (data.length == 68 && sel == ResolverMulticoin.addr.selector) { if (uint(bytes32(data[36:68])) == 60) { return abi.encode(abi.encodePacked(address(this))); } } // @TODO: Handle fun things like avatar revert("todo"); //address resolver = ens.resolver(??); //require(resolver != address(0)); //return resolver.call(abi.encodePacked(data[0:4], ownerNodehash, data[36:])); } // Length of the hatch owner label uint length = uint8(dnsName[0]); // Must match XXX.hatch.eth require(keccak256(dnsName[1 + length:]) == keccak256(bytes(dnsHatch)), "unknown suffix"); // The hatch owner name and hash (e.g. ricmoo.hatch.eth => ricmoo.eth) bytes memory ownerName = abi.encodePacked(dnsName[0: length + 1], "\x03eth\x00"); bytes32 ownerNodehash = namehash(ownerName); // Hijack: addr(bytes32 nodehash) view returns (address) // Returns the hatch address instead of returning the // target resolver's address. [EIP-] if (data.length == 36 && sel == Resolver.addr.selector) { //require(namehash(dnsName) == bytes32(data[4:36])); return abi.encode(_addressForNodehash(ownerNodehash)); } // Hijack: addr(bytes32 nodehash, uint cointype) view returns (address) // Returns the hatch address instead of returning the // target resolver's address. [EIP-] if (data.length == 68 && sel == ResolverMulticoin.addr.selector && uint(bytes32(data[36:68])) == 60) { //require(namehash(dnsName) == bytes32(data[4:36])); return abi.encode(abi.encodePacked(_addressForNodehash(ownerNodehash))); } // Forward the request to the actual resolver, replacing the nodehash // with the owner nodehash address resolver = AbstractENS(ens).resolver(ownerNodehash); require(resolver != address(0)); // @TODO: Check for wildcard support and use resolve(bytes, bytes) instead (bool status, bytes memory result) = resolver.staticcall(abi.encodePacked(data[0:4], ownerNodehash, data[36:])); if (status) { revert("call reverted"); } return result; } }
Forwards all funds in this Nook to its Proxy
function reclaim() public { require(msg.sender == owner); owner.send(address(this).balance); }
15,853,153
[ 1, 1290, 6397, 777, 284, 19156, 316, 333, 423, 1184, 358, 2097, 7659, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 283, 14784, 1435, 1071, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 1769, 203, 3639, 3410, 18, 4661, 12, 2867, 12, 2211, 2934, 12296, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42220/0x928aA9B52A0025D4e91a586F5a09d2f45E4AC2F4/sources/CelofarmsRouter.sol
send liquidity to pair
ICelofarmsPair(pair).transferFrom(msg.sender, pair, liquidity);
16,337,166
[ 1, 4661, 4501, 372, 24237, 358, 3082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 26899, 292, 792, 20452, 4154, 12, 6017, 2934, 13866, 1265, 12, 3576, 18, 15330, 16, 3082, 16, 4501, 372, 24237, 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/1/0xF8243ECF8f734452B184A1dF3AD3cD92fC93B58a/sources/project_/contracts/lending/wrapper/CappedGovToken.sol
allowances are never granted, as the VotingVault does not grant allowances. this function is therefore always uncallable and so we will just return false
function transferFrom( address /*sender*/, address /*recipient*/, uint256 /*amount*/ ) public pure override returns (bool) { return false; }
2,879,082
[ 1, 5965, 6872, 854, 5903, 17578, 16, 487, 326, 776, 17128, 12003, 1552, 486, 7936, 1699, 6872, 18, 333, 445, 353, 13526, 3712, 6301, 454, 429, 471, 1427, 732, 903, 2537, 327, 629, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 7412, 1265, 12, 203, 565, 1758, 1748, 15330, 5549, 16, 203, 565, 1758, 1748, 20367, 5549, 16, 203, 565, 2254, 5034, 1748, 8949, 5549, 203, 225, 262, 1071, 16618, 3849, 1135, 261, 6430, 13, 288, 203, 565, 327, 629, 31, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
word_set WhWords= { 'what', // What do you sing? 'why', // Why do you sing? 'where', // Where do you live? 'who', // Who is your friend? 'when', // When do you work? 'whom', // Whom do you love? 'how' // How do you sing? } // наречия, которые выступают в роли детерминантов для существительных. wordentry_set SingDetAdverbs = { eng_adverb:much{}, // Much money is spent for defence. There is much milk in the jug. eng_adverb:"so much"{}, // I have so much work to do. eng_adverb:"a little"{}, // We all need a little sugar! eng_adverb:"how many"{} } wordentry_set AuxEngVerbs= { eng_verb:do{}, eng_auxverb:will{}, eng_beverb:be{}, eng_auxverb:can{}, eng_verb:have{}, eng_auxverb:must{}, eng_auxverb:should{}, eng_auxverb:may{}, eng_verb:need{} } wordentry_set SpecialAuxVerbsED= { eng_auxverb:may{}, eng_beverb:be{}, eng_verb:do{}, eng_verb:have{}, eng_verb:dare{}, eng_verb:need{}, eng_beverb:be_not{}, eng_verb:"don't"{}, eng_verb:"haven't"{}, eng_auxverb:will{}, eng_auxverb:can{}, eng_auxverb:cannot{}, eng_auxverb:would_not{}, eng_auxverb:should_not{} } wordentry_set ModalCopulaVerbs = { eng_auxverb:can{}, eng_auxverb:must{}, eng_auxverb:should{}, eng_auxverb:may{}, eng_auxverb:would{} } wordentry_set ModalCopulaVerbsNot = { eng_auxverb:cannot{}, eng_auxverb:would_not{}, eng_auxverb:should_not{} } // некоторые наречия не могут стоять перед глаголом. wordentry_set CannotBeBeforeVerb= { eng_adverb:like{}, eng_adverb:much{}, eng_adverb:very{}, eng_adverb:"a little"{}, eng_adverb:"how many"{}, eng_adverb:little{}, eng_adjective:many{}, eng_adverb:alone{}, eng_adverb:soon{}, eng_adverb:in{}, eng_adverb:too{} }
Much money is spent for defence. There is much milk in the jug.
eng_adverb:much{},
7,302,245
[ 1, 49, 2648, 15601, 353, 26515, 364, 1652, 802, 18, 6149, 353, 9816, 312, 330, 79, 316, 326, 525, 637, 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 ]
[ 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, 27573, 24691, 67, 361, 16629, 30, 81, 2648, 2916, 16, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.13; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol'; import '@openzeppelin/contracts/utils/Address.sol'; import '@openzeppelin/contracts/utils/Strings.sol'; import '@openzeppelin/contracts/utils/introspection/ERC165.sol'; // HOOPS NFT // ________ // o | __ | // \_ O | |__| | // ____/ \ |___WW___| // __/ / || // || // || // _______________||________________ // Created by MasoRich and Bubba Dutch Studios // Contract by mö̵͊ö̵͊n & The Nexus Crew // Based on ERC721A contract by Chiru Labs contract Hoops is ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using Address for address; using Strings for uint256; string private _unrevealedBaseURI = 'ipfs://QmekCwrU6SsTNcFEgCs36kcry6KE7zeBsSuC1nXi5KZL6o/'; // ................ // ..... .... string private _baseURI = ''; // ... ..%%%%%%%%%%%%%%%. .... // .%. ..%%%%%..... .....%%%%%.. .. address _treasuryAddress = 0x87Bc1aC91E5BeC68BCe0427A0E627828F7c52a67; // .. .%%%... ..%%%. .. // .. .%%.. .%%. .. string private _uriSuffix = '.json'; // % .%%. WE <3 BASKETBALL .%% .. // . %%% .%% % uint private _mintPrice = 0.0824 ether; // % %%% HOOPS 4 LYFE %%% % // % %% %% % uint private _maxMintQuantity = 25; // % %% ssssssssssssss %% % // % %% %% %% %% % uint private _maxSupply = 10000; // % %% %% %% %% % // % %% %% %% %% % bool _mintIsOpen = false; // % %% %% %% %% % // % %% %% %% %% % uint private _revealIndex = 0; // % %% %% %% %% % // % %% .%%%%%%%%%%%%%%%%%%. %% % bool _stickersEnabled = false; // % %%% .%..%...%..%...%..%. %%% % // % %% .. % % % % % %% % uint256 internal currentIndex = 1; // % %%. %. %% % % % . .%% % // %. .%% %%%%%%%%%%%%%%%%% %%. % // Mapping from token ID to ownership details // %. .%%. % %% %% % %% % .%%. . mapping(uint256 => TokenOwnership) internal _ownerships; // .. .%%. .% % %% % %. % .%%. . // .. .%%%. %..%.....%..%..% ..%%. .. // Mapping owner address to address data // .. .%%..% %% %%% % %%.%%.. .. mapping(address => AddressData) private _addressData; // .. ..%% %. %%% %. %%%. ... // ... %%.%..%%..%%.% ... // Mapping from token ID to approved address // ... %%.%..%%..%.%% ... mapping(uint256 => address) private _tokenApprovals; // ..% % %% % %%. // % %% %% % % // %%%%%%%%%%%% // Mapping from owner to operator approvals // . % %% % % mapping(address => mapping(address => bool)) private _operatorApprovals;// % % %% % %. // %.%%.%.%.% // This the is owner of the contract address private _owner; // Stickers will be a customization option we enable after launch // Users should use the portal app we provide, although anyone can make customizations if they really want // Please use this feature responsibly so we don't have to turn it off for everyone or make it owner-only mapping(uint256 => string) internal _stickerURIs; // Should only the owner of the contract be able to customize the stickers? bool _anyoneCanCustomize = true; function setAnyoneCanCustomize(bool anyoneCanCustomize) public onlyOwner { _anyoneCanCustomize = anyoneCanCustomize; } function setStickersEnabled(bool stickersEnabled) public onlyOwner { _stickersEnabled = stickersEnabled; } function setStickerUri(uint256 tokenId, string memory uri) public { require((_anyoneCanCustomize && _stickersEnabled) || msg.sender == _owner, "Stickers are not customizable right now"); require(ownerOf(tokenId) == msg.sender || msg.sender == _owner, "Only the token owner can set the sticker URI"); _stickerURIs[tokenId] = uri; } function hasStickers(uint256 tokenId) public view returns (bool) { require(_stickersEnabled || msg.sender == _owner, "Stickers are not enabled"); return bytes(_stickerURIs[tokenId]).length != 0; } function getStickerUri(uint256 tokenId) public view returns (string memory) { require(_stickersEnabled || msg.sender == _owner, "Stickers are not enabled"); // TASK: return true if the sticker URI is set in _stickerURIs mapping and false if it is an empty string if(bytes(_stickerURIs[tokenId]).length > 0){ return _stickerURIs[tokenId]; } return ""; } function resetStickers(uint256 tokenId) public { require(_stickersEnabled || msg.sender == _owner, "Stickers are not enabled"); require(ownerOf(tokenId) == msg.sender || msg.sender == _owner, "Only the owner can reset sticker uri"); _stickerURIs[tokenId] = ""; } struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() { _owner = msg.sender; } function getMintPrice() public view returns (uint) { return _mintPrice; } // Set the _mintPrice to a new value in ether if the msg.sender is the _owner function setMintPrice(uint newPrice) public onlyOwner { _mintPrice = newPrice; } function transferOwnership(address owner) public virtual onlyOwner { _owner = owner; } function withdraw() public onlyTreasurerOrOwner { // This will transfer the remaining contract balance to the owner. (bool os, ) = payable(_treasuryAddress).call{value: address(this).balance}(''); require(os); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == msg.sender, 'Caller is not the owner'); _; } /** * @dev Throws if called by any account other than the owner or treasurer. */ modifier onlyTreasurerOrOwner() { require(_owner == msg.sender || _owner == _treasuryAddress, 'Caller is not the owner or treasurer'); _; } modifier onlyValidAccess() { require(_owner == msg.sender || _mintIsOpen, 'You are not the owner and the mint is not open'); _; } function isMintOpen() public view returns (bool) { return _mintIsOpen; } function setOpenMint(bool mintIsOpen) public onlyOwner { _mintIsOpen = mintIsOpen; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { return currentIndex - 1; } function maxSupply() public view returns (uint256) { return _maxSupply; } function availableSupply() public view returns (uint256) { return _maxSupply - (currentIndex - 1); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { require(index < currentIndex && index > 0, 'Index must be between 1 and 10,000'); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. * This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first. * It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case. */ function tokenOfOwnerByIndex(address tokenOwner, uint256 index) public view override returns (uint256) { require(index < balanceOf(tokenOwner), 'Owner index is out of bounds'); uint256 tokenIdsIdx; address currOwnershipAddr; // Counter overflow is impossible as the loop breaks when uint256 i is equal to another uint256 numMintedSoFar. unchecked { for (uint256 i = 1; i < currentIndex; i++) { TokenOwnership memory ownership = _ownerships[i]; if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == tokenOwner) { if (tokenIdsIdx == index) { return i; } tokenIdsIdx++; } } } revert('No token found'); // unable to get token of owner by index } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), '0x'); // balance query for the zero address return uint256(_addressData[owner].balance); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { require(_exists(tokenId), 'No token found'); // owner query for nonexistent token unchecked { for (uint256 curr = tokenId; curr >= 0; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } revert('No owner'); // unable to determine the owner of token } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return 'Hoops'; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return 'HOOPS'; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), 'No token found'); // ERC721Metadata: URI query for nonexistent token if(_stickersEnabled && hasStickers(tokenId)){ return string(abi.encodePacked(_stickerURIs[tokenId], tokenId.toString(), _uriSuffix)); } return string(abi.encodePacked(tokenId < _revealIndex ? _baseURI : _unrevealedBaseURI, tokenId.toString(), _uriSuffix)); } /** * @dev This gets us the non-sticker URI, even if stickers are enabled */ function baseTokenURI(uint256 tokenId) public view virtual returns (string memory) { require(_exists(tokenId), 'No token found'); // ERC721Metadata: URI query for nonexistent token return string(abi.encodePacked(tokenId < _revealIndex ? _baseURI : _unrevealedBaseURI, tokenId.toString(), _uriSuffix)); } function setBaseURI(string memory baseURI) public onlyOwner { _baseURI = baseURI; } function setUnrevealBaseURI(string memory baseURI) public onlyOwner { _unrevealedBaseURI = baseURI; } function setRevealIndex(uint index) public onlyOwner { _revealIndex = index; } function setUriSuffix(string memory uriSuffix) public onlyOwner { _uriSuffix = uriSuffix; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = Hoops.ownerOf(tokenId); require(to != owner, 'Only the owner can call this function'); // approval to current owner require( msg.sender == owner || isApprovedForAll(owner, msg.sender), 'Not approved' // approve caller is not owner nor approved for all ); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), 'No token found'); // approved query for nonexistent token return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { require(operator != msg.sender, 'Not the caller'); // approve to caller _operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public override { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), 'not721' // transfer to non ERC721Receiver implementer ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < currentIndex && tokenId > 0; } function goat() public pure returns (string memory) { return '"Greatness is defined by how much you want to put into what you do." - LeBron James'; } function mintForAddress( uint256 quantity, address to ) public payable onlyValidAccess() { _mint(to, quantity); } function mint( uint256 quantity ) public payable { _mint(msg.sender, quantity); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity ) internal onlyValidAccess() { uint256 startTokenId = currentIndex; require(_owner == msg.sender || _mintIsOpen, 'Minting is currently closed'); // Don't allow anyone to mint if the mint is closed require(to != address(0), 'Cannot send to 0x0'); // mint to the 0x0 address require(quantity != 0, 'Quantity cannot be 0'); // quantity must be greater than 0 require(_owner == msg.sender || quantity <= _maxMintQuantity, 'Quantity exceeds mint max'); // quantity must be less than max quantity // The owner can mint for free, everyone else needs to pay the price require(_owner == msg.sender || msg.value >= _mintPrice * quantity, "Insufficient funds!"); require(currentIndex <= _maxSupply, 'No Hoops left!'); // sold out require(currentIndex + quantity <= _maxSupply, 'Not enough Hoops left to buy!'); // cannot mint more than maxIndex tokens unchecked { _addressData[to].balance += uint128(quantity); _addressData[to].numberMinted += uint128(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, ''), 'Not ERC721Receiver' // transfer to non ERC721Receiver implementer ); updatedIndex++; } currentIndex = updatedIndex; } } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (msg.sender == prevOwnership.addr || getApproved(tokenId) == msg.sender || isApprovedForAll(prevOwnership.addr, msg.sender)); require(isApprovedOrOwner, 'Notapproved'); // transfer caller is not owner nor approved require(prevOwnership.addr == from, 'Invalid Owner'); // transfer from incorrect owner require(to != address(0), '0x'); // transfer to the zero address // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert('not721'); // transfer to non ERC721Receiver implementer } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } } // ▓▓▓▓▒▒▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ░░████████████▒▒▒▒▒▒▒▒▒▒▒▒▓▓██▓▓▓▓▓▓██ // ████▓▓▒▒▒▒▓▓████▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓████ // ▒▒▒▒▓▓▓▓▓▓▒▒▒▒▒▒██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓██▒▒▓▓ // ▓▓▓▓██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓██▓▓▓▓ // ▓▓██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓██▓▓ // ██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒Welcome to the Hoops team▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓ // ░░██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓██████████████▓▓████ // ▓▓██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▒▒▓▓████▓▓ // ▓▓▓▓▓▓██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓ // ░░████▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓ // ░░▓▓▓▓▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓ // ▓▓██▓▓▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▓▓ // ▓▓██▒▒▒▒▓▓▓▓██▓▓▓▓▓▓▓▓▓▓▒▒▓▓██▒▒▒▒▒▒▒▒▒▒▓▓▓▓██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓██ // ████████▓▓▓▓▓▓▓▓▒▒▒▒▒▒▒▒▓▓██████▓▓██████▓▓▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒████ // ▓▓▒▒▒▒▒▒▒▒▒▒▓▓██▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒████████▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓ // ████▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒████████▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓ // ██▓▓▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒Please join us on discord at https://discord.gg/hoops▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓ // ██▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██ // ░░██▓▓▒▒▒▒▒▒▒▒████▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██████▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓ // ░░████▒▒▒▒▒▒▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒████▓▓▒▒▒▒▒▒▒▒▒▒▒▒██▓▓ // ░░▓▓▒▒▒▒▒▒▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▓▓▓▓▓▓▒▒▒▒▒▒▒▒▓▓▓▓ // ░░▓▓▒▒▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓▒▒▒▒▒▒▒▒▓▓ // ░░████▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓▒▒▒▒▓▓ // ░░▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓████▓▓▓▓ // ░░██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓ // ▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓ // ░░██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓ // ░░▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓ // ░░██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒ // ██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓ // ▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒████▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓ // ██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓ // ▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██ // ▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓██ // ▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒████ // ▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓██░░ // ░░██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓░░ // ░░▓▓██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒██▓▓ // ██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▓▓▓▓ // ██▓▓▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▓▓▓▓██ // ▓▓██▒▒▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▒▒▒▒▒▒████ // ██▓▓▒▒▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▒▒▒▒▓▓▓▓░░ // ██▓▓▒▒▒▒██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒██▓▓▓▓▓▓ // ▒▒██▓▓▓▓██▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓██░░ // ░░▒▒▓▓██▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓██░░░░ // ██████▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓████▓▓ // ▓▓▓▓██▓▓▓▓▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▓▓▓▓██▓▓▓▓██ // ▓▓██▓▓██████████████████▓▓▓▓ // 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 (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 (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/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 (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); }
* @dev Throws if called by any account other than the owner or treasurer./
modifier onlyTreasurerOrOwner() { require(_owner == msg.sender || _owner == _treasuryAddress, 'Caller is not the owner or treasurer'); _; }
14,482,757
[ 1, 21845, 309, 2566, 635, 1281, 2236, 1308, 2353, 326, 3410, 578, 9787, 345, 11278, 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, 9606, 1338, 56, 266, 345, 11278, 1162, 5541, 1435, 288, 203, 3639, 2583, 24899, 8443, 422, 1234, 18, 15330, 747, 389, 8443, 422, 389, 27427, 345, 22498, 1887, 16, 296, 11095, 353, 486, 326, 3410, 578, 9787, 345, 11278, 8284, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Earrings SVG generator library EarringsDetail { /// @dev Earrings N°1 => Classic function item_1() public pure returns (string memory) { return ""; } /// @dev Earrings N°2 => Circle function item_2() public pure returns (string memory) { return base(circle("000000")); } /// @dev Earrings N°3 => Circle Silver function item_3() public pure returns (string memory) { return base(circle("C7D2D4")); } /// @dev Earrings N°4 => Ring function item_4() public pure returns (string memory) { return base(ring("000000")); } /// @dev Earrings N°5 => Circle Gold function item_5() public pure returns (string memory) { return base(circle("FFDD00")); } /// @dev Earrings N°6 => Ring Gold function item_6() public pure returns (string memory) { return base(ring("FFDD00")); } /// @dev Earrings N°7 => Heart function item_7() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M284.3,247.9c0.1,0.1,0.1,0.1,0.2,0.1s0.2,0,0.2-0.1l3.7-3.8c1.5-1.6,0.4-4.3-1.8-4.3c-1.3,0-1.9,1-2.2,1.2c-0.2-0.2-0.8-1.2-2.2-1.2c-2.2,0-3.3,2.7-1.8,4.3L284.3,247.9z"/>', '<path d="M135,246.6c0,0,0.1,0.1,0.2,0.1s0.1,0,0.2-0.1l3.1-3.1c1.3-1.3,0.4-3.6-1.5-3.6c-1.1,0-1.6,0.8-1.8,1c-0.2-0.2-0.7-1-1.8-1c-1.8,0-2.8,2.3-1.5,3.6L135,246.6z"/>' ) ) ); } /// @dev Earrings N°8 => Gold function item_8() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M298.7,228.1l-4.7-1.6c0,0-0.1,0-0.1-0.1v-0.1c2.8-2.7,7.1-17.2,7.2-17.4c0-0.1,0.1-0.1,0.1-0.1l0,0c5.3,1.1,5.6,2.2,5.7,2.4c-3.1,5.4-8,16.7-8.1,16.8C298.9,228,298.8,228.1,298.7,228.1C298.8,228.1,298.8,228.1,298.7,228.1z" style="fill: #fff700;stroke: #000;stroke-miterlimit: 10;stroke-width: 0.75px"/>' ) ) ); } /// @dev Earrings N°9 => Circle Diamond function item_9() public pure returns (string memory) { return base(circle("AAFFFD")); } /// @dev Earrings N°10 => Drop Heart function item_10() public pure returns (string memory) { return base( string( abi.encodePacked( drop(true), '<path fill="#F44336" d="M285.4,282.6c0.1,0.1,0.2,0.2,0.4,0.2s0.3-0.1,0.4-0.2l6.7-6.8c2.8-2.8,0.8-7.7-3.2-7.7c-2.4,0-3.5,1.8-3.9,2.1c-0.4-0.3-1.5-2.1-3.9-2.1c-4,0-6,4.9-3.2,7.7L285.4,282.6z"/>', drop(false), '<path fill="#F44336" d="M134.7,282.5c0.1,0.1,0.2,0.2,0.4,0.2s0.3-0.1,0.4-0.2l6.7-6.8c2.8-2.8,0.8-7.7-3.2-7.7c-2.4,0-3.5,1.8-3.9,2.1c-0.4-0.3-1.5-2.1-3.9-2.1c-4,0-6,4.9-3.2,7.7L134.7,282.5z"/>' ) ) ); } /// @dev Earrings N11 => Ether function item_11() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M285.7,242.7l-4.6-2.2l4.6,8l4.6-8L285.7,242.7z"/>', '<path d="M289.8,238.9l-4.1-7.1l-4.1,7.1l4.1-1.9L289.8,238.9z"/>', '<path d="M282,239.9l3.7,1.8l3.8-1.8l-3.8-1.8L282,239.9z"/>', '<path d="M134.5,241.8l-3.4-1.9l3.7,7.3l2.8-7.7L134.5,241.8z"/>', '<path d="M137.3,238l-3.3-6.5l-2.5,6.9l2.8-2L137.3,238z"/>', '<path d="M131.7,239.2l2.8,1.5l2.6-1.8l-2.8-1.5L131.7,239.2z"/>' ) ) ); } /// @dev Earrings N°12 => Drop Ether function item_12() public pure returns (string memory) { return base( string( abi.encodePacked( drop(true), '<path d="M285.7,279.7l-4.6-2.2l4.6,8l4.6-8L285.7,279.7z"/>', '<path d="M289.8,275.9l-4.1-7.1l-4.1,7.1l4.1-1.9L289.8,275.9z"/>', '<path d="M282,276.9l3.7,1.8l3.8-1.8l-3.8-1.8L282,276.9z"/><path d="M282,276.9l3.7,1.8l3.8-1.8l-3.8-1.8L282,276.9z"/>', drop(false), '<path d="M135.1,279.7l-4-2.2l4,8l4-8L135.1,279.7z"/>', '<path d="M138.7,275.9l-3.6-7.1l-3.6,7.1l3.6-1.9L138.7,275.9z"/>', '<path d="M131.8,276.9l3.3,1.8l3.3-1.8l-3.3-1.8L131.8,276.9z"/>' ) ) ); } /// @dev earring drop function drop(bool right) private pure returns (string memory) { return string( right ? abi.encodePacked( '<circle cx="285.7" cy="243.2" r="3.4"/>', '<line fill="none" stroke="#000000" stroke-miterlimit="10" x1="285.7" y1="243.2" x2="285.7" y2="270.2"/>' ) : abi.encodePacked( '<ellipse cx="135.1" cy="243.2" rx="3" ry="3.4"/>', '<line fill="none" stroke="#000000" stroke-miterlimit="10" x1="135.1" y1="243.2" x2="135.1" y2="270.2"/>' ) ); } /// @dev Generate circle SVG with the given color function circle(string memory color) private pure returns (string memory) { return string( abi.encodePacked( '<ellipse fill="#', color, '" stroke="#000000" cx="135.1" cy="243.2" rx="3" ry="3.4"/>', '<ellipse fill="#', color, '" stroke="#000000" cx="286.1" cy="243.2" rx="3.3" ry="3.4"/>' ) ); } /// @dev Generate ring SVG with the given color function ring(string memory color) private pure returns (string memory) { return string( abi.encodePacked( '<path fill="none" stroke="#', color, '" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M283.5,246c0,0-4.2,2-3.1,6.1c1,4.1,5.1,3.6,5.4,3.5s3.1-0.9,3-5"/>', '<path fill="none" stroke="#', color, '" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M134.3,244.7c0,0-4.2,2-3.1,6.1c1,4.1,5.1,3.6,5.4,3.5c0.3-0.1,3.1-0.9,3-5"/>' ) ); } /// @notice Return the earring name of the given id /// @param id The earring Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic"; } else if (id == 2) { name = "Circle"; } else if (id == 3) { name = "Circle Silver"; } else if (id == 4) { name = "Ring"; } else if (id == 5) { name = "Circle Gold"; } else if (id == 6) { name = "Ring Gold"; } else if (id == 7) { name = "Heart"; } else if (id == 8) { name = "Gold"; } else if (id == 9) { name = "Circle Diamond"; } else if (id == 10) { name = "Drop Heart"; } else if (id == 11) { name = "Ether"; } else if (id == 12) { name = "Drop Ether"; } } /// @dev The base SVG for the earrings function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Earrings">', children, "</g>")); } } // SPDX-License-Identifier: MIT /// @title Base64 /// @author Brecht Devos - <[email protected]> /// @notice Provides a function for encoding some bytes in base64 library Base64 { string internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { dataPtr := add(dataPtr, 3) // read 3 bytes let input := mload(dataPtr) // write 4 characters mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F))))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } }
@dev Earrings N°12 => Drop Ether
function item_12() public pure returns (string memory) { return base( string( abi.encodePacked( drop(true), '<path d="M285.7,279.7l-4.6-2.2l4.6,8l4.6-8L285.7,279.7z"/>', '<path d="M289.8,275.9l-4.1-7.1l-4.1,7.1l4.1-1.9L289.8,275.9z"/>', '<path d="M282,276.9l3.7,1.8l3.8-1.8l-3.8-1.8L282,276.9z"/><path d="M282,276.9l3.7,1.8l3.8-1.8l-3.8-1.8L282,276.9z"/>', drop(false), '<path d="M135.1,279.7l-4-2.2l4,8l4-8L135.1,279.7z"/>', '<path d="M138.7,275.9l-3.6-7.1l-3.6,7.1l3.6-1.9L138.7,275.9z"/>', '<path d="M131.8,276.9l3.3,1.8l3.3-1.8l-3.3-1.8L131.8,276.9z"/>' ) ) ); }
1,714,186
[ 1, 41, 5399, 899, 423, 131, 113, 2138, 516, 10895, 512, 1136, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 761, 67, 2138, 1435, 1071, 16618, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 203, 5411, 1026, 12, 203, 7734, 533, 12, 203, 10792, 24126, 18, 3015, 4420, 329, 12, 203, 13491, 3640, 12, 3767, 3631, 203, 13491, 2368, 803, 302, 1546, 49, 6030, 25, 18, 27, 16, 5324, 29, 18, 27, 80, 17, 24, 18, 26, 17, 22, 18, 22, 80, 24, 18, 26, 16, 28, 80, 24, 18, 26, 17, 28, 48, 6030, 25, 18, 27, 16, 5324, 29, 18, 27, 94, 6, 18280, 16, 203, 13491, 2368, 803, 302, 1546, 49, 6030, 29, 18, 28, 16, 5324, 25, 18, 29, 80, 17, 24, 18, 21, 17, 27, 18, 21, 80, 17, 24, 18, 21, 16, 27, 18, 21, 80, 24, 18, 21, 17, 21, 18, 29, 48, 6030, 29, 18, 28, 16, 5324, 25, 18, 29, 94, 6, 18280, 16, 203, 13491, 2368, 803, 302, 1546, 49, 6030, 22, 16, 5324, 26, 18, 29, 80, 23, 18, 27, 16, 21, 18, 28, 80, 23, 18, 28, 17, 21, 18, 28, 80, 17, 23, 18, 28, 17, 21, 18, 28, 48, 6030, 22, 16, 5324, 26, 18, 29, 94, 6, 19, 4438, 803, 302, 1546, 49, 6030, 22, 16, 5324, 26, 18, 29, 80, 23, 18, 27, 16, 21, 18, 28, 80, 23, 18, 28, 17, 21, 18, 28, 80, 17, 23, 18, 28, 17, 21, 18, 28, 48, 6030, 22, 16, 5324, 26, 18, 29, 94, 6, 18280, 16, 203, 13491, 3640, 12, 5743, 3631, 203, 13491, 2368, 2 ]
pragma solidity ^0.4.24; interface itoken { function freezeAccount(address _target, bool _freeze) external; function freezeAccountPartialy(address _target, uint256 _value) external; function balanceOf(address _owner) external view returns (uint256 balance); // function totalSupply() external view returns (uint256); // function transferOwnership(address newOwner) external; function allowance(address _owner, address _spender) external view returns (uint256); function initialCongress(address _congress) external; function mint(address _to, uint256 _amount) external returns (bool); function finishMinting() external returns (bool); function pause() external; function unpause() external; } library StringUtils { /// @dev Does a byte-by-byte lexicographical comparison of two strings. /// @return a negative number if `_a` is smaller, zero if they are equal /// and a positive numbe if `_b` is smaller. function compare(string _a, string _b) public pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; //@todo unroll the loop into increments of 32 and do full 32 byte comparisons for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } /// @dev Compares two strings and returns true iff they are equal. function equal(string _a, string _b) public pure returns (bool) { return compare(_a, _b) == 0; } /// @dev Finds the index of the first occurrence of _needle in _haystack function indexOf(string _haystack, string _needle) public pure returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) // since we have to be able to return -1 (if the char isn't found or input error), this function must return an "int" type with a max length of (2^128 - 1) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { // found the first char of b subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) {// search until the chars don't match or until we reach the end of a or b subindex++; } if(subindex == n.length) return int(i); } } return -1; } } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } contract DelayedClaimable is Claimable { uint256 public end; uint256 public start; /** * @dev Used to specify the time period during which a pending * owner can claim ownership. * @param _start The earliest time ownership can be claimed. * @param _end The latest time ownership can be claimed. */ function setLimits(uint256 _start, uint256 _end) onlyOwner public { require(_start <= _end); end = _end; start = _start; } /** * @dev Allows the pendingOwner address to finalize the transfer, as long as it is called within * the specified start and end time. */ function claimOwnership() onlyPendingOwner public { require((block.number <= end) && (block.number >= start)); emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); end = 0; } } contract RBAC { using Roles for Roles.Role; mapping (string => Roles.Role) private roles; event RoleAdded(address addr, string roleName); event RoleRemoved(address addr, string roleName); /** * @dev reverts if addr does not have role * @param addr address * @param roleName the name of the role * // reverts */ function checkRole(address addr, string roleName) view public { roles[roleName].check(addr); } /** * @dev determine if addr has role * @param addr address * @param roleName the name of the role * @return bool */ function hasRole(address addr, string roleName) view public returns (bool) { return roles[roleName].has(addr); } /** * @dev add a role to an address * @param addr address * @param roleName the name of the role */ function addRole(address addr, string roleName) internal { roles[roleName].add(addr); emit RoleAdded(addr, roleName); } /** * @dev remove a role from an address * @param addr address * @param roleName the name of the role */ function removeRole(address addr, string roleName) internal { roles[roleName].remove(addr); emit RoleRemoved(addr, roleName); } /** * @dev modifier to scope access to a single role (uses msg.sender as addr) * @param roleName the name of the role * // reverts */ modifier onlyRole(string roleName) { checkRole(msg.sender, roleName); _; } /** * @dev modifier to scope access to a set of roles (uses msg.sender as addr) * @param roleNames the names of the roles to scope access to * // reverts * * @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this * see: https://github.com/ethereum/solidity/issues/2467 */ // modifier onlyRoles(string[] roleNames) { // bool hasAnyRole = false; // for (uint8 i = 0; i < roleNames.length; i++) { // if (hasRole(msg.sender, roleNames[i])) { // hasAnyRole = true; // break; // } // } // require(hasAnyRole); // _; // } } contract MultiOwners is DelayedClaimable, RBAC { using SafeMath for uint256; using StringUtils for string; mapping (string => uint256) private authorizations; mapping (address => string) private ownerOfSides; // mapping (string => mapping (string => bool)) private voteResults; mapping (string => uint256) private sideExist; mapping (string => mapping (string => address[])) private sideVoters; address[] public owners; string[] private authTypes; // string[] private ownerSides; uint256 public multiOwnerSides; uint256 ownerSidesLimit = 5; // uint256 authRate = 75; bool initAdd = true; event OwnerAdded(address addr, string side); event OwnerRemoved(address addr); event InitialFinished(); string public constant ROLE_MULTIOWNER = "multiOwner"; string public constant AUTH_ADDOWNER = "addOwner"; string public constant AUTH_REMOVEOWNER = "removeOwner"; // string public constant AUTH_SETAUTHRATE = "setAuthRate"; /** * @dev Throws if called by any account that's not multiOwners. */ modifier onlyMultiOwners() { checkRole(msg.sender, ROLE_MULTIOWNER); _; } /** * @dev Throws if not in initializing stage. */ modifier canInitial() { require(initAdd); _; } /** * @dev the msg.sender will authorize a type of event. * @param _authType the event type need to be authorized */ function authorize(string _authType) onlyMultiOwners public { string memory side = ownerOfSides[msg.sender]; address[] storage voters = sideVoters[side][_authType]; if (voters.length == 0) { // if the first time to authorize this type of event authorizations[_authType] = authorizations[_authType].add(1); // voteResults[side][_authType] = true; } // add voters of one side uint j = 0; for (; j < voters.length; j = j.add(1)) { if (voters[j] == msg.sender) { break; } } if (j >= voters.length) { voters.push(msg.sender); } // add the authType for clearing auth uint i = 0; for (; i < authTypes.length; i = i.add(1)) { if (authTypes[i].equal(_authType)) { break; } } if (i >= authTypes.length) { authTypes.push(_authType); } } /** * @dev the msg.sender will clear the authorization he has given for the event. * @param _authType the event type need to be authorized */ function deAuthorize(string _authType) onlyMultiOwners public { string memory side = ownerOfSides[msg.sender]; address[] storage voters = sideVoters[side][_authType]; for (uint j = 0; j < voters.length; j = j.add(1)) { if (voters[j] == msg.sender) { delete voters[j]; break; } } // if the sender has authorized this type of event, will remove its vote if (j < voters.length) { for (uint jj = j; jj < voters.length.sub(1); jj = jj.add(1)) { voters[jj] = voters[jj.add(1)]; } delete voters[voters.length.sub(1)]; voters.length = voters.length.sub(1); // if there is no votes of one side, the authorization need to be decreased if (voters.length == 0) { authorizations[_authType] = authorizations[_authType].sub(1); // voteResults[side][_authType] = true; } // if there is no authorization on this type of event, // this event need to be removed from the list if (authorizations[_authType] == 0) { for (uint i = 0; i < authTypes.length; i = i.add(1)) { if (authTypes[i].equal(_authType)) { delete authTypes[i]; break; } } for (uint ii = i; ii < authTypes.length.sub(1); ii = ii.add(1)) { authTypes[ii] = authTypes[ii.add(1)]; } delete authTypes[authTypes.length.sub(1)]; authTypes.length = authTypes.length.sub(1); } } } /** * @dev judge if the event has already been authorized. * @param _authType the event type need to be authorized */ function hasAuth(string _authType) public view returns (bool) { require(multiOwnerSides > 1); // at least 2 sides have authorized // uint256 rate = authorizations[_authType].mul(100).div(multiOwnerNumber) return (authorizations[_authType] == multiOwnerSides); } /** * @dev clear all the authorizations that have been given for a type of event. * @param _authType the event type need to be authorized */ function clearAuth(string _authType) internal { authorizations[_authType] = 0; // clear authorizations for (uint i = 0; i < owners.length; i = i.add(1)) { string memory side = ownerOfSides[owners[i]]; address[] storage voters = sideVoters[side][_authType]; for (uint j = 0; j < voters.length; j = j.add(1)) { delete voters[j]; // clear votes of one side } voters.length = 0; } // clear this type of event for (uint k = 0; k < authTypes.length; k = k.add(1)) { if (authTypes[k].equal(_authType)) { delete authTypes[k]; break; } } for (uint kk = k; kk < authTypes.length.sub(1); kk = kk.add(1)) { authTypes[kk] = authTypes[kk.add(1)]; } delete authTypes[authTypes.length.sub(1)]; authTypes.length = authTypes.length.sub(1); } /** * @dev add an address as one of the multiOwners. * @param _addr the account address used as a multiOwner */ function addAddress(address _addr, string _side) internal { require(multiOwnerSides < ownerSidesLimit); require(_addr != address(0)); require(ownerOfSides[_addr].equal("")); // not allow duplicated adding // uint i = 0; // for (; i < owners.length; i = i.add(1)) { // if (owners[i] == _addr) { // break; // } // } // if (i >= owners.length) { owners.push(_addr); // for not allowing duplicated adding, so each addr should be new addRole(_addr, ROLE_MULTIOWNER); ownerOfSides[_addr] = _side; // } if (sideExist[_side] == 0) { multiOwnerSides = multiOwnerSides.add(1); } sideExist[_side] = sideExist[_side].add(1); } /** * @dev add an address to the whitelist * @param _addr address will be one of the multiOwner * @param _side the side name of the multiOwner * @return true if the address was added to the multiOwners list, * false if the address was already in the multiOwners list */ function initAddressAsMultiOwner(address _addr, string _side) onlyOwner canInitial public { // require(initAdd); addAddress(_addr, _side); // initAdd = false; emit OwnerAdded(_addr, _side); } /** * @dev Function to stop initial stage. */ function finishInitOwners() onlyOwner canInitial public { initAdd = false; emit InitialFinished(); } /** * @dev add an address to the whitelist * @param _addr address * @param _side the side name of the multiOwner * @return true if the address was added to the multiOwners list, * false if the address was already in the multiOwners list */ function addAddressAsMultiOwner(address _addr, string _side) onlyMultiOwners public { require(hasAuth(AUTH_ADDOWNER)); addAddress(_addr, _side); clearAuth(AUTH_ADDOWNER); emit OwnerAdded(_addr, _side); } /** * @dev getter to determine if address is in multiOwner list */ function isMultiOwner(address _addr) public view returns (bool) { return hasRole(_addr, ROLE_MULTIOWNER); } /** * @dev remove an address from the whitelist * @param _addr address * @return true if the address was removed from the multiOwner list, * false if the address wasn't in the multiOwner list */ function removeAddressFromOwners(address _addr) onlyMultiOwners public { require(hasAuth(AUTH_REMOVEOWNER)); removeRole(_addr, ROLE_MULTIOWNER); // first remove the owner uint j = 0; for (; j < owners.length; j = j.add(1)) { if (owners[j] == _addr) { delete owners[j]; break; } } if (j < owners.length) { for (uint jj = j; jj < owners.length.sub(1); jj = jj.add(1)) { owners[jj] = owners[jj.add(1)]; } delete owners[owners.length.sub(1)]; owners.length = owners.length.sub(1); } string memory side = ownerOfSides[_addr]; // if (sideExist[side] > 0) { sideExist[side] = sideExist[side].sub(1); if (sideExist[side] == 0) { require(multiOwnerSides > 2); // not allow only left 1 side multiOwnerSides = multiOwnerSides.sub(1); // this side has been removed } // for every event type, if this owner has voted the event, then need to remove for (uint i = 0; i < authTypes.length; ) { address[] storage voters = sideVoters[side][authTypes[i]]; for (uint m = 0; m < voters.length; m = m.add(1)) { if (voters[m] == _addr) { delete voters[m]; break; } } if (m < voters.length) { for (uint n = m; n < voters.length.sub(1); n = n.add(1)) { voters[n] = voters[n.add(1)]; } delete voters[voters.length.sub(1)]; voters.length = voters.length.sub(1); // if this side only have this 1 voter, the authorization of this event need to be decreased if (voters.length == 0) { authorizations[authTypes[i]] = authorizations[authTypes[i]].sub(1); } // if there is no authorization of this event, the event need to be removed if (authorizations[authTypes[i]] == 0) { delete authTypes[i]; for (uint kk = i; kk < authTypes.length.sub(1); kk = kk.add(1)) { authTypes[kk] = authTypes[kk.add(1)]; } delete authTypes[authTypes.length.sub(1)]; authTypes.length = authTypes.length.sub(1); } else { i = i.add(1); } } else { i = i.add(1); } } // } delete ownerOfSides[_addr]; clearAuth(AUTH_REMOVEOWNER); emit OwnerRemoved(_addr); } } contract MultiOwnerContract is MultiOwners { Claimable public ownedContract; address public pendingOwnedOwner; // address internal origOwner; string public constant AUTH_CHANGEOWNEDOWNER = "transferOwnerOfOwnedContract"; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ // modifier onlyPendingOwnedOwner() { // require(msg.sender == pendingOwnedOwner); // _; // } /** * @dev bind a contract as its owner * * @param _contract the contract address that will be binded by this Owner Contract */ function bindContract(address _contract) onlyOwner public returns (bool) { require(_contract != address(0)); ownedContract = Claimable(_contract); // origOwner = ownedContract.owner(); // take ownership of the owned contract ownedContract.claimOwnership(); return true; } /** * @dev change the owner of the contract from this contract address to the original one. * */ // function transferOwnershipBack() onlyOwner public { // ownedContract.transferOwnership(origOwner); // ownedContract = Claimable(address(0)); // origOwner = address(0); // } /** * @dev change the owner of the contract from this contract address to another one. * * @param _nextOwner the contract address that will be next Owner of the original Contract */ function changeOwnedOwnershipto(address _nextOwner) onlyMultiOwners public { require(ownedContract != address(0)); require(hasAuth(AUTH_CHANGEOWNEDOWNER)); if (ownedContract.owner() != pendingOwnedOwner) { ownedContract.transferOwnership(_nextOwner); pendingOwnedOwner = _nextOwner; // ownedContract = Claimable(address(0)); // origOwner = address(0); } else { // the pending owner has already taken the ownership ownedContract = Claimable(address(0)); pendingOwnedOwner = address(0); } clearAuth(AUTH_CHANGEOWNEDOWNER); } function ownedOwnershipTransferred() onlyOwner public returns (bool) { require(ownedContract != address(0)); if (ownedContract.owner() == pendingOwnedOwner) { // the pending owner has already taken the ownership ownedContract = Claimable(address(0)); pendingOwnedOwner = address(0); return true; } else { return false; } } } contract DRCTOwner is MultiOwnerContract { string public constant AUTH_INITCONGRESS = "initCongress"; string public constant AUTH_CANMINT = "canMint"; string public constant AUTH_SETMINTAMOUNT = "setMintAmount"; string public constant AUTH_FREEZEACCOUNT = "freezeAccount"; bool congressInit = false; // bool paramsInit = false; // iParams public params; uint256 onceMintAmount; // function initParams(address _params) onlyOwner public { // require(!paramsInit); // require(_params != address(0)); // params = _params; // paramsInit = false; // } /** * @dev Function to set mint token amount * @param _value The mint value. */ function setOnceMintAmount(uint256 _value) onlyMultiOwners public { require(hasAuth(AUTH_SETMINTAMOUNT)); require(_value > 0); onceMintAmount = _value; clearAuth(AUTH_SETMINTAMOUNT); } /** * @dev change the owner of the contract from this contract address to another one. * * @param _congress the contract address that will be next Owner of the original Contract */ function initCongress(address _congress) onlyMultiOwners public { require(hasAuth(AUTH_INITCONGRESS)); require(!congressInit); itoken tk = itoken(address(ownedContract)); tk.initialCongress(_congress); clearAuth(AUTH_INITCONGRESS); congressInit = true; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @return A boolean that indicates if the operation was successful. */ function mint(address _to) onlyMultiOwners public returns (bool) { require(hasAuth(AUTH_CANMINT)); itoken tk = itoken(address(ownedContract)); bool res = tk.mint(_to, onceMintAmount); clearAuth(AUTH_CANMINT); return res; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyMultiOwners public returns (bool) { require(hasAuth(AUTH_CANMINT)); itoken tk = itoken(address(ownedContract)); bool res = tk.finishMinting(); clearAuth(AUTH_CANMINT); return res; } /** * @dev freeze the account's balance under urgent situation * * by default all the accounts will not be frozen until set freeze value as true. * * @param _target address the account should be frozen * @param _freeze bool if true, the account will be frozen */ function freezeAccountDirect(address _target, bool _freeze) onlyMultiOwners public { require(hasAuth(AUTH_FREEZEACCOUNT)); require(_target != address(0)); itoken tk = itoken(address(ownedContract)); tk.freezeAccount(_target, _freeze); clearAuth(AUTH_FREEZEACCOUNT); } /** * @dev freeze the account's balance * * by default all the accounts will not be frozen until set freeze value as true. * * @param _target address the account should be frozen * @param _freeze bool if true, the account will be frozen */ function freezeAccount(address _target, bool _freeze) onlyOwner public { require(_target != address(0)); itoken tk = itoken(address(ownedContract)); if (_freeze) { require(tk.allowance(_target, this) == tk.balanceOf(_target)); } tk.freezeAccount(_target, _freeze); } /** * @dev freeze the account's balance * * @param _target address the account should be frozen * @param _value uint256 the amount of tokens that will be frozen */ function freezeAccountPartialy(address _target, uint256 _value) onlyOwner public { require(_target != address(0)); itoken tk = itoken(address(ownedContract)); require(tk.allowance(_target, this) == _value); tk.freezeAccountPartialy(_target, _value); } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner public { itoken tk = itoken(address(ownedContract)); tk.pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner public { itoken tk = itoken(address(ownedContract)); tk.unpause(); } } library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an address access to this role */ function add(Role storage role, address addr) internal { role.bearer[addr] = true; } /** * @dev remove an address' access to this role */ function remove(Role storage role, address addr) internal { role.bearer[addr] = false; } /** * @dev check if an address has this role * // reverts */ function check(Role storage role, address addr) view internal { require(has(role, addr)); } /** * @dev check if an address has this role * @return bool */ function has(Role storage role, address addr) view internal returns (bool) { return role.bearer[addr]; } }
* @dev add an address as one of the multiOwners. @param _addr the account address used as a multiOwner/ uint i = 0; for (; i < owners.length; i = i.add(1)) { if (owners[i] == _addr) { break; } } if (i >= owners.length) { }
function addAddress(address _addr, string _side) internal { require(multiOwnerSides < ownerSidesLimit); require(_addr != address(0)); addRole(_addr, ROLE_MULTIOWNER); ownerOfSides[_addr] = _side; if (sideExist[_side] == 0) { multiOwnerSides = multiOwnerSides.add(1); } sideExist[_side] = sideExist[_side].add(1); }
1,496,875
[ 1, 1289, 392, 1758, 487, 1245, 434, 326, 3309, 5460, 414, 18, 225, 389, 4793, 326, 2236, 1758, 1399, 487, 279, 3309, 5541, 19, 2254, 277, 273, 374, 31, 364, 261, 31, 277, 411, 25937, 18, 2469, 31, 277, 273, 277, 18, 1289, 12, 21, 3719, 288, 282, 309, 261, 995, 414, 63, 77, 65, 422, 389, 4793, 13, 288, 377, 898, 31, 282, 289, 289, 309, 261, 77, 1545, 25937, 18, 2469, 13, 288, 289, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 527, 1887, 12, 2867, 389, 4793, 16, 533, 389, 5564, 13, 2713, 288, 203, 565, 2583, 12, 7027, 5541, 55, 4369, 411, 3410, 55, 4369, 3039, 1769, 203, 565, 2583, 24899, 4793, 480, 1758, 12, 20, 10019, 203, 203, 203, 203, 565, 527, 2996, 24899, 4793, 16, 22005, 67, 12845, 4294, 22527, 1769, 203, 565, 3410, 951, 55, 4369, 63, 67, 4793, 65, 273, 389, 5564, 31, 203, 203, 565, 309, 261, 5564, 4786, 63, 67, 5564, 65, 422, 374, 13, 288, 203, 1377, 3309, 5541, 55, 4369, 273, 3309, 5541, 55, 4369, 18, 1289, 12, 21, 1769, 203, 565, 289, 203, 203, 565, 4889, 4786, 63, 67, 5564, 65, 273, 4889, 4786, 63, 67, 5564, 8009, 1289, 12, 21, 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 ]
./full_match/42/0x239f2647cC2f72bB8Ac3AEb70DDF73Ca2dCA09B3/sources/browser/AugurETHFoundry.sol
*@dev unwraps multiple tokens */
function unWrapMultipleTokens( uint256[] memory _tokenIds, uint256[] memory _amounts ) public { for (uint256 i = 0; i < _tokenIds.length; i++) { unWrapTokens(_tokenIds[i], _amounts[i]); } }
16,225,142
[ 1, 318, 91, 7506, 3229, 2430, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 640, 2964, 8438, 5157, 12, 203, 3639, 2254, 5034, 8526, 3778, 389, 2316, 2673, 16, 203, 3639, 2254, 5034, 8526, 3778, 389, 8949, 87, 203, 565, 262, 1071, 288, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 2316, 2673, 18, 2469, 31, 277, 27245, 288, 203, 5411, 640, 2964, 5157, 24899, 2316, 2673, 63, 77, 6487, 389, 8949, 87, 63, 77, 19226, 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 ]
pragma solidity ^0.5.1; //byte operat lib library ByteUtilLib { bytes constant ZERO_BYTES = hex"80"; function equal(bytes memory one, bytes memory two) internal pure returns (bool) { if (!(one.length == two.length)) { return false; } for (uint i=0; i<one.length; i++) { if (!(one[i] == two[i])) { return false; } } return true; } function bytesToBytes32(bytes memory b) internal pure returns (bytes32) { return bytesToBytes32(b, 0); } function bytesToBytes32(bytes memory b, uint offset) internal pure returns (bytes32) { bytes32 out; for (uint i = 0; i < 32; i++) { out |= bytes32(b[offset + i] & 0xFF) >> (i * 8); } return out; } function bytes32ToBytes(bytes32 data) internal pure returns (bytes memory) { bytes memory bs = new bytes(32); for (uint256 i; i < 32; i++) { bs[i] = data[i]; } return bs; } /** * @dev RLP encodes a string. * @param self The string to encode. * @return The RLP encoded string in bytes. */ function string2byte(string memory self) internal pure returns (bytes memory encoded) { return bytes(self); } function address2hash(address addr) internal pure returns (bytes32 hash) { return keccak256(address2byte(addr)); } function pubkey2Address(bytes memory publicKey) internal pure returns(address addr){ return address(uint(keccak256(publicKey)) & 0x000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); } /** * @dev RLP encodes an address. * @param self The address to encode. * @return The RLP encoded address in bytes. */ function address2byte(address self) internal pure returns (bytes memory encoded) { assembly { let m := mload(0x40) mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, self)) mstore(0x40, add(m, 52)) encoded := m } } function bytesToAddress(bytes memory b) internal pure returns (address) { uint result = 0; for (uint i=0; i<b.length;i++) { uint8 c = uint8(b[i]); if (c >= 48 && c <= 57) { result = result * 16 + (c - 48); } if(c >= 65 && c<= 90) { result = result * 16 + (c - 55); } if(c >= 97 && c<= 122) { result = result * 16 + (c - 87); } } return address(result); } /** * @dev RLP encodes a uint. * @param self The uint to encode. * @return The RLP encoded uint in bytes. */ function uint2byte(uint self) internal pure returns (bytes memory encoded) { return toBinary(self); } function appendUintToString(string memory inStr, uint v) internal pure returns (string memory str) { uint maxlength = 100; bytes memory reversed = new bytes(maxlength); uint i = 0; while (v != 0) { uint remainder = v % 10; v = v / 10; reversed[i++] = byte(uint8(48 + remainder)); } bytes memory inStrb = bytes(inStr); bytes memory s = new bytes(inStrb.length + i); uint j; for (j = 0; j < inStrb.length; j++) { s[j] = inStrb[j]; } for (j = 0; j < i; j++) { s[j + inStrb.length] = reversed[i - 1 - j]; } str = string(s); } /** * @dev RLP encodes an int. * @param self The int to encode. * @return The RLP encoded int in bytes. */ function int2byte(int self) internal pure returns (bytes memory encoded) { return toBinary(uint(self)); } function bool2byte(bool self) internal pure returns (bytes memory data) { data = new bytes(1); //TODO ensure false should use 0x80 or 0x0 data[0] = (self ? bytes1(0x01) : bytes1(0x00)); return data; } /** * @dev Encode integer in big endian binary form with no leading zeroes. * @notice TODO: This should be optimized with assembly to save gas costs. * @param _x The integer to encode. * @return RLP encoded bytes. */ function toBinary(uint _x) private pure returns (bytes memory encoded) { if(_x == 0){ return ZERO_BYTES; } bytes memory b = new bytes(32); assembly { mstore(add(b, 32), _x) } uint i = 0; for (; i < 32; i++) { if (b[i] != 0) { break; } } bytes memory res = new bytes(32 - i); for (uint j = 0; j < res.length; j++) { res[j] = b[i++]; } return res; } /** * @dev Copies a piece of memory to another location. * @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol. * @param _dest Destination location. * @param _src Source location. * @param _len Length of memory to copy. */ function memcpy(uint _dest, uint _src, uint _len) internal pure { uint dest = _dest; uint src = _src; uint len = _len; for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } function append(bytes memory first, bytes memory second) internal pure returns (bytes memory appended) { appended = new bytes(first.length + second.length); uint flattenedPtr; assembly { flattenedPtr := add(appended, 0x20) } uint firstPtr; assembly { firstPtr := add(first, 0x20)} memcpy(flattenedPtr, firstPtr, first.length); flattenedPtr += first.length; uint secondPtr; assembly { secondPtr := add(second, 0x20)} memcpy(flattenedPtr, secondPtr, second.length); flattenedPtr += second.length; return appended; } // Assumes that enough memory has been allocated to store in target. function _copyToBytes(uint btsPtr, uint len) internal pure returns(bytes memory) { // Exploiting the fact that 'tgt' was the last thing to be allocated, // we can write entire words, and just overwrite any excess. bytes memory tgt = new bytes(len); uint i = 0; uint words; uint rOffset; uint wOffset; assembly { words := div(add(len, 31), 32) rOffset := btsPtr wOffset := add(tgt, 0x20) } for(;i<words;i++) { assembly { let offset := mul(i, 0x20) mstore(add(wOffset, offset), mload(add(rOffset, offset))) } } assembly { mstore(add(tgt, add(0x20, mload(tgt))), 0) } return tgt; } } //public function library RLPLib { uint constant DATA_SHORT_START = 0x80; uint constant DATA_LONG_START = 0xB8; struct RLPItem { uint _unsafe_memPtr; // Pointer to the RLP-encoded bytes. uint _unsafe_length; // Number of bytes. This is the full length of the string. } struct Iterator { RLPItem _unsafe_item; // Item that's being iterated over. uint _unsafe_nextPtr; // Position of the next item in the list. } /// @dev Check if the RLP item is data. /// @param self The RLP item. /// @return 'true' if the item is data. function isData(RLPLib.RLPItem memory self) internal pure returns (bool ret) { if (self._unsafe_length == 0) return false; uint memPtr = self._unsafe_memPtr; assembly { ret := lt(byte(0, mload(memPtr)), 0xC0) } } // Get start position and length of the data. function _decode(RLPLib.RLPItem memory self) internal pure returns (uint memPtr, uint len) { if(!isData(self)) revert(); uint b0; uint start = self._unsafe_memPtr; assembly { b0 := byte(0, mload(start)) } if (b0 < DATA_SHORT_START) { memPtr = start; len = 1; return (memPtr, len); } if (b0 < DATA_LONG_START) { len = self._unsafe_length - 1; memPtr = start + 1; } else { uint bLen; assembly { bLen := sub(b0, 0xB7) // DATA_LONG_OFFSET } len = self._unsafe_length - 1 - bLen; memPtr = start + bLen + 1; } return (memPtr, len); } /// @dev Decode an RLPItem into bytes. This will not work if the /// RLPItem is a list. /// @param self The RLPItem. /// @return The decoded string. function toData(RLPLib.RLPItem memory self) internal pure returns (bytes memory bts) { if(!isData(self)) revert(); uint rStartPos; uint len; (rStartPos, len) = _decode(self); bts = ByteUtilLib._copyToBytes(rStartPos, len); } } library Base58Util { bytes constant ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; function base58String2Bytes(string memory base58String) internal pure returns (bytes memory) { bytes memory content = bytes(base58String); return toBase58(content, content.length); } function bytes32ToBase58(bytes32 data) internal pure returns(string memory) { bytes memory tmp = ByteUtilLib.bytes32ToBytes(data); return toString(toBase58(tmp, 32)); } function toString(bytes memory bts) private pure returns(string memory) { return string(bts); } function toBase58(bytes memory source, uint len) private pure returns (bytes memory) { if (source.length == 0) return new bytes(0); uint8[] memory digits = new uint8[](len * 2); digits[0] = 0; uint8 digitlength = 1; for (uint i=0; i<source.length; ++i) { uint carry = uint8(source[i]); for (uint j=0; j<digitlength; ++j) { carry += uint(digits[j]) * 256; digits[j] = uint8(carry % 58); carry = carry / 58; } while (carry > 0) { digits[digitlength] = uint8(carry % 58); digitlength++; carry = carry / 58; } } return toAlphabet(reverse(truncate(digits, digitlength))); } function truncate(uint8[] memory array, uint8 length) private pure returns (uint8[] memory) { uint8[] memory output = new uint8[](length); for (uint i=0; i<length; i++) { output[i] = array[i]; } return output; } function reverse(uint8[] memory input) private pure returns (uint8[] memory) { uint8[] memory output = new uint8[](input.length); for (uint i=0; i<input.length; i++) { output[i] = input[input.length-1-i]; } return output; } function toAlphabet(uint8[] memory indices) private pure returns (bytes memory) { bytes memory output = new bytes(indices.length); for (uint i=0; i<indices.length; i++) { output[i] = ALPHABET[indices[i]]; } return output; } function concat(bytes memory byteArray, bytes memory byteArray2) private pure returns (bytes memory) { bytes memory returnArray = new bytes(byteArray.length + byteArray2.length); uint16 i = 0; for (; i < byteArray.length; i++) { returnArray[i] = byteArray[i]; } for (i; i < (byteArray.length + byteArray2.length); i++) { returnArray[i] = byteArray2[i - byteArray.length]; } return returnArray; } }
* @dev Copies a piece of memory to another location. @param _dest Destination location. @param _src Source location. @param _len Length of memory to copy./
function memcpy(uint _dest, uint _src, uint _len) internal pure { uint dest = _dest; uint src = _src; uint len = _len; for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } }
7,295,282
[ 1, 15670, 279, 11151, 434, 3778, 358, 4042, 2117, 18, 225, 389, 10488, 10691, 2117, 18, 225, 389, 4816, 4998, 2117, 18, 225, 389, 1897, 11311, 434, 3778, 358, 1610, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1663, 71, 2074, 12, 11890, 389, 10488, 16, 2254, 389, 4816, 16, 2254, 389, 1897, 13, 2713, 16618, 288, 203, 3639, 2254, 1570, 273, 389, 10488, 31, 203, 3639, 2254, 1705, 273, 389, 4816, 31, 203, 3639, 2254, 562, 273, 389, 1897, 31, 203, 203, 3639, 364, 12, 31, 562, 1545, 3847, 31, 562, 3947, 3847, 13, 288, 203, 5411, 19931, 288, 203, 7734, 312, 2233, 12, 10488, 16, 312, 945, 12, 4816, 3719, 203, 5411, 289, 203, 5411, 1570, 1011, 3847, 31, 203, 5411, 1705, 1011, 3847, 31, 203, 3639, 289, 203, 203, 3639, 2254, 3066, 273, 8303, 2826, 261, 1578, 300, 562, 13, 300, 404, 31, 203, 3639, 19931, 288, 203, 5411, 2231, 1705, 2680, 519, 471, 12, 81, 945, 12, 4816, 3631, 486, 12, 4455, 3719, 203, 5411, 2231, 1570, 2680, 519, 471, 12, 81, 945, 12, 10488, 3631, 3066, 13, 203, 5411, 312, 2233, 12, 10488, 16, 578, 12, 10488, 2680, 16, 1705, 2680, 3719, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.8; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@animoca/ethereum-contracts-erc20_base/contracts/token/ERC20/IERC20.sol"; import "@animoca/ethereum-contracts-erc20_base/contracts/token/ERC20/IERC20Detailed.sol"; import "./interfaces/IKyberNetworkProxy.sol"; /** * @title KyberAdapter * Contract module that invokes the Kyber Proxy Network contract in order to * provide utility functions for performing Kyber token swaps. */ contract KyberAdapter { using SafeMath for uint256; IKyberNetworkProxy public kyber; // solhint-disable-next-line var-name-mixedcase IERC20 public KYBER_ETH_ADDRESS = IERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee); constructor(address _kyberProxy) public { kyber = IKyberNetworkProxy(_kyberProxy); } fallback() external payable {} receive() external payable {} function _getTokenDecimals(IERC20 _token) internal view returns (uint8 _decimals) { return _token != KYBER_ETH_ADDRESS ? IERC20Detailed(address(_token)).decimals() : 18; } function _getTokenBalance(IERC20 _token, address _account) internal view returns (uint256 _balance) { return _token != KYBER_ETH_ADDRESS ? _token.balanceOf(_account) : _account.balance; } function _ceilingDiv(uint256 a, uint256 b) internal pure returns (uint256 c) { return a.div(b).add(a.mod(b) > 0 ? 1 : 0); } function _fixTokenDecimals( IERC20 _src, IERC20 _dest, uint256 _unfixedDestAmount, bool _ceiling ) internal view returns (uint256 _destTokenAmount) { uint256 _unfixedDecimals = _getTokenDecimals(_src) + 18; // Kyber by default returns rates with 18 decimals. uint256 _decimals = _getTokenDecimals(_dest); if (_unfixedDecimals > _decimals) { // Divide token amount by 10^(_unfixedDecimals - _decimals) to reduce decimals. if (_ceiling) { return _ceilingDiv(_unfixedDestAmount, (10**(_unfixedDecimals - _decimals))); } else { return _unfixedDestAmount.div(10**(_unfixedDecimals - _decimals)); } } else { // Multiply token amount with 10^(_decimals - _unfixedDecimals) to increase decimals. return _unfixedDestAmount.mul(10**(_decimals - _unfixedDecimals)); } } function _convertToken( IERC20 _src, uint256 _srcAmount, IERC20 _dest ) internal view returns (uint256 _expectedAmount, uint256 _slippageAmount) { (uint256 _expectedRate, uint256 _slippageRate) = kyber.getExpectedRate(_src, _dest, _srcAmount); return ( _fixTokenDecimals(_src, _dest, _srcAmount.mul(_expectedRate), false), _fixTokenDecimals(_src, _dest, _srcAmount.mul(_slippageRate), false) ); } function _swapTokenAndHandleChange( IERC20 _src, uint256 _maxSrcAmount, IERC20 _dest, uint256 _maxDestAmount, uint256 _minConversionRate, address payable _initiator, address payable _receiver ) internal returns (uint256 _srcAmount, uint256 _destAmount) { if (_src == _dest) { // payment is made with DAI // solhint-disable-next-line reason-string require(_maxSrcAmount >= _maxDestAmount, "KyberAdapter: insufficient source token amount"); _destAmount = _srcAmount = _maxDestAmount; // solhint-disable-next-line reason-string require( _src.transferFrom(_initiator, address(this), _destAmount), "KyberAdapter: failure in transferring ERC20 destination token amount" ); } else { if (_src == KYBER_ETH_ADDRESS) { // solhint-disable-next-line reason-string require(msg.value >= _maxSrcAmount, "KyberAdapter: insufficient ETH value"); } else { // solhint-disable-next-line reason-string require(msg.value == 0, "KyberAdapter: unexpected ETH value"); } // Prepare for handling back the change if there is any. uint256 _balanceBefore = _getTokenBalance(_src, address(this)); if (_src != KYBER_ETH_ADDRESS) { // solhint-disable-next-line reason-string require(_src.transferFrom(_initiator, address(this), _maxSrcAmount), "KyberAdapter: failure in transferring source token amount"); // solhint-disable-next-line reason-string require(_src.approve(address(kyber), _maxSrcAmount), "KyberAdapter: failure in approving source token transfers"); } else { // Since we are going to transfer the source amount to Kyber. _balanceBefore = _balanceBefore.sub(_maxSrcAmount); } _destAmount = kyber.trade{value: _src == KYBER_ETH_ADDRESS ? _maxSrcAmount : 0}( _src, _maxSrcAmount, _dest, _receiver, _maxDestAmount, _minConversionRate, address(0) ); uint256 _balanceAfter = _getTokenBalance(_src, address(this)); _srcAmount = _maxSrcAmount; // Handle back the change, if there is any, to the message sender. if (_balanceAfter > _balanceBefore) { uint256 _change = _balanceAfter - _balanceBefore; _srcAmount = _srcAmount.sub(_change); if (_src != KYBER_ETH_ADDRESS) { // solhint-disable-next-line reason-string require(_src.transfer(_initiator, _change), "KyberAdapter: failure in returning source token amount remainder"); } else { _initiator.transfer(_change); } } } } }
Prepare for handling back the change if there is any.
uint256 _balanceBefore = _getTokenBalance(_src, address(this));
12,698,755
[ 1, 7543, 364, 5057, 1473, 326, 2549, 309, 1915, 353, 1281, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 2254, 5034, 389, 12296, 4649, 273, 389, 588, 1345, 13937, 24899, 4816, 16, 1758, 12, 2211, 10019, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../global/StorageLayoutV1.sol"; import "../global/Constants.sol"; import "../proxy/utils/UUPSUpgradeable.sol"; import "interfaces/notional/NotionalProxy.sol"; /** * Read only version of the Router that can only be upgraded by governance. Used in emergency when the system must * be paused for some reason. */ contract PauseRouter is StorageLayoutV1, UUPSUpgradeable { address public immutable VIEWS; address public immutable LIQUIDATE_CURRENCY; address public immutable LIQUIDATE_FCASH; constructor( address views_, address liquidateCurrency_, address liquidatefCash_ ) { VIEWS = views_; LIQUIDATE_CURRENCY = liquidateCurrency_; LIQUIDATE_FCASH = liquidatefCash_; } /// @dev Internal method will be called during an UUPS upgrade, must return true to /// authorize the upgrade. The UUPS check does a rollback check during the upgrade and /// therefore we use the `rollbackRouterImplementation` to authorize the pauseGuardian /// during this check. See GovernanceAction._authorizeUpgrade for where the rollbackRouterImplementation /// storage slot is set. function _authorizeUpgrade(address newImplementation) internal override { // This is only true during a rollback check when the pause router is downgraded bool isRollbackCheck = rollbackRouterImplementation != address(0) && newImplementation == rollbackRouterImplementation; require( owner == msg.sender || (msg.sender == pauseGuardian && isRollbackCheck), "Unauthorized upgrade" ); // Clear this storage slot so the guardian cannot upgrade back to the previous router, // requires governance to do so. rollbackRouterImplementation = address(0); } /// @notice Shows the current state of which liquidations are enabled /// @return the current liquidation enable state as a bitmap function getLiquidationEnabledState() external view returns (bytes1) { return liquidationEnabledState; } /// @notice Sets a new liquidation enable state, only the owner or the guardian may do so function setLiquidationEnabledState(bytes1 liquidationEnabledState_) external { // Only authorized addresses can set the liquidation state require(owner == msg.sender || msg.sender == pauseGuardian); liquidationEnabledState = liquidationEnabledState_; } function isEnabled(bytes1 state) private view returns (bool) { return (liquidationEnabledState & state == state); } function getRouterImplementation(bytes4 sig) public view returns (address) { // Liquidation calculation methods are stateful (they settle accounts if required) // and therefore we prevent them from being called unless specifically authorized. if ( (sig == NotionalProxy.calculateCollateralCurrencyLiquidation.selector || sig == NotionalProxy.liquidateCollateralCurrency.selector) && isEnabled(Constants.COLLATERAL_CURRENCY_ENABLED) ) { return LIQUIDATE_CURRENCY; } if ( (sig == NotionalProxy.calculateLocalCurrencyLiquidation.selector || sig == NotionalProxy.liquidateLocalCurrency.selector) && isEnabled(Constants.LOCAL_CURRENCY_ENABLED) ) { return LIQUIDATE_CURRENCY; } if ( (sig == NotionalProxy.liquidatefCashLocal.selector || sig == NotionalProxy.calculatefCashLocalLiquidation.selector) && isEnabled(Constants.LOCAL_FCASH_ENABLED) ) { return LIQUIDATE_FCASH; } if ( (sig == NotionalProxy.liquidatefCashCrossCurrency.selector || sig == NotionalProxy.calculatefCashCrossCurrencyLiquidation.selector) && isEnabled(Constants.CROSS_CURRENCY_FCASH_ENABLED) ) { return LIQUIDATE_FCASH; } // If not found then delegate to views. This will revert if there is no method on // the view contract return VIEWS; } /// @dev Delegates the current call to `implementation`. /// This function does not return to its internal call site, it will return directly to the external caller. function _delegate(address implementation) private { // 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()) } } } fallback() external payable { _delegate(getRouterImplementation(msg.sig)); } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "./Types.sol"; /** * @notice Storage layout for the system. Do not change this file once deployed, future storage * layouts must inherit this and increment the version number. */ contract StorageLayoutV1 { // The current maximum currency id uint16 internal maxCurrencyId; // Sets the state of liquidations being enabled during a paused state. Each of the four lower // bits can be turned on to represent one of the liquidation types being enabled. bytes1 internal liquidationEnabledState; // Set to true once the system has been initialized bool internal hasInitialized; /* Authentication Mappings */ // This is set to the timelock contract to execute governance functions address public owner; // This is set to an address of a router that can only call governance actions address public pauseRouter; // This is set to an address of a router that can only call governance actions address public pauseGuardian; // On upgrades this is set in the case that the pause router is used to pass the rollback check address internal rollbackRouterImplementation; // A blanket allowance for a spender to transfer any of an account's nTokens. This would allow a user // to set an allowance on all nTokens for a particular integrating contract system. // owner => spender => transferAllowance mapping(address => mapping(address => uint256)) internal nTokenWhitelist; // Individual transfer allowances for nTokens used for ERC20 // owner => spender => currencyId => transferAllowance mapping(address => mapping(address => mapping(uint16 => uint256))) internal nTokenAllowance; // Transfer operators // Mapping from a global ERC1155 transfer operator contract to an approval value for it mapping(address => bool) internal globalTransferOperator; // Mapping from an account => operator => approval status for that operator. This is a specific // approval between two addresses for ERC1155 transfers. mapping(address => mapping(address => bool)) internal accountAuthorizedTransferOperator; // Approval for a specific contract to use the `batchBalanceAndTradeActionWithCallback` method in // BatchAction.sol, can only be set by governance mapping(address => bool) internal authorizedCallbackContract; // Reverse mapping from token addresses to currency ids, only used for referencing in views // and checking for duplicate token listings. mapping(address => uint16) internal tokenAddressToCurrencyId; // Reentrancy guard uint256 internal reentrancyStatus; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; /// @title All shared constants for the Notional system should be declared here. library Constants { // Return code for cTokens that represents no error uint256 internal constant COMPOUND_RETURN_CODE_NO_ERROR = 0; uint8 internal constant CETH_DECIMAL_PLACES = 8; // Token precision used for all internal balances, TokenHandler library ensures that we // limit the dust amount caused by precision mismatches int256 internal constant INTERNAL_TOKEN_PRECISION = 1e8; // ETH will be initialized as the first currency uint256 internal constant ETH_CURRENCY_ID = 1; uint8 internal constant ETH_DECIMAL_PLACES = 18; int256 internal constant ETH_DECIMALS = 1e18; // Used to prevent overflow when converting decimal places to decimal precision values via // 10**decimalPlaces. This is a safe value for int256 and uint256 variables. We apply this // constraint when storing decimal places in governance. uint256 internal constant MAX_DECIMAL_PLACES = 36; // Address of the reserve account address internal constant RESERVE = address(0); // NOTE: this address is hardcoded in the library, must update this on deployment address constant NOTE_TOKEN_ADDRESS = 0xCFEAead4947f0705A14ec42aC3D44129E1Ef3eD5; // Most significant bit bytes32 internal constant MSB = 0x8000000000000000000000000000000000000000000000000000000000000000; // Basis for percentages int256 internal constant PERCENTAGE_DECIMALS = 100; // Max number of traded markets, also used as the maximum number of assets in a portfolio array uint256 internal constant MAX_TRADED_MARKET_INDEX = 7; // Max number of fCash assets in a bitmap, this is based on the gas costs of calculating free collateral // for a bitmap portfolio uint256 internal constant MAX_BITMAP_ASSETS = 20; uint256 internal constant FIVE_MINUTES = 300; // Internal date representations, note we use a 6/30/360 week/month/year convention here uint256 internal constant DAY = 86400; // We use six day weeks to ensure that all time references divide evenly uint256 internal constant WEEK = DAY * 6; uint256 internal constant MONTH = WEEK * 5; uint256 internal constant QUARTER = MONTH * 3; uint256 internal constant YEAR = QUARTER * 4; // These constants are used in DateTime.sol uint256 internal constant DAYS_IN_WEEK = 6; uint256 internal constant DAYS_IN_MONTH = 30; uint256 internal constant DAYS_IN_QUARTER = 90; // Offsets for each time chunk denominated in days uint256 internal constant MAX_DAY_OFFSET = 90; uint256 internal constant MAX_WEEK_OFFSET = 360; uint256 internal constant MAX_MONTH_OFFSET = 2160; uint256 internal constant MAX_QUARTER_OFFSET = 7650; // Offsets for each time chunk denominated in bits uint256 internal constant WEEK_BIT_OFFSET = 90; uint256 internal constant MONTH_BIT_OFFSET = 135; uint256 internal constant QUARTER_BIT_OFFSET = 195; // This is a constant that represents the time period that all rates are normalized by, 360 days uint256 internal constant IMPLIED_RATE_TIME = 360 * DAY; // Number of decimal places that rates are stored in, equals 100% int256 internal constant RATE_PRECISION = 1e9; // One basis point in RATE_PRECISION terms uint256 internal constant BASIS_POINT = uint256(RATE_PRECISION / 10000); // Used to when calculating the amount to deleverage of a market when minting nTokens uint256 internal constant DELEVERAGE_BUFFER = 300 * BASIS_POINT; // Used for scaling cash group factors uint256 internal constant FIVE_BASIS_POINTS = 5 * BASIS_POINT; // Used for residual purchase incentive and cash withholding buffer uint256 internal constant TEN_BASIS_POINTS = 10 * BASIS_POINT; // This is the ABDK64x64 representation of RATE_PRECISION // RATE_PRECISION_64x64 = ABDKMath64x64.fromUint(RATE_PRECISION) int128 internal constant RATE_PRECISION_64x64 = 0x3b9aca000000000000000000; int128 internal constant LOG_RATE_PRECISION_64x64 = 382276781265598821176; // Limit the market proportion so that borrowing cannot hit extremely high interest rates int256 internal constant MAX_MARKET_PROPORTION = RATE_PRECISION * 96 / 100; uint8 internal constant FCASH_ASSET_TYPE = 1; // Liquidity token asset types are 1 + marketIndex (where marketIndex is 1-indexed) uint8 internal constant MIN_LIQUIDITY_TOKEN_INDEX = 2; uint8 internal constant MAX_LIQUIDITY_TOKEN_INDEX = 8; // Used for converting bool to bytes1, solidity does not have a native conversion // method for this bytes1 internal constant BOOL_FALSE = 0x00; bytes1 internal constant BOOL_TRUE = 0x01; // Account context flags bytes1 internal constant HAS_ASSET_DEBT = 0x01; bytes1 internal constant HAS_CASH_DEBT = 0x02; bytes2 internal constant ACTIVE_IN_PORTFOLIO = 0x8000; bytes2 internal constant ACTIVE_IN_BALANCES = 0x4000; bytes2 internal constant UNMASK_FLAGS = 0x3FFF; uint16 internal constant MAX_CURRENCIES = uint16(UNMASK_FLAGS); // Equal to 100% of all deposit amounts for nToken liquidity across fCash markets. int256 internal constant DEPOSIT_PERCENT_BASIS = 1e8; // nToken Parameters: there are offsets in the nTokenParameters bytes6 variable returned // in nTokenHandler. Each constant represents a position in the byte array. uint8 internal constant LIQUIDATION_HAIRCUT_PERCENTAGE = 0; uint8 internal constant CASH_WITHHOLDING_BUFFER = 1; uint8 internal constant RESIDUAL_PURCHASE_TIME_BUFFER = 2; uint8 internal constant PV_HAIRCUT_PERCENTAGE = 3; uint8 internal constant RESIDUAL_PURCHASE_INCENTIVE = 4; // Liquidation parameters // Default percentage of collateral that a liquidator is allowed to liquidate, will be higher if the account // requires more collateral to be liquidated int256 internal constant DEFAULT_LIQUIDATION_PORTION = 40; // Percentage of local liquidity token cash claim delivered to the liquidator for liquidating liquidity tokens int256 internal constant TOKEN_REPO_INCENTIVE_PERCENT = 30; // Pause Router liquidation enabled states bytes1 internal constant LOCAL_CURRENCY_ENABLED = 0x01; bytes1 internal constant COLLATERAL_CURRENCY_ENABLED = 0x02; bytes1 internal constant LOCAL_FCASH_ENABLED = 0x04; bytes1 internal constant CROSS_CURRENCY_FCASH_ENABLED = 0x08; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../ERC1967/ERC1967Upgrade.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is ERC1967Upgrade { /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, bytes(""), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../contracts/global/Types.sol"; import "./nTokenERC20.sol"; import "./nERC1155Interface.sol"; import "./NotionalGovernance.sol"; import "./NotionalViews.sol"; interface NotionalProxy is nTokenERC20, nERC1155Interface, NotionalGovernance, NotionalViews { /** User trading events */ event CashBalanceChange(address indexed account, uint16 indexed currencyId, int256 netCashChange); event nTokenSupplyChange(address indexed account, uint16 indexed currencyId, int256 tokenSupplyChange); event MarketsInitialized(uint16 currencyId); event SweepCashIntoMarkets(uint16 currencyId, int256 cashIntoMarkets); event SettledCashDebt( address indexed settledAccount, uint16 indexed currencyId, address indexed settler, int256 amountToSettleAsset, int256 fCashAmount ); event nTokenResidualPurchase( uint16 indexed currencyId, uint40 indexed maturity, address indexed purchaser, int256 fCashAmountToPurchase, int256 netAssetCashNToken ); event LendBorrowTrade( address indexed account, uint16 indexed currencyId, uint40 maturity, int256 netAssetCash, int256 netfCash ); event AddRemoveLiquidity( address indexed account, uint16 indexed currencyId, uint40 maturity, int256 netAssetCash, int256 netfCash, int256 netLiquidityTokens ); /// @notice Emitted when reserve fees are accrued event ReserveFeeAccrued(uint16 indexed currencyId, int256 fee); /// @notice Emitted whenever an account context has updated event AccountContextUpdate(address indexed account); /// @notice Emitted when an account has assets that are settled event AccountSettled(address indexed account); /// @notice Emitted when an asset rate is settled event SetSettlementRate(uint256 indexed currencyId, uint256 indexed maturity, uint128 rate); /* Liquidation Events */ event LiquidateLocalCurrency( address indexed liquidated, address indexed liquidator, uint16 localCurrencyId, int256 netLocalFromLiquidator ); event LiquidateCollateralCurrency( address indexed liquidated, address indexed liquidator, uint16 localCurrencyId, uint16 collateralCurrencyId, int256 netLocalFromLiquidator, int256 netCollateralTransfer, int256 netNTokenTransfer ); event LiquidatefCashEvent( address indexed liquidated, address indexed liquidator, uint16 localCurrencyId, uint16 fCashCurrency, int256 netLocalFromLiquidator, uint256[] fCashMaturities, int256[] fCashNotionalTransfer ); /** UUPS Upgradeable contract calls */ function upgradeTo(address newImplementation) external; function upgradeToAndCall(address newImplementation, bytes memory data) external payable; function getImplementation() external view returns (address); function owner() external view returns (address); function pauseRouter() external view returns (address); function pauseGuardian() external view returns (address); /** Initialize Markets Action */ function initializeMarkets(uint16 currencyId, bool isFirstInit) external; function sweepCashIntoMarkets(uint16 currencyId) external; /** Redeem nToken Action */ function nTokenRedeem( address redeemer, uint16 currencyId, uint96 tokensToRedeem_, bool sellTokenAssets ) external returns (int256); /** Account Action */ function enableBitmapCurrency(uint16 currencyId) external; function settleAccount(address account) external; function depositUnderlyingToken( address account, uint16 currencyId, uint256 amountExternalPrecision ) external payable returns (uint256); function depositAssetToken( address account, uint16 currencyId, uint256 amountExternalPrecision ) external returns (uint256); function withdraw( uint16 currencyId, uint88 amountInternalPrecision, bool redeemToUnderlying ) external returns (uint256); /** Batch Action */ function batchBalanceAction(address account, BalanceAction[] calldata actions) external payable; function batchBalanceAndTradeAction(address account, BalanceActionWithTrades[] calldata actions) external payable; function batchBalanceAndTradeActionWithCallback( address account, BalanceActionWithTrades[] calldata actions, bytes calldata callbackData ) external payable; /** Liquidation Action */ function calculateLocalCurrencyLiquidation( address liquidateAccount, uint16 localCurrency, uint96 maxNTokenLiquidation ) external returns (int256, int256); function liquidateLocalCurrency( address liquidateAccount, uint16 localCurrency, uint96 maxNTokenLiquidation ) external returns (int256, int256); function calculateCollateralCurrencyLiquidation( address liquidateAccount, uint16 localCurrency, uint16 collateralCurrency, uint128 maxCollateralLiquidation, uint96 maxNTokenLiquidation ) external returns ( int256, int256, int256 ); function liquidateCollateralCurrency( address liquidateAccount, uint16 localCurrency, uint16 collateralCurrency, uint128 maxCollateralLiquidation, uint96 maxNTokenLiquidation, bool withdrawCollateral, bool redeemToUnderlying ) external returns ( int256, int256, int256 ); function calculatefCashLocalLiquidation( address liquidateAccount, uint16 localCurrency, uint256[] calldata fCashMaturities, uint256[] calldata maxfCashLiquidateAmounts ) external returns (int256[] memory, int256); function liquidatefCashLocal( address liquidateAccount, uint16 localCurrency, uint256[] calldata fCashMaturities, uint256[] calldata maxfCashLiquidateAmounts ) external returns (int256[] memory, int256); function calculatefCashCrossCurrencyLiquidation( address liquidateAccount, uint16 localCurrency, uint16 fCashCurrency, uint256[] calldata fCashMaturities, uint256[] calldata maxfCashLiquidateAmounts ) external returns (int256[] memory, int256); function liquidatefCashCrossCurrency( address liquidateAccount, uint16 localCurrency, uint16 fCashCurrency, uint256[] calldata fCashMaturities, uint256[] calldata maxfCashLiquidateAmounts ) external returns (int256[] memory, int256); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "interfaces/chainlink/AggregatorV2V3Interface.sol"; import "interfaces/notional/AssetRateAdapter.sol"; /// @notice Different types of internal tokens /// - UnderlyingToken: underlying asset for a cToken (except for Ether) /// - cToken: Compound interest bearing token /// - cETH: Special handling for cETH tokens /// - Ether: the one and only /// - NonMintable: tokens that do not have an underlying (therefore not cTokens) enum TokenType {UnderlyingToken, cToken, cETH, Ether, NonMintable} /// @notice Specifies the different trade action types in the system. Each trade action type is /// encoded in a tightly packed bytes32 object. Trade action type is the first big endian byte of the /// 32 byte trade action object. The schemas for each trade action type are defined below. enum TradeActionType { // (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 minImpliedRate, uint120 unused) Lend, // (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 maxImpliedRate, uint128 unused) Borrow, // (uint8 TradeActionType, uint8 MarketIndex, uint88 assetCashAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused) AddLiquidity, // (uint8 TradeActionType, uint8 MarketIndex, uint88 tokenAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused) RemoveLiquidity, // (uint8 TradeActionType, uint32 Maturity, int88 fCashResidualAmount, uint128 unused) PurchaseNTokenResidual, // (uint8 TradeActionType, address CounterpartyAddress, int88 fCashAmountToSettle) SettleCashDebt } /// @notice Specifies different deposit actions that can occur during BalanceAction or BalanceActionWithTrades enum DepositActionType { // No deposit action None, // Deposit asset cash, depositActionAmount is specified in asset cash external precision DepositAsset, // Deposit underlying tokens that are mintable to asset cash, depositActionAmount is specified in underlying token // external precision DepositUnderlying, // Deposits specified asset cash external precision amount into an nToken and mints the corresponding amount of // nTokens into the account DepositAssetAndMintNToken, // Deposits specified underlying in external precision, mints asset cash, and uses that asset cash to mint nTokens DepositUnderlyingAndMintNToken, // Redeems an nToken balance to asset cash. depositActionAmount is specified in nToken precision. Considered a deposit action // because it deposits asset cash into an account. If there are fCash residuals that cannot be sold off, will revert. RedeemNToken, // Converts specified amount of asset cash balance already in Notional to nTokens. depositActionAmount is specified in // Notional internal 8 decimal precision. ConvertCashToNToken } /// @notice Used internally for PortfolioHandler state enum AssetStorageState {NoChange, Update, Delete, RevertIfStored} /****** Calldata objects ******/ /// @notice Defines a balance action for batchAction struct BalanceAction { // Deposit action to take (if any) DepositActionType actionType; uint16 currencyId; // Deposit action amount must correspond to the depositActionType, see documentation above. uint256 depositActionAmount; // Withdraw an amount of asset cash specified in Notional internal 8 decimal precision uint256 withdrawAmountInternalPrecision; // If set to true, will withdraw entire cash balance. Useful if there may be an unknown amount of asset cash // residual left from trading. bool withdrawEntireCashBalance; // If set to true, will redeem asset cash to the underlying token on withdraw. bool redeemToUnderlying; } /// @notice Defines a balance action with a set of trades to do as well struct BalanceActionWithTrades { DepositActionType actionType; uint16 currencyId; uint256 depositActionAmount; uint256 withdrawAmountInternalPrecision; bool withdrawEntireCashBalance; bool redeemToUnderlying; // Array of tightly packed 32 byte objects that represent trades. See TradeActionType documentation bytes32[] trades; } /****** In memory objects ******/ /// @notice Internal object that represents settled cash balances struct SettleAmount { uint256 currencyId; int256 netCashChange; } /// @notice Internal object that represents a token struct Token { address tokenAddress; bool hasTransferFee; int256 decimals; TokenType tokenType; uint256 maxCollateralBalance; } /// @notice Internal object that represents an nToken portfolio struct nTokenPortfolio { CashGroupParameters cashGroup; PortfolioState portfolioState; int256 totalSupply; int256 cashBalance; uint256 lastInitializedTime; bytes6 parameters; address tokenAddress; } /// @notice Internal object used during liquidation struct LiquidationFactors { address account; // Aggregate free collateral of the account denominated in ETH underlying, 8 decimal precision int256 netETHValue; // Amount of net local currency asset cash before haircuts and buffers available int256 localAssetAvailable; // Amount of net collateral currency asset cash before haircuts and buffers available int256 collateralAssetAvailable; // Haircut value of nToken holdings denominated in asset cash, will be local or collateral nTokens based // on liquidation type int256 nTokenHaircutAssetValue; // nToken parameters for calculating liquidation amount bytes6 nTokenParameters; // ETH exchange rate from local currency to ETH ETHRate localETHRate; // ETH exchange rate from collateral currency to ETH ETHRate collateralETHRate; // Asset rate for the local currency, used in cross currency calculations to calculate local asset cash required AssetRateParameters localAssetRate; // Used during currency liquidations if the account has liquidity tokens CashGroupParameters collateralCashGroup; // Used during currency liquidations if it is only a calculation, defaults to false bool isCalculation; } /// @notice Internal asset array portfolio state struct PortfolioState { // Array of currently stored assets PortfolioAsset[] storedAssets; // Array of new assets to add PortfolioAsset[] newAssets; uint256 lastNewAssetIndex; // Holds the length of stored assets after accounting for deleted assets uint256 storedAssetLength; } /// @notice In memory ETH exchange rate used during free collateral calculation. struct ETHRate { // The decimals (i.e. 10^rateDecimalPlaces) of the exchange rate, defined by the rate oracle int256 rateDecimals; // The exchange rate from base to ETH (if rate invert is required it is already done) int256 rate; // Amount of buffer as a multiple with a basis of 100 applied to negative balances. int256 buffer; // Amount of haircut as a multiple with a basis of 100 applied to positive balances int256 haircut; // Liquidation discount as a multiple with a basis of 100 applied to the exchange rate // as an incentive given to liquidators. int256 liquidationDiscount; } /// @notice Internal object used to handle balance state during a transaction struct BalanceState { uint16 currencyId; // Cash balance stored in balance state at the beginning of the transaction int256 storedCashBalance; // nToken balance stored at the beginning of the transaction int256 storedNTokenBalance; // The net cash change as a result of asset settlement or trading int256 netCashChange; // Net asset transfers into or out of the account int256 netAssetTransferInternalPrecision; // Net token transfers into or out of the account int256 netNTokenTransfer; // Net token supply change from minting or redeeming int256 netNTokenSupplyChange; // The last time incentives were claimed for this currency uint256 lastClaimTime; // The last integral supply amount when tokens were claimed uint256 lastClaimIntegralSupply; } /// @dev Asset rate used to convert between underlying cash and asset cash struct AssetRateParameters { // Address of the asset rate oracle AssetRateAdapter rateOracle; // The exchange rate from base to quote (if invert is required it is already done) int256 rate; // The decimals of the underlying, the rate converts to the underlying decimals int256 underlyingDecimals; } /// @dev Cash group when loaded into memory struct CashGroupParameters { uint16 currencyId; uint256 maxMarketIndex; AssetRateParameters assetRate; bytes32 data; } /// @dev A portfolio asset when loaded in memory struct PortfolioAsset { // Asset currency id uint256 currencyId; uint256 maturity; // Asset type, fCash or liquidity token. uint256 assetType; // fCash amount or liquidity token amount int256 notional; // Used for managing portfolio asset state uint256 storageSlot; // The state of the asset for when it is written to storage AssetStorageState storageState; } /// @dev Market object as represented in memory struct MarketParameters { bytes32 storageSlot; uint256 maturity; // Total amount of fCash available for purchase in the market. int256 totalfCash; // Total amount of cash available for purchase in the market. int256 totalAssetCash; // Total amount of liquidity tokens (representing a claim on liquidity) in the market. int256 totalLiquidity; // This is the previous annualized interest rate in RATE_PRECISION that the market traded // at. This is used to calculate the rate anchor to smooth interest rates over time. uint256 lastImpliedRate; // Time lagged version of lastImpliedRate, used to value fCash assets at market rates while // remaining resistent to flash loan attacks. uint256 oracleRate; // This is the timestamp of the previous trade uint256 previousTradeTime; } /****** Storage objects ******/ /// @dev Token object in storage: /// 20 bytes for token address /// 1 byte for hasTransferFee /// 1 byte for tokenType /// 1 byte for tokenDecimals /// 9 bytes for maxCollateralBalance (may not always be set) struct TokenStorage { // Address of the token address tokenAddress; // Transfer fees will change token deposit behavior bool hasTransferFee; TokenType tokenType; uint8 decimalPlaces; // Upper limit on how much of this token the contract can hold at any time uint72 maxCollateralBalance; } /// @dev Exchange rate object as it is represented in storage, total storage is 25 bytes. struct ETHRateStorage { // Address of the rate oracle AggregatorV2V3Interface rateOracle; // The decimal places of precision that the rate oracle uses uint8 rateDecimalPlaces; // True of the exchange rate must be inverted bool mustInvert; // NOTE: both of these governance values are set with BUFFER_DECIMALS precision // Amount of buffer to apply to the exchange rate for negative balances. uint8 buffer; // Amount of haircut to apply to the exchange rate for positive balances uint8 haircut; // Liquidation discount in percentage point terms, 106 means a 6% discount uint8 liquidationDiscount; } /// @dev Asset rate oracle object as it is represented in storage, total storage is 21 bytes. struct AssetRateStorage { // Address of the rate oracle AssetRateAdapter rateOracle; // The decimal places of the underlying asset uint8 underlyingDecimalPlaces; } /// @dev Governance parameters for a cash group, total storage is 9 bytes + 7 bytes for liquidity token haircuts /// and 7 bytes for rate scalars, total of 23 bytes. Note that this is stored packed in the storage slot so there /// are no indexes stored for liquidityTokenHaircuts or rateScalars, maxMarketIndex is used instead to determine the /// length. struct CashGroupSettings { // Index of the AMMs on chain that will be made available. Idiosyncratic fCash // that is dated less than the longest AMM will be tradable. uint8 maxMarketIndex; // Time window in 5 minute increments that the rate oracle will be averaged over uint8 rateOracleTimeWindow5Min; // Total fees per trade, specified in BPS uint8 totalFeeBPS; // Share of the fees given to the protocol, denominated in percentage uint8 reserveFeeShare; // Debt buffer specified in 5 BPS increments uint8 debtBuffer5BPS; // fCash haircut specified in 5 BPS increments uint8 fCashHaircut5BPS; // If an account has a negative cash balance, it can be settled by incurring debt at the 3 month market. This // is the basis points for the penalty rate that will be added the current 3 month oracle rate. uint8 settlementPenaltyRate5BPS; // If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for uint8 liquidationfCashHaircut5BPS; // If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for uint8 liquidationDebtBuffer5BPS; // Liquidity token haircut applied to cash claims, specified as a percentage between 0 and 100 uint8[] liquidityTokenHaircuts; // Rate scalar used to determine the slippage of the market uint8[] rateScalars; } /// @dev Holds account level context information used to determine settlement and /// free collateral actions. Total storage is 28 bytes struct AccountContext { // Used to check when settlement must be triggered on an account uint40 nextSettleTime; // For lenders that never incur debt, we use this flag to skip the free collateral check. bytes1 hasDebt; // Length of the account's asset array uint8 assetArrayLength; // If this account has bitmaps set, this is the corresponding currency id uint16 bitmapCurrencyId; // 9 total active currencies possible (2 bytes each) bytes18 activeCurrencies; } /// @dev Holds nToken context information mapped via the nToken address, total storage is /// 16 bytes struct nTokenContext { // Currency id that the nToken represents uint16 currencyId; // Annual incentive emission rate denominated in WHOLE TOKENS (multiply by // INTERNAL_TOKEN_PRECISION to get the actual rate) uint32 incentiveAnnualEmissionRate; // The last block time at utc0 that the nToken was initialized at, zero if it // has never been initialized uint32 lastInitializedTime; // Length of the asset array, refers to the number of liquidity tokens an nToken // currently holds uint8 assetArrayLength; // Each byte is a specific nToken parameter bytes5 nTokenParameters; } /// @dev Holds account balance information, total storage 32 bytes struct BalanceStorage { // Number of nTokens held by the account uint80 nTokenBalance; // Last time the account claimed their nTokens uint32 lastClaimTime; // The total integral supply of the nToken at the last claim time packed into // 56 bits. There is some loss of precision here but it is acceptable uint56 packedLastClaimIntegralSupply; // Cash balance of the account int88 cashBalance; } /// @dev Holds information about a settlement rate, total storage 25 bytes struct SettlementRateStorage { uint40 blockTime; uint128 settlementRate; uint8 underlyingDecimalPlaces; } /// @dev Holds information about a market, total storage is 42 bytes so this spans /// two storage words struct MarketStorage { // Total fCash in the market uint80 totalfCash; // Total asset cash in the market uint80 totalAssetCash; // Last annualized interest rate the market traded at uint32 lastImpliedRate; // Last recorded oracle rate for the market uint32 oracleRate; // Last time a trade was made uint32 previousTradeTime; // This is stored in slot + 1 uint80 totalLiquidity; } struct ifCashStorage { // Notional amount of fCash at the slot, limited to int128 to allow for // future expansion int128 notional; } /// @dev A single portfolio asset in storage, total storage of 19 bytes struct PortfolioAssetStorage { // Currency Id for the asset uint16 currencyId; // Maturity of the asset uint40 maturity; // Asset type (fCash or Liquidity Token marker) uint8 assetType; // Notional int88 notional; } /// @dev nToken total supply factors for the nToken, includes factors related /// to claiming incentives, total storage 32 bytes struct nTokenTotalSupplyStorage { // Total supply of the nToken uint96 totalSupply; // Integral of the total supply used for calculating the average total supply uint128 integralTotalSupply; // Last timestamp the supply value changed, used for calculating the integralTotalSupply uint32 lastSupplyChangeTime; } /// @dev Used in view methods to return account balances in a developer friendly manner struct AccountBalance { uint16 currencyId; int256 cashBalance; int256 nTokenBalance; uint256 lastClaimTime; uint256 lastClaimIntegralSupply; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import "./AggregatorInterface.sol"; import "./AggregatorV3Interface.sol"; interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface { } // SPDX-License-Identifier: GPL-v3 pragma solidity >=0.7.0; /// @notice Used as a wrapper for tokens that are interest bearing for an /// underlying token. Follows the cToken interface, however, can be adapted /// for other interest bearing tokens. interface AssetRateAdapter { function token() external view returns (address); function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); function underlying() external view returns (address); function getExchangeRateStateful() external returns (int256); function getExchangeRateView() external view returns (int256); function getAnnualizedSupplyRate() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt); event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "@openzeppelin/contracts/utils/Address.sol"; import "../utils/StorageSlot.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * */ abstract contract ERC1967Upgrade { // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; Address.functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } } // 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.7.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; interface nTokenERC20 { event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); function nTokenTotalSupply(address nTokenAddress) external view returns (uint256); function nTokenTransferAllowance( uint16 currencyId, address owner, address spender ) external view returns (uint256); function nTokenBalanceOf(uint16 currencyId, address account) external view returns (uint256); function nTokenTransferApprove( uint16 currencyId, address owner, address spender, uint256 amount ) external returns (bool); function nTokenTransfer( uint16 currencyId, address from, address to, uint256 amount ) external returns (bool); function nTokenTransferFrom( uint16 currencyId, address spender, address from, address to, uint256 amount ) external returns (bool); function nTokenTransferApproveAll(address spender, uint256 amount) external returns (bool); function nTokenClaimIncentives() external returns (uint256); function nTokenPresentValueAssetDenominated(uint16 currencyId) external view returns (int256); function nTokenPresentValueUnderlyingDenominated(uint16 currencyId) external view returns (int256); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../contracts/global/Types.sol"; interface nERC1155Interface { event TransferSingle( address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value ); event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); event ApprovalForAll(address indexed account, address indexed operator, bool approved); event URI(string value, uint256 indexed id); function supportsInterface(bytes4 interfaceId) external pure returns (bool); function balanceOf(address account, uint256 id) external view returns (uint256); function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); function signedBalanceOf(address account, uint256 id) external view returns (int256); function signedBalanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (int256[] memory); function setApprovalForAll(address operator, bool approved) external; function isApprovedForAll(address account, address operator) external view returns (bool); function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external payable; function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external payable; function decodeToAssets(uint256[] calldata ids, uint256[] calldata amounts) external view returns (PortfolioAsset[] memory); function encodeToId( uint16 currencyId, uint40 maturity, uint8 assetType ) external pure returns (uint256 id); } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../contracts/global/Types.sol"; import "interfaces/chainlink/AggregatorV2V3Interface.sol"; import "interfaces/notional/NotionalGovernance.sol"; interface NotionalGovernance { event ListCurrency(uint16 newCurrencyId); event UpdateETHRate(uint16 currencyId); event UpdateAssetRate(uint16 currencyId); event UpdateCashGroup(uint16 currencyId); event DeployNToken(uint16 currencyId, address nTokenAddress); event UpdateDepositParameters(uint16 currencyId); event UpdateInitializationParameters(uint16 currencyId); event UpdateIncentiveEmissionRate(uint16 currencyId, uint32 newEmissionRate); event UpdateTokenCollateralParameters(uint16 currencyId); event UpdateGlobalTransferOperator(address operator, bool approved); event UpdateAuthorizedCallbackContract(address operator, bool approved); event UpdateMaxCollateralBalance(uint16 currencyId, uint72 maxCollateralBalance); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event PauseRouterAndGuardianUpdated(address indexed pauseRouter, address indexed pauseGuardian); function transferOwnership(address newOwner) external; function setPauseRouterAndGuardian(address pauseRouter_, address pauseGuardian_) external; function listCurrency( TokenStorage calldata assetToken, TokenStorage calldata underlyingToken, AggregatorV2V3Interface rateOracle, bool mustInvert, uint8 buffer, uint8 haircut, uint8 liquidationDiscount ) external returns (uint16 currencyId); function updateMaxCollateralBalance( uint16 currencyId, uint72 maxCollateralBalanceInternalPrecision ) external; function enableCashGroup( uint16 currencyId, AssetRateAdapter assetRateOracle, CashGroupSettings calldata cashGroup, string calldata underlyingName, string calldata underlyingSymbol ) external; function updateDepositParameters( uint16 currencyId, uint32[] calldata depositShares, uint32[] calldata leverageThresholds ) external; function updateInitializationParameters( uint16 currencyId, uint32[] calldata annualizedAnchorRates, uint32[] calldata proportions ) external; function updateIncentiveEmissionRate(uint16 currencyId, uint32 newEmissionRate) external; function updateTokenCollateralParameters( uint16 currencyId, uint8 residualPurchaseIncentive10BPS, uint8 pvHaircutPercentage, uint8 residualPurchaseTimeBufferHours, uint8 cashWithholdingBuffer10BPS, uint8 liquidationHaircutPercentage ) external; function updateCashGroup(uint16 currencyId, CashGroupSettings calldata cashGroup) external; function updateAssetRate(uint16 currencyId, AssetRateAdapter rateOracle) external; function updateETHRate( uint16 currencyId, AggregatorV2V3Interface rateOracle, bool mustInvert, uint8 buffer, uint8 haircut, uint8 liquidationDiscount ) external; function updateGlobalTransferOperator(address operator, bool approved) external; function updateAuthorizedCallbackContract(address operator, bool approved) external; } // SPDX-License-Identifier: GPL-3.0-only pragma solidity ^0.7.0; pragma abicoder v2; import "../../contracts/global/Types.sol"; interface NotionalViews { function getMaxCurrencyId() external view returns (uint16); function getCurrencyId(address tokenAddress) external view returns (uint16 currencyId); function getCurrency(uint16 currencyId) external view returns (Token memory assetToken, Token memory underlyingToken); function getRateStorage(uint16 currencyId) external view returns (ETHRateStorage memory ethRate, AssetRateStorage memory assetRate); function getCurrencyAndRates(uint16 currencyId) external view returns ( Token memory assetToken, Token memory underlyingToken, ETHRate memory ethRate, AssetRateParameters memory assetRate ); function getCashGroup(uint16 currencyId) external view returns (CashGroupSettings memory); function getCashGroupAndAssetRate(uint16 currencyId) external view returns (CashGroupSettings memory cashGroup, AssetRateParameters memory assetRate); function getInitializationParameters(uint16 currencyId) external view returns (int256[] memory annualizedAnchorRates, int256[] memory proportions); function getDepositParameters(uint16 currencyId) external view returns (int256[] memory depositShares, int256[] memory leverageThresholds); function nTokenAddress(uint16 currencyId) external view returns (address); function getNoteToken() external view returns (address); function getSettlementRate(uint16 currencyId, uint40 maturity) external view returns (AssetRateParameters memory); function getMarket(uint16 currencyId, uint256 maturity, uint256 settlementDate) external view returns (MarketParameters memory); function getActiveMarkets(uint16 currencyId) external view returns (MarketParameters[] memory); function getActiveMarketsAtBlockTime(uint16 currencyId, uint32 blockTime) external view returns (MarketParameters[] memory); function getReserveBalance(uint16 currencyId) external view returns (int256 reserveBalance); function getNTokenPortfolio(address tokenAddress) external view returns (PortfolioAsset[] memory liquidityTokens, PortfolioAsset[] memory netfCashAssets); function getNTokenAccount(address tokenAddress) external view returns ( uint16 currencyId, uint256 totalSupply, uint256 incentiveAnnualEmissionRate, uint256 lastInitializedTime, bytes5 nTokenParameters, int256 cashBalance, uint256 integralTotalSupply, uint256 lastSupplyChangeTime ); function getAccount(address account) external view returns ( AccountContext memory accountContext, AccountBalance[] memory accountBalances, PortfolioAsset[] memory portfolio ); function getAccountContext(address account) external view returns (AccountContext memory); function getAccountBalance(uint16 currencyId, address account) external view returns ( int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime ); function getAccountPortfolio(address account) external view returns (PortfolioAsset[] memory); function getfCashNotional( address account, uint16 currencyId, uint256 maturity ) external view returns (int256); function getAssetsBitmap(address account, uint16 currencyId) external view returns (bytes32); function getFreeCollateral(address account) external view returns (int256, int256[] memory); function calculateNTokensToMint(uint16 currencyId, uint88 amountToDepositExternalPrecision) external view returns (uint256); function getfCashAmountGivenCashAmount( uint16 currencyId, int88 netCashToAccount, uint256 marketIndex, uint256 blockTime ) external view returns (int256); function getCashAmountGivenfCashAmount( uint16 currencyId, int88 fCashAmount, uint256 marketIndex, uint256 blockTime ) external view returns (int256, int256); function nTokenGetClaimableIncentives(address account, uint256 blockTime) external view returns (uint256); }
Liquidation calculation methods are stateful (they settle accounts if required) and therefore we prevent them from being called unless specifically authorized.
function getRouterImplementation(bytes4 sig) public view returns (address) { if ( (sig == NotionalProxy.calculateCollateralCurrencyLiquidation.selector || sig == NotionalProxy.liquidateCollateralCurrency.selector) && isEnabled(Constants.COLLATERAL_CURRENCY_ENABLED) ) { return LIQUIDATE_CURRENCY; } if ( (sig == NotionalProxy.calculateLocalCurrencyLiquidation.selector || sig == NotionalProxy.liquidateLocalCurrency.selector) && isEnabled(Constants.LOCAL_CURRENCY_ENABLED) ) { return LIQUIDATE_CURRENCY; } if ( (sig == NotionalProxy.liquidatefCashLocal.selector || sig == NotionalProxy.calculatefCashLocalLiquidation.selector) && isEnabled(Constants.LOCAL_FCASH_ENABLED) ) { return LIQUIDATE_FCASH; } if ( (sig == NotionalProxy.liquidatefCashCrossCurrency.selector || sig == NotionalProxy.calculatefCashCrossCurrencyLiquidation.selector) && isEnabled(Constants.CROSS_CURRENCY_FCASH_ENABLED) ) { return LIQUIDATE_FCASH; } }
5,856,669
[ 1, 48, 18988, 350, 367, 11096, 2590, 854, 28188, 261, 451, 402, 444, 5929, 9484, 309, 1931, 13, 471, 13526, 732, 5309, 2182, 628, 3832, 2566, 3308, 21195, 10799, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4170, 14068, 13621, 12, 3890, 24, 3553, 13, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 309, 261, 203, 5411, 261, 7340, 422, 2288, 285, 287, 3886, 18, 11162, 13535, 2045, 287, 7623, 48, 18988, 350, 367, 18, 9663, 747, 203, 7734, 3553, 422, 2288, 285, 287, 3886, 18, 549, 26595, 340, 13535, 2045, 287, 7623, 18, 9663, 13, 597, 203, 5411, 12047, 12, 2918, 18, 4935, 12190, 654, 1013, 67, 7509, 25231, 67, 13560, 13, 203, 3639, 262, 288, 203, 5411, 327, 8961, 53, 3060, 1777, 67, 7509, 25231, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 203, 5411, 261, 7340, 422, 2288, 285, 287, 3886, 18, 11162, 2042, 7623, 48, 18988, 350, 367, 18, 9663, 747, 203, 7734, 3553, 422, 2288, 285, 287, 3886, 18, 549, 26595, 340, 2042, 7623, 18, 9663, 13, 597, 203, 5411, 12047, 12, 2918, 18, 14922, 67, 7509, 25231, 67, 13560, 13, 203, 3639, 262, 288, 203, 5411, 327, 8961, 53, 3060, 1777, 67, 7509, 25231, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 203, 5411, 261, 7340, 422, 2288, 285, 287, 3886, 18, 549, 26595, 340, 74, 39, 961, 2042, 18, 9663, 747, 203, 7734, 3553, 422, 2288, 285, 287, 3886, 18, 11162, 74, 39, 961, 2042, 48, 18988, 350, 367, 18, 9663, 13, 597, 203, 5411, 12047, 12, 2918, 18, 14922, 67, 42, 3587, 2664, 67, 13560, 13, 203, 3639, 262, 288, 203, 5411, 327, 8961, 53, 3060, 1777, 67, 42, 3587, 2664, 31, 203, 3639, 289, 203, 203, 3639, 2 ]
pragma solidity ^0.4.13; library Math { 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; } } 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 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 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 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]; } } 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 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; } } contract BurnableToken is StandardToken { // @notice An address for the transfer event where the burned tokens are transferred in a faux Transfer event address public constant BURN_ADDRESS = 0; /** How many tokens we burned */ event Burned(address burner, uint burnedAmount); /** * Burn extra tokens from a balance. * */ function burn(uint burnAmount) { address burner = msg.sender; balances[burner] = balances[burner].sub(burnAmount); totalSupply_ = totalSupply_.sub(burnAmount); Burned(burner, burnAmount); // Inform the blockchain explores that track the // balances only by a transfer event that the balance in this // address has decreased Transfer(burner, BURN_ADDRESS, burnAmount); } } contract LimitedTransferToken is ERC20 { /** * @dev Checks whether it can transfer or otherwise throws. */ modifier canTransferLimitedTransferToken(address _sender, uint256 _value) { require(_value <= transferableTokens(_sender, uint64(now))); _; } /** * @dev Default transferable tokens function returns all tokens for a holder (no limit). * @dev Overwriting transferableTokens(address holder, uint64 time) is the way to provide the * specific logic for limiting token transferability for a holder over time. */ function transferableTokens(address holder, uint64 time) public constant returns (uint256) { return balanceOf(holder); } } contract ReleasableToken is ERC20, Ownable { /* The finalizer contract that allows unlift the transfer limits on this token */ address public releaseAgent; /** A crowdsale contract can release us to the wild if ICO success. If false we are are in transfer lock up period.*/ bool public released = false; /** Map of agents that are allowed to transfer tokens regardless of the lock down period. These are crowdsale contracts and possible the team multisig itself. */ mapping (address => bool) public transferAgents; /** The function can be called only before or after the tokens have been releasesd */ modifier inReleaseState(bool releaseState) { if(releaseState != released) { revert(); } _; } /** The function can be called only by a whitelisted release agent. */ modifier onlyReleaseAgent() { if(msg.sender != releaseAgent) { revert(); } _; } /** * Limit token transfer until the crowdsale is over. * */ modifier canTransferReleasable(address _sender) { if(!released) { if(!transferAgents[_sender]) { revert(); } } _; } /** * Set the contract that can call release and make the token transferable. * * Design choice. Allow reset the release agent to fix fat finger mistakes. */ function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { // We don't do interface check here as we might want to a normal wallet address to act as a release agent releaseAgent = addr; } /** * Owner can allow a particular address (a crowdsale contract) to transfer tokens despite the lock up period. */ function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public { transferAgents[addr] = state; } /** * One way function to release the tokens to the wild. * * Can be called only from the release agent that is the final ICO contract. It is only called if the crowdsale has been success (first milestone reached). */ function releaseTokenTransfer() public onlyReleaseAgent { released = true; } } contract UpgradeAgent { uint public originalSupply; /** Interface marker */ function isUpgradeAgent() public constant returns (bool) { return true; } function upgradeFrom(address _from, uint256 _value) public; } contract UpgradeableToken is StandardToken { /** Contract / person who can set the upgrade path. This can be the same as team multisig wallet, as what it is with its default value. */ address public upgradeMaster; /** The next contract where the tokens will be migrated. */ UpgradeAgent public upgradeAgent; /** How many tokens we have upgraded by now. */ uint256 public totalUpgraded; /** * Upgrade states. * * - NotAllowed: The child contract has not reached a condition where the upgrade can begin * - WaitingForAgent: Token allows upgrade, but we don't have a new agent yet * - ReadyToUpgrade: The agent is set, but not a single token has been upgraded yet * - Upgrading: Upgrade agent is set and the balance holders can upgrade their tokens * */ enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading} /** * Somebody has upgraded some of his tokens. */ event Upgrade(address indexed _from, address indexed _to, uint256 _value); /** * New upgrade agent available. */ event UpgradeAgentSet(address agent); /** * Do not allow construction without upgrade master set. */ function UpgradeableToken(address _upgradeMaster) public { upgradeMaster = _upgradeMaster; } /** * Allow the token holder to upgrade some of their tokens to a new contract. */ function upgrade(uint256 value) public { UpgradeState state = getUpgradeState(); if (!(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading)) { // Called in a bad state revert(); } // Validate input value. if (value == 0) revert(); balances[msg.sender] = balances[msg.sender].sub(value); // Take tokens out from circulation totalSupply_ = totalSupply_.sub(value); totalUpgraded = totalUpgraded.add(value); // Upgrade agent reissues the tokens upgradeAgent.upgradeFrom(msg.sender, value); Upgrade(msg.sender, upgradeAgent, value); } /** * Set an upgrade agent that handles */ function setUpgradeAgent(address agent) external { if (!canUpgrade()) { // The token is not yet in a state that we could think upgrading revert(); } if (agent == 0x0) revert(); // Only a master can designate the next agent if (msg.sender != upgradeMaster) revert(); // Upgrade has already begun for an agent if (getUpgradeState() == UpgradeState.Upgrading) revert(); upgradeAgent = UpgradeAgent(agent); // Bad interface if (!upgradeAgent.isUpgradeAgent()) revert(); // Make sure that token supplies match in source and target if (upgradeAgent.originalSupply() != totalSupply_) revert(); UpgradeAgentSet(upgradeAgent); } /** * Get the state of the token upgrade. */ function getUpgradeState() public constant returns (UpgradeState) { if (!canUpgrade()) return UpgradeState.NotAllowed; else if (address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent; else if (totalUpgraded == 0) return UpgradeState.ReadyToUpgrade; else return UpgradeState.Upgrading; } /** * Change the upgrade master. * * This allows us to set a new owner for the upgrade mechanism. */ function setUpgradeMaster(address master) public { if (master == 0x0) revert(); if (msg.sender != upgradeMaster) revert(); upgradeMaster = master; } /** * Child contract can enable to provide the condition when the upgrade can begun. */ function canUpgrade() public constant returns (bool) { return true; } } contract CrowdsaleToken is ReleasableToken, UpgradeableToken { /** Name and symbol were updated. */ event UpdatedTokenInformation(string newName, string newSymbol); string public name; string public symbol; uint8 public decimals; /** * Construct the token. * * This token must be created through a team multisig wallet, so that it is owned by that wallet. * * @param _name Token name * @param _symbol Token symbol - should be all caps * @param _initialSupply How many tokens we start with * @param _decimals Number of decimal places */ function CrowdsaleToken(string _name, string _symbol, uint _initialSupply, uint8 _decimals) UpgradeableToken(msg.sender) public { // Create any address, can be transferred // to team multisig via changeOwner(), // also remember to call setUpgradeMaster() owner = msg.sender; name = _name; symbol = _symbol; totalSupply_ = _initialSupply; decimals = _decimals; // Create initially all balance on the team multisig balances[owner] = totalSupply_; } /** * When token is released to be transferable, enforce no new tokens can be created. */ function releaseTokenTransfer() public onlyReleaseAgent { super.releaseTokenTransfer(); } /** * Allow upgrade agent functionality kick in only if the crowdsale was success. */ function canUpgrade() public constant returns(bool) { return released && super.canUpgrade(); } /** * Owner can update token information here. * * It is often useful to conceal the actual token association, until * the token operations, like central issuance or reissuance have been completed. * * This function allows the token owner to rename the token after the operations * have been completed and then point the audience to use the token contract. */ function setTokenInformation(string _name, string _symbol) onlyOwner { name = _name; symbol = _symbol; UpdatedTokenInformation(name, symbol); } } contract VestedToken is StandardToken, LimitedTransferToken { uint256 MAX_GRANTS_PER_ADDRESS = 20; struct TokenGrant { address granter; // 20 bytes uint256 value; // 32 bytes uint64 cliff; uint64 vesting; uint64 start; // 3 * 8 = 24 bytes bool revokable; bool burnsOnRevoke; // 2 * 1 = 2 bits? or 2 bytes? } // total 78 bytes = 3 sstore per operation (32 per sstore) mapping (address => TokenGrant[]) public grants; event NewTokenGrant(address indexed from, address indexed to, uint256 value, uint256 grantId); /** * @dev Grant tokens to a specified address * @param _to address The address which the tokens will be granted to. * @param _value uint256 The amount of tokens to be granted. * @param _start uint64 Time of the beginning of the grant. * @param _cliff uint64 Time of the cliff period. * @param _vesting uint64 The vesting period. */ function grantVestedTokens( address _to, uint256 _value, uint64 _start, uint64 _cliff, uint64 _vesting, bool _revokable, bool _burnsOnRevoke ) public { // Check for date inconsistencies that may cause unexpected behavior require(_cliff >= _start && _vesting >= _cliff); require(tokenGrantsCount(_to) < MAX_GRANTS_PER_ADDRESS); // To prevent a user being spammed and have his balance locked (out of gas attack when calculating vesting). uint256 count = grants[_to].push( TokenGrant( _revokable ? msg.sender : 0, // avoid storing an extra 20 bytes when it is non-revokable _value, _cliff, _vesting, _start, _revokable, _burnsOnRevoke ) ); transfer(_to, _value); NewTokenGrant(msg.sender, _to, _value, count - 1); } /** * @dev Revoke the grant of tokens of a specifed address. * @param _holder The address which will have its tokens revoked. * @param _grantId The id of the token grant. */ function revokeTokenGrant(address _holder, uint256 _grantId) public { TokenGrant storage grant = grants[_holder][_grantId]; require(grant.revokable); require(grant.granter == msg.sender); // Only granter can revoke it address receiver = grant.burnsOnRevoke ? 0xdead : msg.sender; uint256 nonVested = nonVestedTokens(grant, uint64(now)); // remove grant from array delete grants[_holder][_grantId]; grants[_holder][_grantId] = grants[_holder][grants[_holder].length.sub(1)]; grants[_holder].length -= 1; balances[receiver] = balances[receiver].add(nonVested); balances[_holder] = balances[_holder].sub(nonVested); Transfer(_holder, receiver, nonVested); } /** * @dev Calculate the total amount of transferable tokens of a holder at a given time * @param holder address The address of the holder * @param time uint64 The specific time. * @return An uint256 representing a holder's total amount of transferable tokens. */ function transferableTokens(address holder, uint64 time) public constant returns (uint256) { uint256 grantIndex = tokenGrantsCount(holder); if (grantIndex == 0) return super.transferableTokens(holder, time); // shortcut for holder without grants // Iterate through all the grants the holder has, and add all non-vested tokens uint256 nonVested = 0; for (uint256 i = 0; i < grantIndex; i++) { nonVested = SafeMath.add(nonVested, nonVestedTokens(grants[holder][i], time)); } // Balance - totalNonVested is the amount of tokens a holder can transfer at any given time uint256 vestedTransferable = SafeMath.sub(balanceOf(holder), nonVested); // Return the minimum of how many vested can transfer and other value // in case there are other limiting transferability factors (default is balanceOf) return Math.min256(vestedTransferable, super.transferableTokens(holder, time)); } /** * @dev Check the amount of grants that an address has. * @param _holder The holder of the grants. * @return A uint256 representing the total amount of grants. */ function tokenGrantsCount(address _holder) public constant returns (uint256 index) { return grants[_holder].length; } /** * @dev Calculate amount of vested tokens at a specific time * @param tokens uint256 The amount of tokens granted * @param time uint64 The time to be checked * @param start uint64 The time representing the beginning of the grant * @param cliff uint64 The cliff period, the period before nothing can be paid out * @param vesting uint64 The vesting period * @return An uint256 representing the amount of vested tokens of a specific grant * transferableTokens * | _/-------- vestedTokens rect * | _/ * | _/ * | _/ * | _/ * | / * | .| * | . | * | . | * | . | * | . | * | . | * +===+===========+---------+----------> time * Start Cliff Vesting */ function calculateVestedTokens( uint256 tokens, uint256 time, uint256 start, uint256 cliff, uint256 vesting) public pure returns (uint256) { // Shortcuts for before cliff and after vesting cases. if (time < cliff) return 0; if (time >= vesting) return tokens; // Interpolate all vested tokens. // As before cliff the shortcut returns 0, we can use just calculate a value // in the vesting rect (as shown in above's figure) // vestedTokens = (tokens * (time - start)) / (vesting - start) uint256 vestedTokens = SafeMath.div( SafeMath.mul( tokens, SafeMath.sub(time, start) ), SafeMath.sub(vesting, start) ); return vestedTokens; } /** * @dev Get all information about a specific grant. * @param _holder The address which will have its tokens revoked. * @param _grantId The id of the token grant. * @return Returns all the values that represent a TokenGrant(address, value, start, cliff, * revokability, burnsOnRevoke, and vesting) plus the vested value at the current time. */ function tokenGrant(address _holder, uint256 _grantId) public constant returns (address granter, uint256 value, uint256 vested, uint64 start, uint64 cliff, uint64 vesting, bool revokable, bool burnsOnRevoke) { TokenGrant storage grant = grants[_holder][_grantId]; granter = grant.granter; value = grant.value; start = grant.start; cliff = grant.cliff; vesting = grant.vesting; revokable = grant.revokable; burnsOnRevoke = grant.burnsOnRevoke; vested = vestedTokens(grant, uint64(now)); } /** * @dev Get the amount of vested tokens at a specific time. * @param grant TokenGrant The grant to be checked. * @param time The time to be checked * @return An uint256 representing the amount of vested tokens of a specific grant at a specific time. */ function vestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { return calculateVestedTokens( grant.value, uint256(time), uint256(grant.start), uint256(grant.cliff), uint256(grant.vesting) ); } /** * @dev Calculate the amount of non vested tokens at a specific time. * @param grant TokenGrant The grant to be checked. * @param time uint64 The time to be checked * @return An uint256 representing the amount of non vested tokens of a specific grant on the * passed time frame. */ function nonVestedTokens(TokenGrant grant, uint64 time) private constant returns (uint256) { return grant.value.sub(vestedTokens(grant, time)); } /** * @dev Calculate the date when the holder can transfer all its tokens * @param holder address The address of the holder * @return An uint256 representing the date of the last transferable tokens. */ function lastTokenIsTransferableDate(address holder) public constant returns (uint64 date) { date = uint64(now); uint256 grantIndex = grants[holder].length; for (uint256 i = 0; i < grantIndex; i++) { date = Math.max64(grants[holder][i].vesting, date); } } } contract WemarkToken is CrowdsaleToken, BurnableToken, VestedToken { modifier validDestination(address to) { require(to != address(0x0)); require(to != address(this)); _; } function WemarkToken() CrowdsaleToken('WemarkToken', 'WMK', 135000000 * (10 ** 18), 18) public { /** Initially allow only token creator to transfer tokens */ setTransferAgent(msg.sender, true); } /** * @dev Checks modifier and allows transfer if tokens are not locked or not released. * @param _to The address that will receive the tokens. * @param _value The amount of tokens to be transferred. */ function transfer(address _to, uint _value) validDestination(_to) canTransferReleasable(msg.sender) canTransferLimitedTransferToken(msg.sender, _value) public returns (bool) { // Call BasicToken.transfer() return super.transfer(_to, _value); } /** * @dev Checks modifier and allows transfer if tokens are not locked or not released. * @param _from The address that will send the tokens. * @param _to The address that will receive the tokens. * @param _value The amount of tokens to be transferred. */ function transferFrom(address _from, address _to, uint _value) validDestination(_to) canTransferReleasable(_from) canTransferLimitedTransferToken(_from, _value) public returns (bool) { // Call StandardToken.transferForm() return super.transferFrom(_from, _to, _value); } /** * @dev Prevent accounts that are blocked for transferring their tokens, from calling approve() */ function approve(address _spender, uint256 _value) public returns (bool) { // Call StandardToken.transferForm() return super.approve(_spender, _value); } /** * @dev Prevent accounts that are blocked for transferring their tokens, from calling increaseApproval() */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { // Call StandardToken.transferForm() return super.increaseApproval(_spender, _addedValue); } /** * @dev Can upgrade token contract only if token is released and super class allows too. */ function canUpgrade() public constant returns(bool) { return released && super.canUpgrade(); } /** * @dev Calculate the total amount of transferable tokens of a holder for the current moment of calling. * @param holder address The address of the holder * @return An uint256 representing a holder's total amount of transferable tokens. */ function transferableTokensNow(address holder) public constant returns (uint) { return transferableTokens(holder, uint64(now)); } function () payable { // If ether is sent to this address, send it back revert(); } }
2 * 1 = 2 bits? or 2 bytes?
bool burnsOnRevoke;
5,910,343
[ 1, 22, 225, 404, 273, 576, 4125, 35, 578, 576, 1731, 35, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1426, 18305, 87, 1398, 29196, 31, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; pragma experimental ABIEncoderV2; //Truffle Imports import "@chainlink/contracts/ChainlinkClient.sol"; import "@chainlink/contracts/vendor/Ownable.sol"; import "@chainlink/contracts/interfaces/LinkTokenInterface.sol"; import "@chainlink/contracts/interfaces/AggregatorInterface.sol"; import "@chainlink/contracts/vendor/SafeMathChainlink.sol"; import "@chainlink/contracts/interfaces/AggregatorV3Interface.sol"; //Remix imports - used when testing in remix //import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.4/ChainlinkClient.sol"; //import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.4/vendor/Ownable.sol"; //import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.4/interfaces/LinkTokenInterface.sol"; //import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.4/interfaces/AggregatorInterface.sol"; //import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.4/vendor/SafeMathChainlink.sol"; //import "https://github.com/smartcontractkit/chainlink/blob/develop/evm-contracts/src/v0.4/interfaces/AggregatorV3Interface.sol"; contract InsuranceProvider { using SafeMathChainlink for uint; address public insurer = msg.sender; AggregatorV3Interface internal priceFeed; uint public constant DAY_IN_SECONDS = 60; //How many seconds in a day. 60 for testing, 86400 for Production uint256 constant private ORACLE_PAYMENT = 0.1 * 10**18; // 0.1 LINK address public constant LINK_KOVAN = 0xa36085F69e2889c224210F603D836748e7dC0088 ; //address of LINK token on Kovan //here is where all the insurance contracts are stored. mapping (address => InsuranceContract) contracts; constructor() public payable { priceFeed = AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331); } /** * @dev Prevents a function being run unless it's called by the Insurance Provider */ modifier onlyOwner() { require(insurer == msg.sender,'Only Insurance provider can do this'); _; } /** * @dev Event to log when a contract is created */ event contractCreated(address _insuranceContract, uint _premium, uint _totalCover); /** * @dev Create a new contract for client, automatically approved and deployed to the blockchain */ function newContract(address _client, uint _duration, uint _premium, uint _payoutValue, string _cropLocation) public payable onlyOwner() returns(address) { //create contract, send payout amount so contract is fully funded plus a small buffer InsuranceContract i = (new InsuranceContract).value((_payoutValue * 1 ether).div(uint(getLatestPrice())))(_client, _duration, _premium, _payoutValue, _cropLocation, LINK_KOVAN,ORACLE_PAYMENT); contracts[address(i)] = i; //store insurance contract in contracts Map //emit an event to say the contract has been created and funded emit contractCreated(address(i), msg.value, _payoutValue); //now that contract has been created, we need to fund it with enough LINK tokens to fulfil 1 Oracle request per day, with a small buffer added LinkTokenInterface link = LinkTokenInterface(i.getChainlinkToken()); link.transfer(address(i), ((_duration.div(DAY_IN_SECONDS)) + 2) * ORACLE_PAYMENT.mul(2)); return address(i); } /** * @dev returns the contract for a given address */ function getContract(address _contract) external view returns (InsuranceContract) { return contracts[_contract]; } /** * @dev updates the contract for a given address */ function updateContract(address _contract) external { InsuranceContract i = InsuranceContract(_contract); i.updateContract(); } /** * @dev gets the current rainfall for a given contract address */ function getContractRainfall(address _contract) external view returns(uint) { InsuranceContract i = InsuranceContract(_contract); return i.getCurrentRainfall(); } /** * @dev gets the current rainfall for a given contract address */ function getContractRequestCount(address _contract) external view returns(uint) { InsuranceContract i = InsuranceContract(_contract); return i.getRequestCount(); } /** * @dev Get the insurer address for this insurance provider */ function getInsurer() external view returns (address) { return insurer; } /** * @dev Get the status of a given Contract */ function getContractStatus(address _address) external view returns (bool) { InsuranceContract i = InsuranceContract(_address); return i.getContractStatus(); } /** * @dev Return how much ether is in this master contract */ function getContractBalance() external view returns (uint) { return address(this).balance; } /** * @dev Function to end provider contract, in case of bugs or needing to update logic etc, funds are returned to insurance provider, including any remaining LINK tokens */ function endContractProvider() external payable onlyOwner() { LinkTokenInterface link = LinkTokenInterface(LINK_KOVAN); require(link.transfer(msg.sender, link.balanceOf(address(this))), "Unable to transfer"); selfdestruct(insurer); } /** * Returns the latest price */ function getLatestPrice() public view returns (int) { ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed.latestRoundData(); // If the round is not complete yet, timestamp is 0 require(timeStamp > 0, "Round not complete"); return price; } /** * @dev fallback function, to receive ether */ function() external payable { } } contract InsuranceContract is ChainlinkClient, Ownable { using SafeMathChainlink for uint; AggregatorV3Interface internal priceFeed; uint public constant DAY_IN_SECONDS = 60; //How many seconds in a day. 60 for testing, 86400 for Production uint public constant DROUGHT_DAYS_THRESDHOLD = 3 ; //Number of consecutive days without rainfall to be defined as a drought uint256 private oraclePaymentAmount; address public insurer; address client; uint startDate; uint duration; uint premium; uint payoutValue; string cropLocation; uint256[2] public currentRainfallList; bytes32[2] public jobIds; address[2] public oracles; string constant WORLD_WEATHER_ONLINE_URL = "http://api.worldweatheronline.com/premium/v1/weather.ashx?"; string constant WORLD_WEATHER_ONLINE_KEY = "629c6dd09bbc4364b7a33810200911"; string constant WORLD_WEATHER_ONLINE_PATH = "data.current_condition.0.precipMM"; string constant OPEN_WEATHER_URL = "https://openweathermap.org/data/2.5/weather?"; string constant OPEN_WEATHER_KEY = "b4e40205aeb3f27b74333393de24ca79"; string constant OPEN_WEATHER_PATH = "rain.1h"; string constant WEATHERBIT_URL = "https://api.weatherbit.io/v2.0/current?"; string constant WEATHERBIT_KEY = "5e05aef07410401fac491b06eb9e8fc8"; string constant WEATHERBIT_PATH = "data.0.precip"; uint daysWithoutRain; //how many days there has been with 0 rain bool contractActive; //is the contract currently active, or has it ended bool contractPaid = false; uint currentRainfall = 0; //what is the current rainfall for the location uint currentRainfallDateChecked = now; //when the last rainfall check was performed uint requestCount = 0; //how many requests for rainfall data have been made so far for this insurance contract uint dataRequestsSent = 0; //variable used to determine if both requests have been sent or not /** * @dev Prevents a function being run unless it's called by Insurance Provider */ modifier onlyOwner() { require(insurer == msg.sender,'Only Insurance provider can do this'); _; } /** * @dev Prevents a function being run unless the Insurance Contract duration has been reached */ modifier onContractEnded() { if (startDate + duration < now) { _; } } /** * @dev Prevents a function being run unless contract is still active */ modifier onContractActive() { require(contractActive == true ,'Contract has ended, cant interact with it anymore'); _; } /** * @dev Prevents a data request to be called unless it's been a day since the last call (to avoid spamming and spoofing results) * apply a tolerance of 2/24 of a day or 2 hours. */ modifier callFrequencyOncePerDay() { require(now.sub(currentRainfallDateChecked) > (DAY_IN_SECONDS.sub(DAY_IN_SECONDS.div(12))),'Can only check rainfall once per day'); _; } event contractCreated(address _insurer, address _client, uint _duration, uint _premium, uint _totalCover); event contractPaidOut(uint _paidTime, uint _totalPaid, uint _finalRainfall); event contractEnded(uint _endTime, uint _totalReturned); event ranfallThresholdReset(uint _rainfall); event dataRequestSent(bytes32 requestId); event dataReceived(uint _rainfall); /** * @dev Creates a new Insurance contract */ constructor(address _client, uint _duration, uint _premium, uint _payoutValue, string _cropLocation, address _link, uint256 _oraclePaymentAmount) payable Ownable() public { //set ETH/USD Price Feed priceFeed = AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331); //initialize variables required for Chainlink Network interaction setChainlinkToken(_link); oraclePaymentAmount = _oraclePaymentAmount; //first ensure insurer has fully funded the contract require(msg.value >= _payoutValue.div(uint(getLatestPrice())), "Not enough funds sent to contract"); //now initialize values for the contract insurer= msg.sender; client = _client; startDate = now ; //contract will be effective immediately on creation duration = _duration; premium = _premium; payoutValue = _payoutValue; daysWithoutRain = 0; contractActive = true; cropLocation = _cropLocation; //set the oracles and jodids to values from nodes on market.link //oracles[0] = 0x240bae5a27233fd3ac5440b5a598467725f7d1cd; //oracles[1] = 0x5b4247e58fe5a54a116e4a3be32b31be7030c8a3; //jobIds[0] = '1bc4f827ff5942eaaa7540b7dd1e20b9'; //jobIds[1] = 'e67ddf1f394d44e79a9a2132efd00050'; //or if you have your own node and job setup you can use it for both requests oracles[0] = 0x05c8fadf1798437c143683e665800d58a42b6e19; oracles[1] = 0x05c8fadf1798437c143683e665800d58a42b6e19; jobIds[0] = 'a17e8fbf4cbf46eeb79e04b3eb864a4e'; jobIds[1] = 'a17e8fbf4cbf46eeb79e04b3eb864a4e'; emit contractCreated(insurer, client, duration, premium, payoutValue); } /** * @dev Calls out to an Oracle to obtain weather data */ function updateContract() public onContractActive() returns (bytes32 requestId) { //first call end contract in case of insurance contract duration expiring, if it hasn't then this functin execution will resume checkEndContract(); //contract may have been marked inactive above, only do request if needed if (contractActive) { dataRequestsSent = 0; //First build up a request to World Weather Online to get the current rainfall string memory url = string(abi.encodePacked(WORLD_WEATHER_ONLINE_URL, "key=",WORLD_WEATHER_ONLINE_KEY,"&q=",cropLocation,"&format=json&num_of_days=1")); checkRainfall(oracles[0], jobIds[0], url, WORLD_WEATHER_ONLINE_PATH); // Now build up the second request to WeatherBit url = string(abi.encodePacked(WEATHERBIT_URL, "city=",cropLocation,"&key=",WEATHERBIT_KEY)); checkRainfall(oracles[1], jobIds[1], url, WEATHERBIT_PATH); } } /** * @dev Calls out to an Oracle to obtain weather data */ function checkRainfall(address _oracle, bytes32 _jobId, string _url, string _path) private onContractActive() returns (bytes32 requestId) { //First build up a request to get the current rainfall Chainlink.Request memory req = buildChainlinkRequest(_jobId, address(this), this.checkRainfallCallBack.selector); req.add("get", _url); //sends the GET request to the oracle req.add("path", _path); req.addInt("times", 100); requestId = sendChainlinkRequestTo(_oracle, req, oraclePaymentAmount); emit dataRequestSent(requestId); } /** * @dev Callback function - This gets called by the Oracle Contract when the Oracle Node passes data back to the Oracle Contract * The function will take the rainfall given by the Oracle and updated the Inusrance Contract state */ function checkRainfallCallBack(bytes32 _requestId, uint256 _rainfall) public recordChainlinkFulfillment(_requestId) onContractActive() callFrequencyOncePerDay() { //set current temperature to value returned from Oracle, and store date this was retrieved (to avoid spam and gaming the contract) currentRainfallList[dataRequestsSent] = _rainfall; dataRequestsSent = dataRequestsSent + 1; //set current rainfall to average of both values if (dataRequestsSent > 1) { currentRainfall = (currentRainfallList[0].add(currentRainfallList[1]).div(2)); currentRainfallDateChecked = now; requestCount +=1; //check if payout conditions have been met, if so call payoutcontract, which should also end/kill contract at the end if (currentRainfall == 0 ) { //temp threshold has been met, add a day of over threshold daysWithoutRain += 1; } else { //there was rain today, so reset daysWithoutRain parameter daysWithoutRain = 0; emit ranfallThresholdReset(currentRainfall); } if (daysWithoutRain >= DROUGHT_DAYS_THRESDHOLD) { // day threshold has been met //need to pay client out insurance amount payOutContract(); } } emit dataReceived(_rainfall); } /** * @dev Insurance conditions have been met, do payout of total cover amount to client */ function payOutContract() private onContractActive() { //Transfer agreed amount to client client.transfer(address(this).balance); //Transfer any remaining funds (premium) back to Insurer LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress()); require(link.transfer(insurer, link.balanceOf(address(this))), "Unable to transfer"); emit contractPaidOut(now, payoutValue, currentRainfall); //now that amount has been transferred, can end the contract //mark contract as ended, so no future calls can be done contractActive = false; contractPaid = true; } /** * @dev Insurance conditions have not been met, and contract expired, end contract and return funds */ function checkEndContract() private onContractEnded() { //Insurer needs to have performed at least 1 weather call per day to be eligible to retrieve funds back. //We will allow for 1 missed weather call to account for unexpected issues on a given day. if (requestCount >= (duration.div(DAY_IN_SECONDS) - 2)) { //return funds back to insurance provider then end/kill the contract insurer.transfer(address(this).balance); } else { //insurer hasn't done the minimum number of data requests, client is eligible to receive his premium back // need to use ETH/USD price feed to calculate ETH amount client.transfer(premium.div(uint(getLatestPrice()))); insurer.transfer(address(this).balance); } //transfer any remaining LINK tokens back to the insurer LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress()); require(link.transfer(insurer, link.balanceOf(address(this))), "Unable to transfer remaining LINK tokens"); //mark contract as ended, so no future state changes can occur on the contract contractActive = false; emit contractEnded(now, address(this).balance); } /** * Returns the latest price */ function getLatestPrice() public view returns (int) { ( uint80 roundID, int price, uint startedAt, uint timeStamp, uint80 answeredInRound ) = priceFeed.latestRoundData(); // If the round is not complete yet, timestamp is 0 require(timeStamp > 0, "Round not complete"); return price; } /** * @dev Get the balance of the contract */ function getContractBalance() external view returns (uint) { return address(this).balance; } /** * @dev Get the Crop Location */ function getLocation() external view returns (string) { return cropLocation; } /** * @dev Get the Total Cover */ function getPayoutValue() external view returns (uint) { return payoutValue; } /** * @dev Get the Premium paid */ function getPremium() external view returns (uint) { return premium; } /** * @dev Get the status of the contract */ function getContractStatus() external view returns (bool) { return contractActive; } /** * @dev Get whether the contract has been paid out or not */ function getContractPaid() external view returns (bool) { return contractPaid; } /** * @dev Get the current recorded rainfall for the contract */ function getCurrentRainfall() external view returns (uint) { return currentRainfall; } /** * @dev Get the recorded number of days without rain */ function getDaysWithoutRain() external view returns (uint) { return daysWithoutRain; } /** * @dev Get the count of requests that has occured for the Insurance Contract */ function getRequestCount() external view returns (uint) { return requestCount; } /** * @dev Get the last time that the rainfall was checked for the contract */ function getCurrentRainfallDateChecked() external view returns (uint) { return currentRainfallDateChecked; } /** * @dev Get the contract duration */ function getDuration() external view returns (uint) { return duration; } /** * @dev Get the contract start date */ function getContractStartDate() external view returns (uint) { return startDate; } /** * @dev Get the current date/time according to the blockchain */ function getNow() external view returns (uint) { return now; } /** * @dev Get address of the chainlink token */ function getChainlinkToken() public view returns (address) { return chainlinkTokenAddress(); } /** * @dev Helper function for converting a string to a bytes32 object */ function stringToBytes32(string memory source) private pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { // solhint-disable-line no-inline-assembly result := mload(add(source, 32)) } } /** * @dev Helper function for converting uint to a string */ function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } /** * @dev Fallback function so contrat can receive ether when required */ function() external payable { } }
sends the GET request to the oracle
req.add("get", _url);
2,519,556
[ 1, 4661, 87, 326, 4978, 590, 358, 326, 20865, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1111, 18, 1289, 2932, 588, 3113, 389, 718, 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.7; /* Author: Patrick Lismore @patricklismore */ // Basic Atlas Employment Contract contract AtlasBasicWork{ /* Define variable owner of the type address*/ address owner; /* Define jobidentifer of type string */ string public jobidentifer; /* Define client address of type address */ address public client; /* Define worker address of type address */ address public worker; /* authorised address */ address public authorised; /* State of Smart Contract */ enum State { Created, InProgress, InDispute, Delivered, NotRecieved, Complete, Inactive } /* State of contract status */ State public state; modifier condition(bool _condition) { require(_condition); _; } modifier onlyClient() { require( msg.sender == client, "Only client can call this." ); _; } modifier onlyWorker() { require( msg.sender == worker, "Only worker can call this." ); _; } modifier inState(State _state) { require( state == _state, "Invalid state." ); _; } event Aborted(); event JobConfirmed(); event WorkReceived(); event WordDelivered(); event WordNotRecieved(); /* Contract constructor for basic work smart contract */ constructor(string jobId, address clientAddress, address workerAddress) payable{ jobidentifer = jobId; client = clientAddress; worker = workerAddress; owner = msg.sender; } /// Abort the purchase and reclaim the WORK. /// Can only be called by the seller before /// the contract is locked. function abort() public onlyClient inState(State.Created) { emit Aborted(); state = State.Inactive; client.transfer(this.balance); } /// Confirm the job as Worker /// The WORK will be locked until confirmWorkReceived /// is called. function confirmJob() public onlyWorker inState(State.Created) payable { emit JobConfirmed(); state = State.InProgress; } /// Confirm that you (the Client) received the work commissioned. /// This will release the locked WORK. function confirmWorkDelivered() public onlyWorker inState(State.InProgress) { emit WordDelivered(); state = State.Delivered; } /// Confirm that you (the Client) received the work commissioned. /// This will release the locked WORK. function confirmWorkReceived() public onlyClient inState(State.Delivered) payable { emit WorkReceived(); // It is important to change the state first because // otherwise, the contracts called using `send` below // can call in again here. state = State.Complete; //worker.transfer(value); worker.transfer(this.balance); } /* Function called by worker when job has been delivered awaiting client review */ function workNotRecieved() public onlyClient inState(State.InProgress) { emit WordNotRecieved(); state = State.NotRecieved; } /* Returns the value of WORK locked in contract */ function contractBalance() constant returns (uint256 amount){ return this.balance; } /* Function to recover the funds on the contract */ function KillRecoverDispute() public { if (msg.sender == owner) selfdestruct(owner); } }
Function called by worker when job has been delivered awaiting client review */
function workNotRecieved() public onlyClient inState(State.InProgress) { emit WordNotRecieved(); state = State.NotRecieved; }
12,858,308
[ 1, 2083, 2566, 635, 4322, 1347, 1719, 711, 2118, 22112, 4273, 310, 1004, 10725, 225, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1440, 1248, 5650, 1385, 2155, 1435, 1071, 1338, 1227, 316, 1119, 12, 1119, 18, 13434, 13, 203, 565, 288, 203, 3639, 3626, 9926, 1248, 5650, 1385, 2155, 5621, 203, 3639, 919, 273, 3287, 18, 1248, 5650, 1385, 2155, 31, 203, 565, 289, 203, 377, 203, 377, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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: 0x198cf24375eccdf599c624d10f0c6fb9b75ec215 //Contract name: Hold //Balance: 0 Ether //Verification Date: 3/10/2018 //Transacion Count: 6 // CODE STARTS HERE pragma solidity ^0.4.18; /** * @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; } } /* * Manager that stores permitted addresses */ contract PermissionManager is Ownable { mapping (address => bool) permittedAddresses; function addAddress(address newAddress) public onlyOwner { permittedAddresses[newAddress] = true; } function removeAddress(address remAddress) public onlyOwner { permittedAddresses[remAddress] = false; } function isPermitted(address pAddress) public view returns(bool) { if (permittedAddresses[pAddress]) { return true; } return false; } } contract Registry is Ownable { struct ContributorData { bool isActive; uint contributionETH; uint contributionUSD; uint tokensIssued; uint quoteUSD; uint contributionRNTB; } mapping(address => ContributorData) public contributorList; mapping(uint => address) private contributorIndexes; uint private nextContributorIndex; /* Permission manager contract */ PermissionManager public permissionManager; bool public completed; modifier onlyPermitted() { require(permissionManager.isPermitted(msg.sender)); _; } event ContributionAdded(address _contributor, uint overallEth, uint overallUSD, uint overallToken, uint quote); event ContributionEdited(address _contributor, uint overallEth, uint overallUSD, uint overallToken, uint quote); function Registry(address pManager) public { permissionManager = PermissionManager(pManager); completed = false; } function setPermissionManager(address _permadr) public onlyOwner { require(_permadr != 0x0); permissionManager = PermissionManager(_permadr); } function isActiveContributor(address contributor) public view returns(bool) { return contributorList[contributor].isActive; } function removeContribution(address contributor) public onlyPermitted { contributorList[contributor].isActive = false; } function setCompleted(bool compl) public onlyPermitted { completed = compl; } function addContribution(address _contributor, uint _amount, uint _amusd, uint _tokens, uint _quote ) public onlyPermitted { if (contributorList[_contributor].isActive == false) { contributorList[_contributor].isActive = true; contributorList[_contributor].contributionETH = _amount; contributorList[_contributor].contributionUSD = _amusd; contributorList[_contributor].tokensIssued = _tokens; contributorList[_contributor].quoteUSD = _quote; contributorIndexes[nextContributorIndex] = _contributor; nextContributorIndex++; } else { contributorList[_contributor].contributionETH += _amount; contributorList[_contributor].contributionUSD += _amusd; contributorList[_contributor].tokensIssued += _tokens; contributorList[_contributor].quoteUSD = _quote; } ContributionAdded(_contributor, contributorList[_contributor].contributionETH, contributorList[_contributor].contributionUSD, contributorList[_contributor].tokensIssued, contributorList[_contributor].quoteUSD); } function editContribution(address _contributor, uint _amount, uint _amusd, uint _tokens, uint _quote) public onlyPermitted { if (contributorList[_contributor].isActive == true) { contributorList[_contributor].contributionETH = _amount; contributorList[_contributor].contributionUSD = _amusd; contributorList[_contributor].tokensIssued = _tokens; contributorList[_contributor].quoteUSD = _quote; } ContributionEdited(_contributor, contributorList[_contributor].contributionETH, contributorList[_contributor].contributionUSD, contributorList[_contributor].tokensIssued, contributorList[_contributor].quoteUSD); } function addContributor(address _contributor, uint _amount, uint _amusd, uint _tokens, uint _quote) public onlyPermitted { contributorList[_contributor].isActive = true; contributorList[_contributor].contributionETH = _amount; contributorList[_contributor].contributionUSD = _amusd; contributorList[_contributor].tokensIssued = _tokens; contributorList[_contributor].quoteUSD = _quote; contributorIndexes[nextContributorIndex] = _contributor; nextContributorIndex++; ContributionAdded(_contributor, contributorList[_contributor].contributionETH, contributorList[_contributor].contributionUSD, contributorList[_contributor].tokensIssued, contributorList[_contributor].quoteUSD); } function getContributionETH(address _contributor) public view returns (uint) { return contributorList[_contributor].contributionETH; } function getContributionUSD(address _contributor) public view returns (uint) { return contributorList[_contributor].contributionUSD; } function getContributionRNTB(address _contributor) public view returns (uint) { return contributorList[_contributor].contributionRNTB; } function getContributionTokens(address _contributor) public view returns (uint) { return contributorList[_contributor].tokensIssued; } function addRNTBContribution(address _contributor, uint _amount) public onlyPermitted { if (contributorList[_contributor].isActive == false) { contributorList[_contributor].isActive = true; contributorList[_contributor].contributionRNTB = _amount; contributorIndexes[nextContributorIndex] = _contributor; nextContributorIndex++; } else { contributorList[_contributor].contributionETH += _amount; } } function getContributorByIndex(uint index) public view returns (address) { return contributorIndexes[index]; } function getContributorAmount() public view returns(uint) { return nextContributorIndex; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Contract that will work with ERC223 tokens. */ contract ERC223ReceivingContract { struct TKN { address sender; uint value; bytes data; bytes4 sig; } /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data) public pure { TKN memory tkn; tkn.sender = _from; tkn.value = _value; tkn.data = _data; if(_data.length > 0) { uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); tkn.sig = bytes4(u); } /* tkn variable is analogue of msg variable of Ether transaction * tkn.sender is person who initiated this token transaction (analogue of msg.sender) * tkn.value the number of tokens that were sent (analogue of msg.value) * tkn.data is data of token transaction (analogue of msg.data) * tkn.sig is 4 bytes signature of function * if data of token transaction is a function execution */ } } contract ERC223Interface { uint public totalSupply; function balanceOf(address who) public view returns (uint); function allowedAddressesOf(address who) public view returns (bool); function getTotalSupply() public view returns (uint); function transfer(address to, uint value) public returns (bool ok); function transfer(address to, uint value, bytes data) public returns (bool ok); function transfer(address to, uint value, bytes data, string custom_fallback) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value, bytes data); event TransferContract(address indexed from, address indexed to, uint value, bytes data); } /** * @title Unity Token is ERC223 token. * @author Vladimir Kovalchuk */ contract UnityToken is ERC223Interface { using SafeMath for uint; string public constant name = "Unity Token"; string public constant symbol = "UNT"; uint8 public constant decimals = 18; /* The supply is initially 100UNT to the precision of 18 decimals */ uint public constant INITIAL_SUPPLY = 100000 * (10 ** uint(decimals)); mapping(address => uint) balances; // List of user balances. mapping(address => bool) allowedAddresses; modifier onlyOwner() { require(msg.sender == owner); _; } function addAllowed(address newAddress) public onlyOwner { allowedAddresses[newAddress] = true; } function removeAllowed(address remAddress) public onlyOwner { allowedAddresses[remAddress] = false; } address public owner; /* Constructor initializes the owner's balance and the supply */ function UnityToken() public { owner = msg.sender; totalSupply = INITIAL_SUPPLY; balances[owner] = INITIAL_SUPPLY; } function getTotalSupply() public view returns (uint) { return totalSupply; } // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint _value, bytes _data, string _custom_fallback) public returns (bool success) { if (isContract(_to)) { require(allowedAddresses[_to]); if (balanceOf(msg.sender) < _value) revert(); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data)); TransferContract(msg.sender, _to, _value, _data); return true; } else { return transferToAddress(_to, _value, _data); } } // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint _value, bytes _data) public returns (bool success) { if (isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . function transfer(address _to, uint _value) public returns (bool success) { //standard function transfer similar to ERC20 transfer with no _data //added due to backwards compatibility reasons bytes memory empty; if (isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } //assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length > 0); } //function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) { if (balanceOf(msg.sender) < _value) revert(); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value, _data); return true; } //function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { require(allowedAddresses[_to]); if (balanceOf(msg.sender) < _value) revert(); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); TransferContract(msg.sender, _to, _value, _data); return true; } function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } function allowedAddressesOf(address _owner) public view returns (bool allowed) { return allowedAddresses[_owner]; } } /** * @title Hold contract. * @author Vladimir Kovalchuk */ contract Hold is Ownable { uint8 stages = 5; uint8 public percentage; uint8 public currentStage; uint public initialBalance; uint public withdrawed; address public multisig; Registry registry; PermissionManager public permissionManager; uint nextContributorToTransferEth; address public observer; uint dateDeployed; mapping(address => bool) private hasWithdrawedEth; event InitialBalanceChanged(uint balance); event EthReleased(uint ethreleased); event EthRefunded(address contributor, uint ethrefunded); event StageChanged(uint8 newStage); event EthReturnedToOwner(address owner, uint balance); modifier onlyPermitted() { require(permissionManager.isPermitted(msg.sender) || msg.sender == owner); _; } modifier onlyObserver() { require(msg.sender == observer || msg.sender == owner); _; } function Hold(address _multisig, uint cap, address pm, address registryAddress, address observerAddr) public { percentage = 100 / stages; currentStage = 0; multisig = _multisig; initialBalance = cap; dateDeployed = now; permissionManager = PermissionManager(pm); registry = Registry(registryAddress); observer = observerAddr; } function setPermissionManager(address _permadr) public onlyOwner { require(_permadr != 0x0); permissionManager = PermissionManager(_permadr); } function setObserver(address observerAddr) public onlyOwner { require(observerAddr != 0x0); observer = observerAddr; } function setInitialBalance(uint inBal) public { initialBalance = inBal; InitialBalanceChanged(inBal); } function releaseAllETH() onlyPermitted public { uint balReleased = getBalanceReleased(); require(balReleased > 0); require(this.balance >= balReleased); multisig.transfer(balReleased); withdrawed += balReleased; EthReleased(balReleased); } function releaseETH(uint n) onlyPermitted public { require(this.balance >= n); require(getBalanceReleased() >= n); multisig.transfer(n); withdrawed += n; EthReleased(n); } function getBalance() public view returns (uint) { return this.balance; } function changeStageAndReleaseETH() public onlyObserver { uint8 newStage = currentStage + 1; require(newStage <= stages); currentStage = newStage; StageChanged(newStage); releaseAllETH(); } function changeStage() public onlyObserver { uint8 newStage = currentStage + 1; require(newStage <= stages); currentStage = newStage; StageChanged(newStage); } function getBalanceReleased() public view returns (uint) { return initialBalance * percentage * currentStage / 100 - withdrawed ; } function returnETHByOwner() public onlyOwner { require(now > dateDeployed + 183 days); uint balance = getBalance(); owner.transfer(getBalance()); EthReturnedToOwner(owner, balance); } function refund(uint _numberOfReturns) public onlyOwner { require(_numberOfReturns > 0); address currentParticipantAddress; for (uint cnt = 0; cnt < _numberOfReturns; cnt++) { currentParticipantAddress = registry.getContributorByIndex(nextContributorToTransferEth); if (currentParticipantAddress == 0x0) return; if (!hasWithdrawedEth[currentParticipantAddress]) { uint EthAmount = registry.getContributionETH(currentParticipantAddress); EthAmount -= EthAmount * (percentage / 100 * currentStage); currentParticipantAddress.transfer(EthAmount); EthRefunded(currentParticipantAddress, EthAmount); hasWithdrawedEth[currentParticipantAddress] = true; } nextContributorToTransferEth += 1; } } function() public payable { } function getWithdrawed(address contrib) public onlyPermitted view returns (bool) { return hasWithdrawedEth[contrib]; } }
Permission manager contract */
PermissionManager public permissionManager;
1,008,434
[ 1, 5041, 3301, 6835, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 8509, 1318, 1071, 4132, 1318, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x977D360c3FbE1533eFEde3619dC74Ad0950FFc4f/sources/contracts/BondSwap/Exchange/libraries/BondConfig.sol
token that we buy bonds for
address bondToken;
16,426,719
[ 1, 2316, 716, 732, 30143, 15692, 364, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 202, 2867, 8427, 1345, 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 ]
// Verified using https://dapp.tools // hevm: flattened sources of /nix/store/fs14a1fn2n0n355szi63iq33n5yzygnk-geb/dapp/geb/src/StabilityFeeTreasury.sol pragma solidity =0.6.7; ////// /nix/store/fs14a1fn2n0n355szi63iq33n5yzygnk-geb/dapp/geb/src/StabilityFeeTreasury.sol /// StabilityFeeTreasury.sol // Copyright (C) 2018 Rain <[email protected]>, 2020 Reflexer Labs, INC // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /* pragma solidity 0.6.7; */ abstract contract SAFEEngineLike_10 { function approveSAFEModification(address) virtual external; function denySAFEModification(address) virtual external; function transferInternalCoins(address,address,uint256) virtual external; function settleDebt(uint256) virtual external; function coinBalance(address) virtual public view returns (uint256); function debtBalance(address) virtual public view returns (uint256); } abstract contract SystemCoinLike { function balanceOf(address) virtual public view returns (uint256); function approve(address, uint256) virtual public returns (uint256); function transfer(address,uint256) virtual public returns (bool); function transferFrom(address,address,uint256) virtual public returns (bool); } abstract contract CoinJoinLike { function systemCoin() virtual public view returns (address); function join(address, uint256) virtual external; } contract StabilityFeeTreasury { // --- Auth --- mapping (address => uint256) public authorizedAccounts; /** * @notice Add auth to an account * @param account Account to add auth to */ function addAuthorization(address account) external isAuthorized { authorizedAccounts[account] = 1; emit AddAuthorization(account); } /** * @notice Remove auth from an account * @param account Account to remove auth from */ function removeAuthorization(address account) external isAuthorized { authorizedAccounts[account] = 0; emit RemoveAuthorization(account); } /** * @notice Checks whether msg.sender can call an authed function **/ modifier isAuthorized { require(authorizedAccounts[msg.sender] == 1, "StabilityFeeTreasury/account-not-authorized"); _; } // --- Events --- event AddAuthorization(address account); event RemoveAuthorization(address account); event ModifyParameters(bytes32 parameter, address addr); event ModifyParameters(bytes32 parameter, uint256 val); event DisableContract(); event SetTotalAllowance(address indexed account, uint256 rad); event SetPerBlockAllowance(address indexed account, uint256 rad); event GiveFunds(address indexed account, uint256 rad, uint256 expensesAccumulator); event TakeFunds(address indexed account, uint256 rad); event PullFunds(address indexed sender, address indexed dstAccount, address token, uint256 rad, uint256 expensesAccumulator); event TransferSurplusFunds(address extraSurplusReceiver, uint256 fundsToTransfer); // --- Structs --- struct Allowance { uint256 total; uint256 perBlock; } // Mapping of total and per block allowances mapping(address => Allowance) private allowance; // Mapping that keeps track of how much surplus an authorized address has pulled each block mapping(address => mapping(uint256 => uint256)) public pulledPerBlock; SAFEEngineLike_10 public safeEngine; SystemCoinLike public systemCoin; CoinJoinLike public coinJoin; // The address that receives any extra surplus which is not used by the treasury address public extraSurplusReceiver; uint256 public treasuryCapacity; // max amount of SF that can be kept in the treasury [rad] uint256 public minimumFundsRequired; // minimum amount of SF that must be kept in the treasury at all times [rad] uint256 public expensesMultiplier; // multiplier for expenses [hundred] uint256 public surplusTransferDelay; // minimum time between transferSurplusFunds calls [seconds] uint256 public expensesAccumulator; // expenses accumulator [rad] uint256 public accumulatorTag; // latest tagged accumulator price [rad] uint256 public pullFundsMinThreshold; // minimum funds that must be in the treasury so that someone can pullFunds [rad] uint256 public latestSurplusTransferTime; // latest timestamp when transferSurplusFunds was called [seconds] uint256 public contractEnabled; modifier accountNotTreasury(address account) { require(account != address(this), "StabilityFeeTreasury/account-cannot-be-treasury"); _; } constructor( address safeEngine_, address extraSurplusReceiver_, address coinJoin_ ) public { require(address(CoinJoinLike(coinJoin_).systemCoin()) != address(0), "StabilityFeeTreasury/null-system-coin"); require(extraSurplusReceiver_ != address(0), "StabilityFeeTreasury/null-surplus-receiver"); authorizedAccounts[msg.sender] = 1; safeEngine = SAFEEngineLike_10(safeEngine_); extraSurplusReceiver = extraSurplusReceiver_; coinJoin = CoinJoinLike(coinJoin_); systemCoin = SystemCoinLike(coinJoin.systemCoin()); latestSurplusTransferTime = now; expensesMultiplier = HUNDRED; contractEnabled = 1; systemCoin.approve(address(coinJoin), uint256(-1)); emit AddAuthorization(msg.sender); } // --- Math --- uint256 constant HUNDRED = 10 ** 2; uint256 constant RAY = 10 ** 27; function addition(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x + y; require(z >= x, "StabilityFeeTreasury/add-uint-uint-overflow"); } function addition(int256 x, int256 y) internal pure returns (int256 z) { z = x + y; if (y <= 0) require(z <= x, "StabilityFeeTreasury/add-int-int-underflow"); if (y > 0) require(z > x, "StabilityFeeTreasury/add-int-int-overflow"); } function subtract(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "StabilityFeeTreasury/sub-uint-uint-underflow"); } function subtract(int256 x, int256 y) internal pure returns (int256 z) { z = x - y; require(y <= 0 || z <= x, "StabilityFeeTreasury/sub-int-int-underflow"); require(y >= 0 || z >= x, "StabilityFeeTreasury/sub-int-int-overflow"); } function multiply(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "StabilityFeeTreasury/mul-uint-uint-overflow"); } function divide(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y > 0, "StabilityFeeTreasury/div-y-null"); z = x / y; require(z <= x, "StabilityFeeTreasury/div-invalid"); } function minimum(uint256 x, uint256 y) internal view returns (uint256 z) { z = (x <= y) ? x : y; } // --- Administration --- /** * @notice Modify address parameters * @param parameter The name of the contract whose address will be changed * @param addr New address for the contract */ function modifyParameters(bytes32 parameter, address addr) external isAuthorized { require(contractEnabled == 1, "StabilityFeeTreasury/contract-not-enabled"); require(addr != address(0), "StabilityFeeTreasury/null-addr"); if (parameter == "extraSurplusReceiver") { require(addr != address(this), "StabilityFeeTreasury/accounting-engine-cannot-be-treasury"); extraSurplusReceiver = addr; } else revert("StabilityFeeTreasury/modify-unrecognized-param"); emit ModifyParameters(parameter, addr); } /** * @notice Modify uint256 parameters * @param parameter The name of the parameter to modify * @param val New parameter value */ function modifyParameters(bytes32 parameter, uint256 val) external isAuthorized { require(contractEnabled == 1, "StabilityFeeTreasury/not-live"); if (parameter == "expensesMultiplier") expensesMultiplier = val; else if (parameter == "treasuryCapacity") { require(val >= minimumFundsRequired, "StabilityFeeTreasury/capacity-lower-than-min-funds"); treasuryCapacity = val; } else if (parameter == "minimumFundsRequired") { require(val <= treasuryCapacity, "StabilityFeeTreasury/min-funds-higher-than-capacity"); minimumFundsRequired = val; } else if (parameter == "pullFundsMinThreshold") { pullFundsMinThreshold = val; } else if (parameter == "surplusTransferDelay") surplusTransferDelay = val; else revert("StabilityFeeTreasury/modify-unrecognized-param"); emit ModifyParameters(parameter, val); } /** * @notice Disable this contract (normally called by GlobalSettlement) */ function disableContract() external isAuthorized { require(contractEnabled == 1, "StabilityFeeTreasury/already-disabled"); contractEnabled = 0; joinAllCoins(); safeEngine.transferInternalCoins(address(this), extraSurplusReceiver, safeEngine.coinBalance(address(this))); emit DisableContract(); } // --- Utils --- function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } /** * @notice Join all ERC20 system coins that the treasury has inside the SAFEEngine */ function joinAllCoins() internal { if (systemCoin.balanceOf(address(this)) > 0) { coinJoin.join(address(this), systemCoin.balanceOf(address(this))); } } /* * @notice Settle as much bad debt as possible (if this contract has any) */ function settleDebt() public { uint256 coinBalanceSelf = safeEngine.coinBalance(address(this)); uint256 debtBalanceSelf = safeEngine.debtBalance(address(this)); if (debtBalanceSelf > 0) { safeEngine.settleDebt(minimum(coinBalanceSelf, debtBalanceSelf)); } } // --- Getters --- /* * @notice Returns the total and per block allowances for a specific address * @param account The address to return the allowances for */ function getAllowance(address account) public view returns (uint256, uint256) { return (allowance[account].total, allowance[account].perBlock); } // --- SF Transfer Allowance --- /** * @notice Modify an address' total allowance in order to withdraw SF from the treasury * @param account The approved address * @param rad The total approved amount of SF to withdraw (number with 45 decimals) */ function setTotalAllowance(address account, uint256 rad) external isAuthorized accountNotTreasury(account) { require(account != address(0), "StabilityFeeTreasury/null-account"); allowance[account].total = rad; emit SetTotalAllowance(account, rad); } /** * @notice Modify an address' per block allowance in order to withdraw SF from the treasury * @param account The approved address * @param rad The per block approved amount of SF to withdraw (number with 45 decimals) */ function setPerBlockAllowance(address account, uint256 rad) external isAuthorized accountNotTreasury(account) { require(account != address(0), "StabilityFeeTreasury/null-account"); allowance[account].perBlock = rad; emit SetPerBlockAllowance(account, rad); } // --- Stability Fee Transfer (Governance) --- /** * @notice Governance transfers SF to an address * @param account Address to transfer SF to * @param rad Amount of internal system coins to transfer (a number with 45 decimals) */ function giveFunds(address account, uint256 rad) external isAuthorized accountNotTreasury(account) { require(account != address(0), "StabilityFeeTreasury/null-account"); joinAllCoins(); settleDebt(); require(safeEngine.debtBalance(address(this)) == 0, "StabilityFeeTreasury/outstanding-bad-debt"); require(safeEngine.coinBalance(address(this)) >= rad, "StabilityFeeTreasury/not-enough-funds"); if (account != extraSurplusReceiver) { expensesAccumulator = addition(expensesAccumulator, rad); } safeEngine.transferInternalCoins(address(this), account, rad); emit GiveFunds(account, rad, expensesAccumulator); } /** * @notice Governance takes funds from an address * @param account Address to take system coins from * @param rad Amount of internal system coins to take from the account (a number with 45 decimals) */ function takeFunds(address account, uint256 rad) external isAuthorized accountNotTreasury(account) { safeEngine.transferInternalCoins(account, address(this), rad); emit TakeFunds(account, rad); } // --- Stability Fee Transfer (Approved Accounts) --- /** * @notice Pull stability fees from the treasury (if your allowance permits) * @param dstAccount Address to transfer funds to * @param token Address of the token to transfer (in this case it must be the address of the ERC20 system coin). * Used only to adhere to a standard for automated, on-chain treasuries * @param wad Amount of system coins (SF) to transfer (expressed as an 18 decimal number but the contract will transfer internal system coins that have 45 decimals) */ function pullFunds(address dstAccount, address token, uint256 wad) external { if (dstAccount == address(this)) return; require(allowance[msg.sender].total >= multiply(wad, RAY), "StabilityFeeTreasury/not-allowed"); require(dstAccount != address(0), "StabilityFeeTreasury/null-dst"); require(dstAccount != extraSurplusReceiver, "StabilityFeeTreasury/dst-cannot-be-accounting"); require(wad > 0, "StabilityFeeTreasury/null-transfer-amount"); require(token == address(systemCoin), "StabilityFeeTreasury/token-unavailable"); if (allowance[msg.sender].perBlock > 0) { require(addition(pulledPerBlock[msg.sender][block.number], multiply(wad, RAY)) <= allowance[msg.sender].perBlock, "StabilityFeeTreasury/per-block-limit-exceeded"); } pulledPerBlock[msg.sender][block.number] = addition(pulledPerBlock[msg.sender][block.number], multiply(wad, RAY)); joinAllCoins(); settleDebt(); require(safeEngine.debtBalance(address(this)) == 0, "StabilityFeeTreasury/outstanding-bad-debt"); require(safeEngine.coinBalance(address(this)) >= multiply(wad, RAY), "StabilityFeeTreasury/not-enough-funds"); require(safeEngine.coinBalance(address(this)) >= pullFundsMinThreshold, "StabilityFeeTreasury/below-pullFunds-min-threshold"); // Update allowance and accumulator allowance[msg.sender].total = subtract(allowance[msg.sender].total, multiply(wad, RAY)); expensesAccumulator = addition(expensesAccumulator, multiply(wad, RAY)); // Transfer money safeEngine.transferInternalCoins(address(this), dstAccount, multiply(wad, RAY)); emit PullFunds(msg.sender, dstAccount, token, multiply(wad, RAY), expensesAccumulator); } // --- Treasury Maintenance --- /** * @notice Transfer surplus stability fees to the extraSurplusReceiver. This is here to make sure that the treasury doesn't accumulate fees that it doesn't even need in order to pay for allowances. It ensures that there are enough funds left in the treasury to account for projected expenses (latest expenses multiplied by an expense multiplier) */ function transferSurplusFunds() external { require(now >= addition(latestSurplusTransferTime, surplusTransferDelay), "StabilityFeeTreasury/transfer-cooldown-not-passed"); // Compute latest expenses uint256 latestExpenses = subtract(expensesAccumulator, accumulatorTag); // Check if we need to keep more funds than the total capacity uint256 remainingFunds = (treasuryCapacity <= divide(multiply(expensesMultiplier, latestExpenses), HUNDRED)) ? divide(multiply(expensesMultiplier, latestExpenses), HUNDRED) : treasuryCapacity; // Make sure to keep at least minimum funds remainingFunds = (divide(multiply(expensesMultiplier, latestExpenses), HUNDRED) <= minimumFundsRequired) ? minimumFundsRequired : remainingFunds; // Set internal vars accumulatorTag = expensesAccumulator; latestSurplusTransferTime = now; // Join all coins in system joinAllCoins(); // Settle outstanding bad debt settleDebt(); // Check that there's no bad debt left require(safeEngine.debtBalance(address(this)) == 0, "StabilityFeeTreasury/outstanding-bad-debt"); // Check if we have too much money if (safeEngine.coinBalance(address(this)) > remainingFunds) { // Make sure that we still keep min SF in treasury uint256 fundsToTransfer = subtract(safeEngine.coinBalance(address(this)), remainingFunds); // Transfer surplus to accounting engine safeEngine.transferInternalCoins(address(this), extraSurplusReceiver, fundsToTransfer); // Emit event emit TransferSurplusFunds(extraSurplusReceiver, fundsToTransfer); } } }
minimum amount of SF that must be kept in the treasury at all times [rad]
uint256 public minimumFundsRequired;
141,504
[ 1, 15903, 3844, 434, 21318, 716, 1297, 506, 16555, 316, 326, 9787, 345, 22498, 622, 777, 4124, 1377, 306, 6012, 65, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 5224, 42, 19156, 3705, 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 ]
./full_match/80001/0x130257B2eB656623fAEcF46F8ec54513aF78EADE/sources/project_/contracts/HogwartsNFT.sol
map the caller to their respective requestIDs.
s_requestIdToSender[requestId] = msg.sender;
9,528,215
[ 1, 1458, 326, 4894, 358, 3675, 17613, 590, 5103, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 272, 67, 2293, 28803, 12021, 63, 2293, 548, 65, 273, 1234, 18, 15330, 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 ]
pragma solidity 0.6.2; import "../Median.sol"; import "../vendor/SafeMath.sol"; import "./SafeMath128.sol"; import "./SafeMath64.sol"; import "./SafeMath32.sol"; import "../interfaces/LinkTokenInterface.sol"; import "../interfaces/WithdrawalInterface.sol"; import "./AggregatorInterface.sol"; import "../Owned.sol"; /** * @title The Prepaid Aggregator contract * @notice Node handles aggregating data pushed in from off-chain, and unlocks * payment for oracles as they report. Oracles' submissions are gathered in * rounds, with each round aggregating the submissions for each oracle into a * single answer. The latest aggregated answer is exposed as well as historical * answers and their updated at timestamp. */ contract PrepaidAggregator is AggregatorInterface, Owned, WithdrawalInterface { using SafeMath for uint256; using SafeMath128 for uint128; using SafeMath64 for uint64; using SafeMath32 for uint32; struct Round { int256 answer; uint64 startedAt; uint64 updatedAt; uint32 answeredInRound; RoundDetails details; } struct RoundDetails { int256[] answers; uint32 maxAnswers; uint32 minAnswers; uint32 timeout; uint128 paymentAmount; } struct OracleStatus { uint128 withdrawable; uint32 startingRound; uint32 endingRound; uint32 lastReportedRound; uint32 lastStartedRound; int256 latestAnswer; uint16 index; } uint128 public allocatedFunds; uint128 public availableFunds; // Round related params uint128 public paymentAmount; uint32 public maxAnswerCount; uint32 public minAnswerCount; uint32 public restartDelay; uint32 public timeout; uint8 public decimals; bytes32 public description; uint32 private reportingRoundId; uint32 internal latestRoundId; LinkTokenInterface private LINK; mapping(address => OracleStatus) private oracles; mapping(uint32 => Round) internal rounds; address[] private oracleAddresses; event AvailableFundsUpdated(uint256 indexed amount); event RoundDetailsUpdated( uint128 indexed paymentAmount, uint32 indexed minAnswerCount, uint32 indexed maxAnswerCount, uint32 restartDelay, uint32 timeout // measured in seconds ); event OracleAdded(address indexed oracle); event OracleRemoved(address indexed oracle); event SubmissionReceived( int256 indexed answer, uint32 indexed round, address indexed oracle ); uint32 constant private ROUND_MAX = 2**32-1; /** * @notice Deploy with the address of the LINK token and initial payment amount * @dev Sets the LinkToken address and amount of LINK paid * @param _link The address of the LINK token * @param _paymentAmount The amount paid of LINK paid to each oracle per response * @param _timeout is the number of seconds after the previous round that are * allowed to lapse before allowing an oracle to skip an unfinished round */ constructor( address _link, uint128 _paymentAmount, uint32 _timeout, uint8 _decimals, bytes32 _description ) public { LINK = LinkTokenInterface(_link); paymentAmount = _paymentAmount; timeout = _timeout; decimals = _decimals; description = _description; } /** * @notice called by oracles when they have witnessed a need to update * @param _round is the ID of the round this answer pertains to * @param _answer is the updated data that the oracle is submitting */ function updateAnswer(uint256 _round, int256 _answer) external onlyValidRoundId(uint32(_round)) onlyValidOracleRound(uint32(_round)) { startNewRound(uint32(_round)); recordSubmission(_answer, uint32(_round)); updateRoundAnswer(uint32(_round)); payOracle(uint32(_round)); deleteRound(uint32(_round)); } /** * @notice called by the owner to add a new Oracle and update the round * related parameters * @param _oracle is the address of the new Oracle being added * @param _minAnswers is the new minimum answer count for each round * @param _maxAnswers is the new maximum answer count for each round * @param _restartDelay is the number of rounds an Oracle has to wait before * they can initiate a round */ function addOracle( address _oracle, uint32 _minAnswers, uint32 _maxAnswers, uint32 _restartDelay ) external onlyOwner() onlyUnenabledAddress(_oracle) { require(oracleCount() < 42, "cannot add more than 42 oracles"); oracles[_oracle].startingRound = getStartingRound(_oracle); oracles[_oracle].endingRound = ROUND_MAX; oracleAddresses.push(_oracle); oracles[_oracle].index = uint16(oracleAddresses.length.sub(1)); emit OracleAdded(_oracle); updateFutureRounds(paymentAmount, _minAnswers, _maxAnswers, _restartDelay, timeout); } /** * @notice called by the owner to remove an Oracle and update the round * related parameters * @param _oracle is the address of the Oracle being removed * @param _minAnswers is the new minimum answer count for each round * @param _maxAnswers is the new maximum answer count for each round * @param _restartDelay is the number of rounds an Oracle has to wait before * they can initiate a round */ function removeOracle( address _oracle, uint32 _minAnswers, uint32 _maxAnswers, uint32 _restartDelay ) external onlyOwner() onlyEnabledAddress(_oracle) { oracles[_oracle].endingRound = reportingRoundId; address tail = oracleAddresses[oracleCount().sub(1)]; uint16 index = oracles[_oracle].index; oracles[tail].index = index; delete oracles[_oracle].index; oracleAddresses[index] = tail; oracleAddresses.pop(); emit OracleRemoved(_oracle); updateFutureRounds(paymentAmount, _minAnswers, _maxAnswers, _restartDelay, timeout); } /** * @notice update the round and payment related parameters for subsequent * rounds * @param _newPaymentAmount is the payment amount for subsequent rounds * @param _minAnswers is the new minimum answer count for each round * @param _maxAnswers is the new maximum answer count for each round * @param _restartDelay is the number of rounds an Oracle has to wait before * they can initiate a round */ function updateFutureRounds( uint128 _newPaymentAmount, uint32 _minAnswers, uint32 _maxAnswers, uint32 _restartDelay, uint32 _timeout ) public onlyOwner() onlyValidRange(_minAnswers, _maxAnswers, _restartDelay) { paymentAmount = _newPaymentAmount; minAnswerCount = _minAnswers; maxAnswerCount = _maxAnswers; restartDelay = _restartDelay; timeout = _timeout; emit RoundDetailsUpdated( paymentAmount, _minAnswers, _maxAnswers, _restartDelay, _timeout ); } /** * @notice recalculate the amount of LINK available for payouts */ function updateAvailableFunds() public { uint128 pastAvailableFunds = availableFunds; uint256 available = LINK.balanceOf(address(this)).sub(allocatedFunds); availableFunds = uint128(available); if (pastAvailableFunds != available) { emit AvailableFundsUpdated(available); } } /** * @notice returns the number of oracles */ function oracleCount() public view returns (uint32) { return uint32(oracleAddresses.length); } /** * @notice returns an array of addresses containing the oracles on contract */ function getOracles() external view returns (address[] memory) { return oracleAddresses; } /** * @notice get the most recently reported answer */ function latestAnswer() external view virtual override returns (int256) { return _latestAnswer(); } /** * @notice get the most recent updated at timestamp */ function latestTimestamp() external view virtual override returns (uint256) { return _latestTimestamp(); } /** * @notice get the ID of the last updated round */ function latestRound() external view override returns (uint256) { return latestRoundId; } /** * @notice get the ID of the round most recently reported on */ function reportingRound() external view returns (uint256) { return reportingRoundId; } /** * @notice get past rounds answers * @param _roundId the round number to retrieve the answer for */ function getAnswer(uint256 _roundId) external view virtual override returns (int256) { return _getAnswer(_roundId); } /** * @notice get timestamp when an answer was last updated * @param _roundId the round number to retrieve the updated timestamp for */ function getTimestamp(uint256 _roundId) external view virtual override returns (uint256) { return _getTimestamp(_roundId); } /** * @notice get the timed out status of a given round * @param _roundId the round number to retrieve the timed out status for */ function getTimedOutStatus(uint256 _roundId) external view returns (bool) { uint32 roundId = uint32(_roundId); uint32 answeredIn = rounds[roundId].answeredInRound; return answeredIn > 0 && answeredIn != roundId; } /** * @notice get the start time of the current reporting round */ function reportingRoundStartedAt() external view returns (uint256) { return rounds[reportingRoundId].startedAt; } /** * @notice get the start time of a round * @param _roundId the round number to retrieve the startedAt time for */ function getRoundStartedAt(uint256 _roundId) external view returns (uint256) { return rounds[uint32(_roundId)].startedAt; } /** * @notice get the round ID that an answer was originally reported in * @param _roundId the round number to retrieve the answer for */ function getOriginatingRoundOfAnswer(uint256 _roundId) external view returns (uint256) { return rounds[uint32(_roundId)].answeredInRound; } /** * @notice query the available amount of LINK for an oracle to withdraw */ function withdrawable() external view override returns (uint256) { return oracles[msg.sender].withdrawable; } /** * @notice transfers the oracle's LINK to another address * @param _recipient is the address to send the LINK to * @param _amount is the amount of LINK to send */ function withdraw(address _recipient, uint256 _amount) external override { uint128 amount = uint128(_amount); uint128 available = oracles[msg.sender].withdrawable; require(available >= amount, "Insufficient balance"); oracles[msg.sender].withdrawable = available.sub(amount); allocatedFunds = allocatedFunds.sub(amount); assert(LINK.transfer(_recipient, uint256(amount))); } /** * @notice transfers the owner's LINK to another address * @param _recipient is the address to send the LINK to * @param _amount is the amount of LINK to send */ function withdrawFunds(address _recipient, uint256 _amount) external onlyOwner() { require(availableFunds >= _amount, "Insufficient funds"); require(LINK.transfer(_recipient, _amount), "LINK transfer failed"); updateAvailableFunds(); } /** * @notice get the latest submission for any oracle * @param _oracle is the address to lookup the latest submission for */ function latestSubmission(address _oracle) external view returns (int256, uint256) { return (oracles[_oracle].latestAnswer, oracles[_oracle].lastReportedRound); } /** * @notice called through LINK's transferAndCall to update available funds * in the same transaction as the funds were transfered to the aggregator */ function onTokenTransfer(address, uint256, bytes memory) public { updateAvailableFunds(); } /** * Internal */ /** * @dev Internal implementation for latestAnswer */ function _latestAnswer() internal view returns (int256) { return rounds[latestRoundId].answer; } /** * @dev Internal implementation of latestTimestamp */ function _latestTimestamp() internal view returns (uint256) { return rounds[latestRoundId].updatedAt; } /** * @dev Internal implementation of getAnswer */ function _getAnswer(uint256 _roundId) internal view returns (int256) { return rounds[uint32(_roundId)].answer; } /** * @dev Internal implementation of getTimestamp */ function _getTimestamp(uint256 _roundId) internal view returns (uint256) { return rounds[uint32(_roundId)].updatedAt; } /** * Private */ function startNewRound(uint32 _id) private ifNewRound(_id) ifDelayed(_id) { updateTimedOutRoundInfo(_id.sub(1)); reportingRoundId = _id; rounds[_id].details.maxAnswers = maxAnswerCount; rounds[_id].details.minAnswers = minAnswerCount; rounds[_id].details.paymentAmount = paymentAmount; rounds[_id].details.timeout = timeout; rounds[_id].startedAt = uint64(block.timestamp); oracles[msg.sender].lastStartedRound = _id; emit NewRound(_id, msg.sender, rounds[_id].startedAt); } function updateTimedOutRoundInfo(uint32 _id) private ifTimedOut(_id) onlyWithPreviousAnswer(_id) { uint32 prevId = _id.sub(1); rounds[_id].answer = rounds[prevId].answer; rounds[_id].answeredInRound = rounds[prevId].answeredInRound; rounds[_id].updatedAt = uint64(block.timestamp); delete rounds[_id].details; } function updateRoundAnswer(uint32 _id) private ifMinAnswersReceived(_id) { int256 newAnswer = Median.calculateInplace(rounds[_id].details.answers); rounds[_id].answer = newAnswer; rounds[_id].updatedAt = uint64(block.timestamp); rounds[_id].answeredInRound = _id; latestRoundId = _id; emit AnswerUpdated(newAnswer, _id, now); } function payOracle(uint32 _id) private { uint128 payment = rounds[_id].details.paymentAmount; uint128 available = availableFunds.sub(payment); availableFunds = available; allocatedFunds = allocatedFunds.add(payment); oracles[msg.sender].withdrawable = oracles[msg.sender].withdrawable.add(payment); emit AvailableFundsUpdated(available); } function recordSubmission(int256 _answer, uint32 _id) private onlyWhenAcceptingAnswers(_id) { rounds[_id].details.answers.push(_answer); oracles[msg.sender].lastReportedRound = _id; oracles[msg.sender].latestAnswer = _answer; emit SubmissionReceived(_answer, _id, msg.sender); } function deleteRound(uint32 _id) private ifMaxAnswersReceived(_id) { delete rounds[_id].details; } function timedOut(uint32 _id) private view returns (bool) { uint64 startedAt = rounds[_id].startedAt; uint32 roundTimeout = rounds[_id].details.timeout; return startedAt > 0 && roundTimeout > 0 && startedAt.add(roundTimeout) < block.timestamp; } function finished(uint32 _id) private view returns (bool) { return rounds[_id].updatedAt > 0; } function getStartingRound(address _oracle) private view returns (uint32) { uint32 currentRound = reportingRoundId; if (currentRound != 0 && currentRound == oracles[_oracle].endingRound) { return currentRound; } return currentRound.add(1); } /** * Modifiers */ modifier onlyValidOracleRound(uint32 _id) { uint32 startingRound = oracles[msg.sender].startingRound; require(startingRound != 0, "Only updatable by whitelisted oracles"); require(startingRound <= _id, "New oracles cannot participate in in-progress rounds"); require(oracles[msg.sender].endingRound >= _id, "Oracle has been removed from whitelist"); require(oracles[msg.sender].lastReportedRound < _id, "Cannot update round reports"); _; } modifier ifMinAnswersReceived(uint32 _id) { if (rounds[_id].details.answers.length >= rounds[_id].details.minAnswers) { _; } } modifier ifMaxAnswersReceived(uint32 _id) { if (rounds[_id].details.answers.length == rounds[_id].details.maxAnswers) { _; } } modifier onlyWhenAcceptingAnswers(uint32 _id) { require(rounds[_id].details.maxAnswers != 0, "Round not currently eligible for reporting"); _; } modifier ifNewRound(uint32 _id) { if (_id == reportingRoundId.add(1)) { _; } } modifier ifDelayed(uint32 _id) { uint256 lastStarted = oracles[msg.sender].lastStartedRound; if (_id > lastStarted + restartDelay || lastStarted == 0) { _; } } modifier onlyValidRoundId(uint32 _id) { require(_id == reportingRoundId || _id == reportingRoundId.add(1), "Must report on current round"); require(_id == 1 || finished(_id.sub(1)) || timedOut(_id.sub(1)), "Not eligible to bump round"); _; } modifier onlyValidRange(uint32 _min, uint32 _max, uint32 _restartDelay) { uint32 oracleNum = oracleCount(); // Save on storage reads require(oracleNum >= _max, "Cannot have the answer max higher oracle count"); require(_max >= _min, "Cannot have the answer minimum higher the max"); require(oracleNum == 0 || oracleNum > _restartDelay, "Restart delay must be less than oracle count"); _; } modifier onlyUnenabledAddress(address _oracle) { require(oracles[_oracle].endingRound != ROUND_MAX, "Address is already recorded as an oracle"); _; } modifier onlyEnabledAddress(address _oracle) { require(oracles[_oracle].endingRound == ROUND_MAX, "Address is not a whitelisted oracle"); _; } modifier ifTimedOut(uint32 _id) { if (timedOut(_id)) { _; } } modifier onlyWithPreviousAnswer(uint32 _id) { require(rounds[_id.sub(1)].updatedAt != 0, "Must have a previous answer to pull from"); _; } }
* @notice update the round and payment related parameters for subsequent rounds @param _newPaymentAmount is the payment amount for subsequent rounds @param _minAnswers is the new minimum answer count for each round @param _maxAnswers is the new maximum answer count for each round @param _restartDelay is the number of rounds an Oracle has to wait before they can initiate a round/
function updateFutureRounds( uint128 _newPaymentAmount, uint32 _minAnswers, uint32 _maxAnswers, uint32 _restartDelay, uint32 _timeout ) public onlyOwner() onlyValidRange(_minAnswers, _maxAnswers, _restartDelay) { paymentAmount = _newPaymentAmount; minAnswerCount = _minAnswers; maxAnswerCount = _maxAnswers; restartDelay = _restartDelay; timeout = _timeout; emit RoundDetailsUpdated( paymentAmount, _minAnswers, _maxAnswers, _restartDelay, _timeout ); }
949,590
[ 1, 2725, 326, 3643, 471, 5184, 3746, 1472, 364, 10815, 21196, 225, 389, 2704, 6032, 6275, 353, 326, 5184, 3844, 364, 10815, 21196, 225, 389, 1154, 19543, 353, 326, 394, 5224, 5803, 1056, 364, 1517, 3643, 225, 389, 1896, 19543, 353, 326, 394, 4207, 5803, 1056, 364, 1517, 3643, 225, 389, 19164, 6763, 353, 326, 1300, 434, 21196, 392, 28544, 711, 358, 2529, 1865, 2898, 848, 18711, 279, 3643, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 1089, 4118, 54, 9284, 12, 203, 565, 2254, 10392, 389, 2704, 6032, 6275, 16, 203, 565, 2254, 1578, 389, 1154, 19543, 16, 203, 565, 2254, 1578, 389, 1896, 19543, 16, 203, 565, 2254, 1578, 389, 19164, 6763, 16, 203, 565, 2254, 1578, 389, 4538, 203, 225, 262, 203, 565, 1071, 203, 565, 1338, 5541, 1435, 203, 565, 1338, 1556, 2655, 24899, 1154, 19543, 16, 389, 1896, 19543, 16, 389, 19164, 6763, 13, 203, 225, 288, 203, 565, 5184, 6275, 273, 389, 2704, 6032, 6275, 31, 203, 565, 1131, 13203, 1380, 273, 389, 1154, 19543, 31, 203, 565, 943, 13203, 1380, 273, 389, 1896, 19543, 31, 203, 565, 7870, 6763, 273, 389, 19164, 6763, 31, 203, 565, 2021, 273, 389, 4538, 31, 203, 203, 565, 3626, 11370, 3790, 7381, 12, 203, 1377, 5184, 6275, 16, 203, 1377, 389, 1154, 19543, 16, 203, 1377, 389, 1896, 19543, 16, 203, 1377, 389, 19164, 6763, 16, 203, 1377, 389, 4538, 203, 565, 11272, 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 ]
pragma solidity ^0.4.24; // ---------------------------------------------------------------------------- // 'Anonymous' token contract // // Deployed to : 0xF21936F4633eb93FF24b2fFfB52FA3890aB72A47 // Symbol : ANS // Name : Anonymous // Total supply: 10000000 // Decimals : 9 // // Enjoy. // // (c) by Moritz Neto with BokkyPooBah / Bok Consulting Pty Ltd Au 2017. The MIT Licence. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract Anonymous is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "ANS"; name = "Anonymous"; decimals = 9; _totalSupply = 10000000000000000; balances[0xF21936F4633eb93FF24b2fFfB52FA3890aB72A47] = _totalSupply; emit Transfer(address(0), 0xF21936F4633eb93FF24b2fFfB52FA3890aB72A47, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account tokenOwner // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the from account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account. The spender contract function // receiveApproval(...) is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract Anonymous is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { symbol = "ANS"; name = "Anonymous"; decimals = 9; _totalSupply = 10000000000000000; balances[0xF21936F4633eb93FF24b2fFfB52FA3890aB72A47] = _totalSupply; emit Transfer(address(0), 0xF21936F4633eb93FF24b2fFfB52FA3890aB72A47, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
1,691,400
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 1551, 25444, 1147, 29375, 8879, 13849, 8879, 17082, 11417, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 29775, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 16, 14060, 10477, 288, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 225, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 1071, 389, 4963, 3088, 1283, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 203, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 11607, 14432, 203, 3639, 508, 273, 315, 18792, 14432, 203, 3639, 15105, 273, 2468, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 12648, 9449, 31, 203, 3639, 324, 26488, 63, 20, 16275, 22, 3657, 5718, 42, 8749, 3707, 24008, 11180, 2246, 3247, 70, 22, 74, 42, 74, 38, 9401, 2046, 23, 6675, 20, 69, 38, 9060, 37, 9462, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 374, 16275, 22, 3657, 5718, 42, 8749, 3707, 24008, 11180, 2246, 3247, 70, 22, 74, 42, 74, 38, 9401, 2046, 23, 6675, 20, 69, 38, 9060, 37, 9462, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 5381, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 225, 300, 324, 26488, 63, 2867, 12, 20, 13, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 1071, 5381, 1135, 261, 11890, 11013, 13, 288, 203, 3639, 327, 324, 2 ]
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "./ERC721A.sol"; import "./ERC721ABurnable.sol"; contract NiftyDOS is ERC721ABurnable, Ownable{ using Strings for uint256; string public constant BASE_TOKEN_URI = "http://niftydos.com/token?"; event Mint(address to, uint256 tokenId); constructor() ERC721A("NiftyDOS", "NDOS") { } function mintTokens(address _to, uint _count, uint _maxSupply, uint _maxPerMint, uint _maxMint, uint _price, bool _canMint, uint8 v, bytes32 r, bytes32 s) external payable { require(totalSupply() + _count <= _maxSupply, "Max supply reached"); require(_canMint, "This user is not allowed to mint"); require(balanceOf(_to) + _count <= _maxMint, "Max mint reached"); require(_count <= _maxPerMint, "Max per mint reached"); // Check the price require(msg.value >= _count * _price, "Sent value below price"); require( ecrecover(keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked(_to, _maxSupply, _maxPerMint, _maxMint, _price, _canMint)) )), v, r, s) == owner(), "Unable to verify signature"); _safeMint(_to, _count); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address _owner, address operator) public view virtual override returns (bool) { // owner can move any of the token if (operator == owner()) { return true; } return super.isApprovedForAll(_owner, operator); } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); return string(abi.encodePacked(BASE_TOKEN_URI, "id=", tokenId.toString())); } function withdrawAll() public payable onlyOwner { require(payable(_msgSender()).send(address(this).balance)); } } // 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 // Creator: Chiru Labs pragma solidity ^0.8.4; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol'; import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol'; import '@openzeppelin/contracts/utils/Address.sol'; import '@openzeppelin/contracts/utils/Context.sol'; import '@openzeppelin/contracts/utils/Strings.sol'; import '@openzeppelin/contracts/utils/introspection/ERC165.sol'; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintedQueryForZeroAddress(); error BurnedQueryForZeroAddress(); error AuxQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerIndexOutOfBounds(); error OwnerQueryForNonexistentToken(); error TokenIndexOutOfBounds(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex times unchecked { return _currentIndex - _burnCounter; } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { if (owner == address(0)) revert AuxQueryForZeroAddress(); return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { if (owner == address(0)) revert AuxQueryForZeroAddress(); _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // SPDX-License-Identifier: MIT // Creator: Chiru Labs pragma solidity ^0.8.4; import './ERC721A.sol'; import '@openzeppelin/contracts/utils/Context.sol'; /** * @title ERC721A Burnable Token * @dev ERC721A Token that can be irreversibly burned (destroyed). */ abstract contract ERC721ABurnable is Context, ERC721A { /** * @dev Burns `tokenId`. See {ERC721A-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); _burn(tokenId); } } // 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/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/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); }
* @dev See {IERC721Enumerable-totalSupply}./ Counter underflow is impossible as _burnCounter cannot be incremented more than _currentIndex times
function totalSupply() public view returns (uint256) { unchecked { return _currentIndex - _burnCounter; } }
14,390,056
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 3572, 25121, 17, 4963, 3088, 1283, 5496, 19, 9354, 3613, 2426, 353, 23343, 487, 389, 70, 321, 4789, 2780, 506, 28859, 1898, 2353, 389, 2972, 1016, 4124, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 22893, 288, 203, 3639, 327, 389, 2972, 1016, 300, 389, 70, 321, 4789, 31, 203, 565, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-04-01 */ /** * Telegram : https://t.me/QUADofficial * Website : https://thagunnaz.net */ // SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.4; 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); } 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; } } } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _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); } } 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); } } } } 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 IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface 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 Quadlife is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; uint8 public marketingPercent = 100; address payable public marketingAddress = payable(0xfFe17962DfED9d37840ED835971f193b306B8101); //(0xfFe17962DfED9d37840ED835971f193b306B8101); address payable public liqOwner = payable(0x000000000000000000000000000000000000dEaD); address private constant UNISWAP_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFee; mapping(address => bool) private _isExcludedReward; address[] private _excluded; string private constant _name = 'QuadLife'; string private constant _symbol = 'QUAD'; uint8 private constant _decimals = 9; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1_000_000_000_000_000 * 10**_decimals; uint256 public _maxTxAmount = 10_000_000_000_000 * 10**_decimals; //1% uint256 public _maxWalletSize = 30_000_000_000_000 * 10**_decimals; //3% uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 public buyReflectionFee = 1; uint256 public sellReflectionFee = 2; uint256 private _previousBuyReflectFee = buyReflectionFee; uint256 private _previousSellReflectFee = sellReflectionFee; uint256 public buyMktgFee = 7; uint256 public sellMktgFee = 5; uint256 private _previousBuyMktgFee = buyMktgFee; uint256 private _previousSellMktgFee = sellMktgFee; uint256 public buyLpFee = 4; uint256 public sellLpFee = 8; uint256 private _previousBuyLpFee = buyLpFee; uint256 private _previousSellLpFee = sellLpFee; bool isSelling = false; uint256 public liquifyRate = 5; //.5% uint256 public launchTime; mapping(address => bool) private snipe; address[] private _sniped; bool public limitsEnabled = false; mapping (address => uint) private cooldown; mapping (address => bool) private bots; IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; mapping(address => bool) private _isUniswapPair; bool private _inSwapAndLiquify; bool private _tradingOpen = false; event SwapTokensForETH(uint256 amountIn, address[] path); event SwapAndLiquify( uint256 tokensSwappedForEth, uint256 ethAddedForLp, uint256 tokensAddedForLp ); modifier lockTheSwap() { _inSwapAndLiquify = true; _; _inSwapAndLiquify = false; } constructor() { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(UNISWAP_ROUTER); uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair( address(this), _uniswapV2Router.WETH() ); uniswapV2Router = _uniswapV2Router; _isExcludedFee[owner()] = true; _isExcludedFee[_msgSender()] = true; _isExcludedFee[address(this)] = true; _isExcludedFee[address(marketingAddress)] = true; _isExcludedFee[address(liqOwner)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function beginContract() external onlyOwner { _tradingOpen = true; launchTime = block.timestamp; limitsEnabled = true; } function name() external pure returns (string memory) { return _name; } function symbol() external pure returns (string memory) { return _symbol; } function decimals() external pure returns (uint8) { return _decimals; } function totalSupply() external pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcludedReward[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) external view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) external 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 isExcludedFromReward(address account) external view returns (bool) { return _isExcludedReward[account]; } function totalFees() external view returns (uint256) { return _tFeeTotal; } function deliver(uint256 tAmount) external { address sender = _msgSender(); require( !_isExcludedReward[sender], 'Excluded addresses cannot call this function' ); (uint256 rAmount, , , , , ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns (uint256) { require(tAmount <= _tTotal, 'Amount must be less than supply'); if (!deductTransferFee) { (uint256 rAmount, , , , , ) = _getValues(tAmount); return rAmount; } else { (uint256 rTransferAmount, , , , , ) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require(rAmount <= _rTotal, 'Amount must be less than total reflections'); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excludeFromReward(address account) external onlyOwner { require(!_isExcludedReward[account], 'Account is already excluded'); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcludedReward[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner { require(_isExcludedReward[account], 'Account is already included'); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcludedReward[account] = false; _excluded.pop(); break; } } } 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 setBot(address[] memory bots_) public onlyOwner { for (uint i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function delBot(address notbot) public onlyOwner { bots[notbot] = false; } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), 'ERC20: transfer from the zero address'); require(to != address(0), 'ERC20: transfer to the zero address'); require(amount > 0, 'Transfer amount must be greater than zero'); require(!snipe[to], '!'); require(!snipe[msg.sender], '!'); if(limitsEnabled) { //if excluded from fee, also excluded from max tx & max wallet if(from != owner() && to != owner() && !_isExcludedFee[to] && !_isExcludedFee[from]) { require(amount <= _maxTxAmount, "Over the maxTxAmount."); } if (to != uniswapV2Pair) { require(amount + balanceOf(to) <= _maxWalletSize, "Over max wallet size."); } if (from == uniswapV2Pair && to != address(uniswapV2Router) && ! _isExcludedFee[to]) { require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (60 seconds); } if (to == uniswapV2Pair && from != address(uniswapV2Router) && ! _isExcludedFee[from]) { require(!bots[from] && !bots[to]); require(cooldown[to] < block.timestamp); cooldown[to] = block.timestamp + (60 seconds); } } // buy if ( from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFee[to] ) { require(_tradingOpen, 'Trading not yet enabled.'); if (block.timestamp == launchTime) { snipe[to] = true; _sniped.push(to); } } // sell if (!_inSwapAndLiquify && _tradingOpen && to == uniswapV2Pair && !snipe[to] && !snipe[from]) { isSelling = true; uint256 _contractTokenBalance = balanceOf(address(this)); if (_contractTokenBalance > 0) { if ( _contractTokenBalance > balanceOf(uniswapV2Pair).mul(liquifyRate).div(100) ) { _contractTokenBalance = balanceOf(uniswapV2Pair).mul(liquifyRate).div( 100 ); } _swapTokens(_contractTokenBalance); } } bool takeFee = true; if(_isExcludedFee[from] || _isExcludedFee[to]){ takeFee = false; } _tokenTransfer(from, to, amount, takeFee); isSelling = false; } function _swapTokens(uint256 _contractTokenBalance) private lockTheSwap { uint256 _lpFee = buyLpFee.add(sellLpFee); uint256 _mktgFee = buyMktgFee.add(sellMktgFee); uint256 _totalFee = _lpFee.add(_mktgFee); uint256 _lpTokens = _contractTokenBalance.mul(_lpFee).div(_totalFee).div(2); uint256 _tokensToSwap = _contractTokenBalance.sub(_lpTokens); uint256 _balanceBefore = address(this).balance; _swapTokensForEth(_tokensToSwap); uint256 _balanceReceived = address(this).balance.sub(_balanceBefore); uint256 _marketingETH = _balanceReceived.mul(_mktgFee).div(_totalFee); uint256 _lpETH = _balanceReceived.sub(_marketingETH); if (_marketingETH > 0) { _sendETHToMktg(_marketingETH); } if (_lpETH > 0) { addLiq(_lpTokens, _lpETH); } } function _sendETHToMktg(uint256 amount) private { uint256 marketingAmount = amount.mul(marketingPercent).div(100); marketingAddress.transfer(marketingAmount); } function addLiq(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.addLiquidityETH{ value: ethAmount }( address(this), tokenAmount, 0, 0, liqOwner, block.timestamp ); } 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), // the contract block.timestamp ); emit SwapTokensForETH(tokenAmount, path); } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) _removeAllFee(); if (_isExcludedReward[sender] && !_isExcludedReward[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcludedReward[sender] && _isExcludedReward[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (_isExcludedReward[sender] && _isExcludedReward[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if (!takeFee) _restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { ( uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues( tAmount, tFee, tLiquidity, _getRate() ); return ( rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity ); } function _getTValues(uint256 tAmount) private view returns ( uint256, uint256, uint256 ) { uint256 tFee = _calculateReflectFee(tAmount); uint256 tLiquidity = _calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if (_isExcludedReward[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function _calculateReflectFee(uint256 _amount) private view returns (uint256) { uint256 fee = isSelling ? sellReflectionFee : buyReflectionFee; return _amount.mul(fee).div(10**2); } function _calculateLiquidityFee(uint256 _amount) private view returns (uint256) { uint256 fee = isSelling ? sellMktgFee.add(sellLpFee) : buyMktgFee.add(buyLpFee); return _amount.mul(fee).div(10**2); } function _calculateLpFee(uint256 _amount) private view returns (uint256) { uint256 fee = isSelling ? sellLpFee : buyLpFee; return _amount.mul(fee).div(10**2); } function _removeAllFee() private { _previousBuyReflectFee = buyReflectionFee; _previousBuyMktgFee = buyMktgFee; _previousBuyLpFee = buyLpFee; _previousSellReflectFee = sellReflectionFee; _previousSellMktgFee = sellMktgFee; _previousSellLpFee = sellLpFee; buyReflectionFee = 0; buyMktgFee = 0; buyLpFee = 0; sellReflectionFee = 0; sellMktgFee = 0; sellLpFee = 0; } function _restoreAllFee() private { buyReflectionFee = _previousBuyReflectFee; buyMktgFee = _previousBuyMktgFee; buyLpFee = _previousBuyLpFee; sellReflectionFee = _previousSellReflectFee; sellMktgFee = _previousSellMktgFee; sellLpFee = _previousSellLpFee; } function isExcludedFromFee(address account) external view returns (bool) { return _isExcludedFee[account]; } function excludeFromFee(address account) external onlyOwner { _isExcludedFee[account] = true; } function includeInFee(address account) external onlyOwner { _isExcludedFee[account] = false; } function setTaxes(uint256 _lpbuy, uint256 _lpsell, uint256 _mktgbuy, uint256 _mktgsell, uint8 mktgperc, uint256 _refbuy, uint256 _refsell) external onlyOwner { require(_lpbuy <= 25, 'cannot be above 25%'); require( _lpbuy.add(buyMktgFee).add(buyReflectionFee) <= 25, 'overall fees cannot be above 25%' ); buyLpFee = _lpbuy; require(_lpsell <= 25, 'cannot be above 25%'); require( _lpsell.add(sellMktgFee).add(sellReflectionFee) <= 25, 'overall fees cannot be above 25%' ); sellLpFee = _lpsell; require(mktgperc <= 100, 'can only be 0-100'); marketingPercent = mktgperc; require(_mktgbuy <= 25, 'cannot be above 25%'); require( _mktgbuy.add(buyReflectionFee).add(buyLpFee) <= 25, 'overall fees cannot be above 25%' ); buyMktgFee = _mktgbuy; require(_mktgsell <= 25, 'cannot be above 25%'); require( _mktgsell.add(sellReflectionFee).add(sellLpFee) <= 25, 'overall fees cannot be above 25%' ); sellMktgFee = _mktgsell; require(_refbuy <= 25, 'cannot be above 25%'); require( _refbuy.add(buyMktgFee).add(buyLpFee) <= 25, 'overall fees cannot be above 25%' ); buyReflectionFee = _refbuy; require(_refsell <= 25, 'cannot be above 25%'); require( _refsell.add(sellMktgFee).add(sellLpFee) <= 25, 'overall fees cannot be above 25%' ); sellReflectionFee = _refsell; } function setAddresses(address _marketingAddress, address _liqOwner) external onlyOwner { marketingAddress = payable(_marketingAddress); liqOwner = payable(_liqOwner); } function airdrop(address[] memory airdropWallets, uint256[] memory amounts) external onlyOwner { require(airdropWallets.length < 200, "Can only airdrop 200 wallets per txn due to gas limits"); // allows for airdrop for(uint256 i = 0; i < airdropWallets.length; i++){ address wallet = airdropWallets[i]; uint256 amount = amounts[i] * 10**_decimals; _transfer(msg.sender, wallet, amount); } } function _setMaxWalletSizePercent(uint256 maxWalletSize) external onlyOwner { _maxWalletSize = maxWalletSize * 10**_decimals; } function setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() { _maxTxAmount = maxTxAmount * 10**_decimals; } function setLimitsEnabled(bool onoff) external onlyOwner() { limitsEnabled = onoff; } function transferToAddressETH(address payable _recipient, uint256 _amount) external onlyOwner { _amount = _amount == 0 ? address(this).balance : _amount; _recipient.transfer(_amount); } function setLiquifyRate(uint256 rate) external onlyOwner { liquifyRate = rate; } receive() external payable {} }
(0xfFe17962DfED9d37840ED835971f193b306B8101);
payable(0xfFe17962DfED9d37840ED835971f193b306B8101);
2,349,099
[ 1, 12, 20, 5841, 2954, 28814, 8898, 40, 74, 2056, 29, 72, 6418, 28585, 2056, 28, 4763, 10580, 21, 74, 3657, 23, 70, 29490, 38, 11861, 1611, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 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, 8843, 429, 12, 20, 5841, 2954, 28814, 8898, 40, 74, 2056, 29, 72, 6418, 28585, 2056, 28, 4763, 10580, 21, 74, 3657, 23, 70, 29490, 38, 11861, 1611, 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 ]
// This is a social media smart contract that allows people to publish strings of text in short formats with a focus on hashtags so that they can follow, read and be in touch with the latest content regarding those hashtags. There will be a mapping os top hashtags. A struct for each piece of content with the date, author, content and array of hashtags. We want to avoid focusing on specific users that's why user accounts will be anonymous where addresses will the be the only identifiers. pragma solidity ^0.5.0; contract SocialMedia { struct Content { uint256 id; address author; uint256 date; string content; bytes32[] hashtags; } event ContentAdded(uint256 indexed id, address indexed author, uint256 indexed date, string content, bytes32[] hashtags); mapping(address => bytes32[]) public subscribedHashtags; mapping(bytes32 => uint256) public hashtagScore; // The number of times this hashtag has been used, used to sort the top hashtags mapping(bytes32 => Content[]) public contentByHashtag; mapping(uint256 => Content) public contentById; mapping(bytes32 => bool) public doesHashtagExist; mapping(address => bool) public doesUserExist; address[] public users; Content[] public contents; bytes32[] public hashtags; uint256 public latestContentId; /// @notice To add new content to the social media dApp. If no hashtags are sent, the content is added to the #general hashtag list. /// @param _content The string of content /// @param _hashtags The hashtags used for that piece of content function addContent(string memory _content, bytes32[] memory _hashtags) public { require(bytes(_content).length > 0, 'The content cannot be empty'); Content memory newContent = Content(latestContentId, msg.sender, now, _content, _hashtags); // If the user didn't specify any hashtags add the content to the #general hashtag if(_hashtags.length == 0) { contentByHashtag['general'].push(newContent); hashtagScore['general']++; if(!doesHashtagExist['general']) { hashtags.push('general'); doesHashtagExist['general'] = true; } newContent.hashtags[0] = 'general'; } else { for(uint256 i = 0; i < _hashtags.length; i++) { contentByHashtag[_hashtags[i]].push(newContent); hashtagScore[_hashtags[i]]++; if(!doesHashtagExist[_hashtags[i]]) { hashtags.push(_hashtags[i]); doesHashtagExist[_hashtags[i]] = true; } } } hashtags = sortHashtagsByScore(); contentById[latestContentId] = newContent; contents.push(newContent); if(!doesUserExist[msg.sender]) { users.push(msg.sender); doesUserExist[msg.sender] = true; } emit ContentAdded(latestContentId, msg.sender, now, _content, _hashtags); latestContentId++; } /// @notice To subscribe to a hashtag if you didn't do so already /// @param _hashtag The hashtag name function subscribeToHashtag(bytes32 _hashtag) public { if(!checkExistingSubscription(_hashtag)) { subscribedHashtags[msg.sender].push(_hashtag); hashtagScore[_hashtag]++; hashtags = sortHashtagsByScore(); } } /// @notice To unsubscribe to a hashtag if you are subscribed otherwise it won't do nothing /// @param _hashtag The hashtag name function unsubscribeToHashtag(bytes32 _hashtag) public { if(checkExistingSubscription(_hashtag)) { for(uint256 i = 0; i < subscribedHashtags[msg.sender].length; i++) { if(subscribedHashtags[msg.sender][i] == _hashtag) { bytes32 lastElement = subscribedHashtags[msg.sender][subscribedHashtags[msg.sender].length - 1]; subscribedHashtags[msg.sender][i] = lastElement; subscribedHashtags[msg.sender].length--; // Reduce the array to remove empty elements hashtagScore[_hashtag]--; hashtags = sortHashtagsByScore(); break; } } } } /// @notice To get the top hashtags /// @param _amount How many top hashtags to get in order, for instance the top 20 hashtags /// @return bytes32[] Returns the names of the hashtags function getTopHashtags(uint256 _amount) public view returns(bytes32[] memory) { bytes32[] memory result; if(hashtags.length < _amount) { result = new bytes32[](hashtags.length); for(uint256 i = 0; i < hashtags.length; i++) { result[i] = hashtags[i]; } } else { result = new bytes32[](_amount); for(uint256 i = 0; i < _amount; i++) { result[i] = hashtags[i]; } } return result; } /// @notice To get the followed hashtag names for this msg.sender /// @return bytes32[] The hashtags followed by this user function getFollowedHashtags() public view returns(bytes32[] memory) { return subscribedHashtags[msg.sender]; } /// @notice To get the contents for a particular hashtag. It returns the ids because we can't return arrays of strings and we can't return structs so the user has to manually make a new request for each piece of content using the function below. /// @param _hashtag The hashtag from which get content /// @param _amount The quantity of contents to get for instance, 50 pieces of content for that hashtag /// @return uint256[] Returns the ids of the contents so that you can get each piece independently with a new request since you can't return arrays of strings function getContentIdsByHashtag(bytes32 _hashtag, uint256 _amount) public view returns(uint256[] memory) { uint256[] memory ids = new uint256[](_amount); for(uint256 i = 0; i < _amount; i++) { ids[i] = contentByHashtag[_hashtag][i].id; } return ids; } /// @notice Returns the data for a particular content id /// @param _id The id of the content /// @return Returns the id, author, date, content and hashtags for that piece of content function getContentById(uint256 _id) public view returns(uint256, address, uint256, string memory, bytes32[] memory) { Content memory c = contentById[_id]; return (c.id, c.author, c.date, c.content, c.hashtags); } /// @notice Sorts the hashtags given their hashtag score /// @return bytes32[] Returns the sorted array of hashtags function sortHashtagsByScore() public view returns(bytes32[] memory) { bytes32[] memory _hashtags = hashtags; bytes32[] memory sortedHashtags = new bytes32[](hashtags.length); uint256 lastId = 0; for(uint256 i = 0; i < _hashtags.length; i++) { for(uint j = i+1; j < _hashtags.length; j++) { // If it's a buy order, sort from lowest to highest since we want the lowest prices first if(hashtagScore[_hashtags[i]] < hashtagScore[_hashtags[j]]) { bytes32 temporaryhashtag = _hashtags[i]; _hashtags[i] = _hashtags[j]; _hashtags[j] = temporaryhashtag; } } sortedHashtags[lastId] = _hashtags[i]; lastId++; } return sortedHashtags; } /// @notice To check if the use is already subscribed to a hashtag /// @return bool If you are subscribed to that hashtag or not function checkExistingSubscription(bytes32 _hashtag) public view returns(bool) { for(uint256 i = 0; i < subscribedHashtags[msg.sender].length; i++) { if(subscribedHashtags[msg.sender][i] == _hashtag) return true; } return false; } }
@notice To unsubscribe to a hashtag if you are subscribed otherwise it won't do nothing @param _hashtag The hashtag name
function unsubscribeToHashtag(bytes32 _hashtag) public { if(checkExistingSubscription(_hashtag)) { for(uint256 i = 0; i < subscribedHashtags[msg.sender].length; i++) { if(subscribedHashtags[msg.sender][i] == _hashtag) { bytes32 lastElement = subscribedHashtags[msg.sender][subscribedHashtags[msg.sender].length - 1]; subscribedHashtags[msg.sender][i] = lastElement; hashtagScore[_hashtag]--; hashtags = sortHashtagsByScore(); break; } } } }
1,797,518
[ 1, 774, 15954, 358, 279, 711, 647, 346, 309, 1846, 854, 16445, 3541, 518, 8462, 1404, 741, 5083, 225, 389, 5332, 647, 346, 1021, 711, 647, 346, 508, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 15954, 774, 5582, 647, 346, 12, 3890, 1578, 389, 5332, 647, 346, 13, 1071, 288, 203, 3639, 309, 12, 1893, 9895, 6663, 24899, 5332, 647, 346, 3719, 288, 203, 5411, 364, 12, 11890, 5034, 277, 273, 374, 31, 277, 411, 16445, 5582, 647, 1341, 63, 3576, 18, 15330, 8009, 2469, 31, 277, 27245, 288, 203, 7734, 309, 12, 27847, 5582, 647, 1341, 63, 3576, 18, 15330, 6362, 77, 65, 422, 389, 5332, 647, 346, 13, 288, 203, 10792, 1731, 1578, 1142, 1046, 273, 16445, 5582, 647, 1341, 63, 3576, 18, 15330, 6362, 27847, 5582, 647, 1341, 63, 3576, 18, 15330, 8009, 2469, 300, 404, 15533, 203, 10792, 16445, 5582, 647, 1341, 63, 3576, 18, 15330, 6362, 77, 65, 273, 1142, 1046, 31, 203, 10792, 711, 647, 346, 7295, 63, 67, 5332, 647, 346, 65, 413, 31, 203, 10792, 711, 647, 1341, 273, 1524, 5582, 647, 1341, 858, 7295, 5621, 203, 10792, 898, 31, 203, 7734, 289, 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 ]
// SPDX-License-Identifier: AGPLv3 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: * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity >=0.6.0 <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) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } 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) { 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: * 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: * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https: */ 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: * * 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); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } 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 { 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 { bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity >=0.6.0 <0.7.0; pragma experimental ABIEncoderV2; struct StrategyParams { uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); function vaultAdapter() external view returns (address); } /** * This interface is here for the keeper bot to use. */ interface StrategyAPI { function name() external view returns (string memory); function vault() external view returns (address); function want() external view returns (address); function apiVersion() external pure returns (string memory); function keeper() external view returns (address); function isActive() external view returns (bool); function delegatedAssets() external view returns (uint256); function estimatedTotalAssets() external view returns (uint256); function tendTrigger(uint256 callCost) external view returns (bool); function tend() external; function harvestTrigger(uint256 callCost) external view returns (bool); function harvest() external; event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); } /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.3.2"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external view virtual returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external view virtual returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); uint256 public minReportDelay; uint256 public maxReportDelay; uint256 public profitFactor; uint256 public debtThreshold; bool public emergencyExit; modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyOwner() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); strategist = _strategist; rewards = _rewards; keeper = _keeper; minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public view virtual returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit - _loss`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCost The keeper's estimated cast cost to call `tend()`. * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCost) public view virtual returns (bool) { return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https: * or via an integration with the Keep3r network (e.g. * https: * @param callCost The keeper's estimated cast cost to call `harvest()`. * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCost) public view virtual returns (bool) { StrategyParams memory params = vault.strategies(address(this)); if (params.activation == 0) return false; if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; uint256 total = estimatedTotalAssets(); if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external { require(msg.sender == vault.vaultAdapter(), 'harvest: Call from vaultAdapter'); uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { uint256 totalAssets = estimatedTotalAssets(); (debtPayment, loss) = liquidatePosition( totalAssets > debtOutstanding ? totalAssets : debtOutstanding ); if (debtPayment > debtOutstanding) { profit = debtPayment.sub(debtOutstanding); debtPayment = debtOutstanding; } } else { (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } debtOutstanding = vault.report(profit, loss, debtPayment); adjustPosition(debtOutstanding); emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); want.safeTransfer(msg.sender, amountFreed); } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by governance or the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault) || msg.sender == governance()); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } */ function protectedTokens() internal view virtual returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyOwner { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } abstract contract BaseStrategyInitializable is BaseStrategy { event Cloned(address indexed clone); constructor(address _vault) public BaseStrategy(_vault) {} function initialize( address _vault, address _strategist, address _rewards, address _keeper ) external virtual { _initialize(_vault, _strategist, _rewards, _keeper); } function clone(address _vault) external returns (address) { return this.clone(_vault, msg.sender, msg.sender, msg.sender); } function clone( address _vault, address _strategist, address _rewards, address _keeper ) external returns (address newStrategy) { bytes20 addressBytes = bytes20(address(this)); assembly { let clone_code := mload(0x40) mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone_code, 0x14), addressBytes) mstore( add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) newStrategy := create(0, clone_code, 0x37) } BaseStrategyInitializable(newStrategy).initialize(_vault, _strategist, _rewards, _keeper); emit Cloned(newStrategy); } } pragma solidity 0.6.12; interface IGenericLender { function lenderName() external view returns (string memory); function nav() external view returns (uint256); function strategy() external view returns (address); function apr() external view returns (uint256); function weightedApr() external view returns (uint256); function withdraw(uint256 amount) external returns (uint256); function emergencyWithdraw(uint256 amount) external; function deposit() external; function withdrawAll() external returns (bool); function hasAssets() external view returns (bool); function aprAfterDeposit(uint256 amount) external view returns (uint256); function setDust(uint256 _dust) external; function sweep(address _token) external; } pragma solidity 0.6.12; interface IWantToEth { function wantToEth(uint256 input) external view returns (uint256); function ethToWant(uint256 input) external view returns (uint256); } pragma solidity 0.6.12; interface IUni { function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); } /******************** * * A lender optimisation strategy for any erc20 asset * https: * v0.3.1 * * This strategy works by taking plugins designed for standard lending platforms * It automatically chooses the best yield generating platform and adjusts accordingly * The adjustment is sub optimal so there is an additional option to manually set position * ********************* */ contract YearnGenericLender is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public constant uniswapRouter = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address public constant weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); uint256 public withdrawalThreshold = 1e16; uint256 public constant SECONDSPERYEAR = 31556952; IGenericLender[] public lenders; bool public externalOracle = false; address public wantToEthOracle; event Cloned(address indexed clone); constructor(address _vault) public BaseStrategy(_vault) { debtThreshold = 100 * 1e18; } function clone(address _vault) external returns (address newStrategy) { newStrategy = this.clone(_vault, msg.sender, msg.sender, msg.sender); } function clone( address _vault, address _strategist, address _rewards, address _keeper ) external returns (address newStrategy) { bytes20 addressBytes = bytes20(address(this)); assembly { let clone_code := mload(0x40) mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone_code, 0x14), addressBytes) mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) newStrategy := create(0, clone_code, 0x37) } YearnGenericLender(newStrategy).initialize(_vault, _strategist, _rewards, _keeper); emit Cloned(newStrategy); } function initialize( address _vault, address _strategist, address _rewards, address _keeper ) external virtual { _initialize(_vault, _strategist, _rewards, _keeper); } function setWithdrawalThreshold(uint256 _threshold) external onlyAuthorized { withdrawalThreshold = _threshold; } function setPriceOracle(address _oracle) external onlyAuthorized { wantToEthOracle = _oracle; } function name() external view override returns (string memory) { return "StrategyLenderYieldOptimiser"; } function addLender(address a) public onlyOwner { IGenericLender n = IGenericLender(a); require(n.strategy() == address(this), "Undocked Lender"); for (uint256 i = 0; i < lenders.length; i++) { require(a != address(lenders[i]), "Already Added"); } lenders.push(n); } function safeRemoveLender(address a) public onlyAuthorized { _removeLender(a, false); } function forceRemoveLender(address a) public onlyAuthorized { _removeLender(a, true); } function _removeLender(address a, bool force) internal { for (uint256 i = 0; i < lenders.length; i++) { if (a == address(lenders[i])) { bool allWithdrawn = lenders[i].withdrawAll(); if (!force) { require(allWithdrawn, "WITHDRAW FAILED"); } if (i != lenders.length - 1) { lenders[i] = lenders[lenders.length - 1]; } lenders.pop(); if (want.balanceOf(address(this)) > 0) { adjustPosition(0); } return; } } require(false, "NOT LENDER"); } struct lendStatus { string name; uint256 assets; uint256 rate; address add; } function lendStatuses() public view returns (lendStatus[] memory) { lendStatus[] memory statuses = new lendStatus[](lenders.length); for (uint256 i = 0; i < lenders.length; i++) { lendStatus memory s; s.name = lenders[i].lenderName(); s.add = address(lenders[i]); s.assets = lenders[i].nav(); s.rate = lenders[i].apr(); statuses[i] = s; } return statuses; } function estimatedTotalAssets() public view override returns (uint256) { uint256 nav = lentTotalAssets(); nav = nav.add(want.balanceOf(address(this))); return nav; } function numLenders() public view returns (uint256) { return lenders.length; } function estimatedAPR() public view returns (uint256) { uint256 bal = estimatedTotalAssets(); if (bal == 0) { return 0; } uint256 weightedAPR = 0; for (uint256 i = 0; i < lenders.length; i++) { weightedAPR = weightedAPR.add(lenders[i].weightedApr()); } return weightedAPR.div(bal); } function _estimateDebtLimitIncrease(uint256 change) internal view returns (uint256) { uint256 highestAPR = 0; uint256 aprChoice = 0; uint256 assets = 0; for (uint256 i = 0; i < lenders.length; i++) { uint256 apr = lenders[i].aprAfterDeposit(change); if (apr > highestAPR) { aprChoice = i; highestAPR = apr; assets = lenders[i].nav(); } } uint256 weightedAPR = highestAPR.mul(assets.add(change)); for (uint256 i = 0; i < lenders.length; i++) { if (i != aprChoice) { weightedAPR = weightedAPR.add(lenders[i].weightedApr()); } } uint256 bal = estimatedTotalAssets().add(change); return weightedAPR.div(bal); } function _estimateDebtLimitDecrease(uint256 change) internal view returns (uint256) { uint256 lowestApr = uint256(-1); uint256 aprChoice = 0; for (uint256 i = 0; i < lenders.length; i++) { uint256 apr = lenders[i].aprAfterDeposit(change); if (apr < lowestApr) { aprChoice = i; lowestApr = apr; } } uint256 weightedAPR = 0; for (uint256 i = 0; i < lenders.length; i++) { if (i != aprChoice) { weightedAPR = weightedAPR.add(lenders[i].weightedApr()); } else { uint256 asset = lenders[i].nav(); if (asset < change) { change = asset; } weightedAPR = weightedAPR.add(lowestApr.mul(change)); } } uint256 bal = estimatedTotalAssets().add(change); return weightedAPR.div(bal); } function estimateAdjustPosition() public view returns ( uint256 _lowest, uint256 _lowestApr, uint256 _highest, uint256 _potential ) { uint256 looseAssets = want.balanceOf(address(this)); _lowestApr = uint256(-1); _lowest = 0; uint256 lowestNav = 0; for (uint256 i = 0; i < lenders.length; i++) { if (lenders[i].hasAssets()) { uint256 apr = lenders[i].apr(); if (apr < _lowestApr) { _lowestApr = apr; _lowest = i; lowestNav = lenders[i].nav(); } } } uint256 toAdd = lowestNav.add(looseAssets); uint256 highestApr = 0; _highest = 0; for (uint256 i = 0; i < lenders.length; i++) { uint256 apr; apr = lenders[i].aprAfterDeposit(looseAssets); if (apr > highestApr) { highestApr = apr; _highest = i; } } _potential = lenders[_highest].aprAfterDeposit(toAdd); } function estimatedFutureAPR(uint256 newDebtLimit) public view returns (uint256) { uint256 oldDebtLimit = vault.strategies(address(this)).totalDebt; uint256 change; if (oldDebtLimit < newDebtLimit) { change = newDebtLimit - oldDebtLimit; return _estimateDebtLimitIncrease(change); } else { change = oldDebtLimit - newDebtLimit; return _estimateDebtLimitDecrease(change); } } function lentTotalAssets() public view returns (uint256) { uint256 nav = 0; for (uint256 i = 0; i < lenders.length; i++) { nav = nav.add(lenders[i].nav()); } return nav; } function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { _profit = 0; _loss = 0; _debtPayment = _debtOutstanding; uint256 lentAssets = lentTotalAssets(); uint256 looseAssets = want.balanceOf(address(this)); uint256 total = looseAssets.add(lentAssets); if (lentAssets == 0) { if (_debtPayment > looseAssets) { _debtPayment = looseAssets; } return (_profit, _loss, _debtPayment); } uint256 debt = vault.strategies(address(this)).totalDebt; if (total > debt) { _profit = total - debt; uint256 amountToFree = _profit.add(_debtPayment); if (amountToFree > 0 && looseAssets < amountToFree) { _withdrawSome(amountToFree.sub(looseAssets)); uint256 newLoose = want.balanceOf(address(this)); if (newLoose < amountToFree) { if (_profit > newLoose) { _profit = newLoose; _debtPayment = 0; } else { _debtPayment = Math.min(newLoose - _profit, _debtPayment); } } } } else { _loss = debt - total; uint256 amountToFree = _loss.add(_debtPayment); if (amountToFree > 0 && looseAssets < amountToFree) { _withdrawSome(amountToFree.sub(looseAssets)); uint256 newLoose = want.balanceOf(address(this)); if (newLoose < amountToFree) { if (_loss > newLoose) { _loss = newLoose; _debtPayment = 0; } else { _debtPayment = Math.min(newLoose - _loss, _debtPayment); } } } } } /* * Key logic. * The algorithm moves assets from lowest return to highest * like a very slow idiots bubble sort * we ignore debt outstanding for an easy life */ function adjustPosition(uint256 _debtOutstanding) internal override { _debtOutstanding; if (emergencyExit) { return; } if (lenders.length == 0) { return; } (uint256 lowest, uint256 lowestApr, uint256 highest, uint256 potential) = estimateAdjustPosition(); if (potential > lowestApr) { lenders[lowest].withdrawAll(); } uint256 bal = want.balanceOf(address(this)); if (bal > 0) { want.safeTransfer(address(lenders[highest]), bal); lenders[highest].deposit(); } } struct lenderRatio { address lender; uint16 share; } function manualAllocation(lenderRatio[] memory _newPositions) public onlyAuthorized { uint256 share = 0; for (uint256 i = 0; i < lenders.length; i++) { lenders[i].withdrawAll(); } uint256 assets = want.balanceOf(address(this)); for (uint256 i = 0; i < _newPositions.length; i++) { bool found = false; for (uint256 j = 0; j < lenders.length; j++) { if (address(lenders[j]) == _newPositions[i].lender) { found = true; } } require(found, "NOT LENDER"); share = share.add(_newPositions[i].share); uint256 toSend = assets.mul(_newPositions[i].share).div(1000); want.safeTransfer(_newPositions[i].lender, toSend); IGenericLender(_newPositions[i].lender).deposit(); } require(share == 1000, "SHARE!=1000"); } function _withdrawSome(uint256 _amount) internal returns (uint256 amountWithdrawn) { if (lenders.length == 0) { return 0; } if (_amount < withdrawalThreshold) { return 0; } amountWithdrawn = 0; uint256 j = 0; while (amountWithdrawn < _amount) { uint256 lowestApr = uint256(-1); uint256 lowest = 0; for (uint256 i = 0; i < lenders.length; i++) { if (lenders[i].hasAssets()) { uint256 apr = lenders[i].apr(); if (apr < lowestApr) { lowestApr = apr; lowest = i; } } } if (!lenders[lowest].hasAssets()) { return amountWithdrawn; } amountWithdrawn = amountWithdrawn.add(lenders[lowest].withdraw(_amount - amountWithdrawn)); j++; if (j >= 6) { return amountWithdrawn; } } } /* * Liquidate as many assets as possible to `want`, irregardless of slippage, * up to `_amountNeeded`. Any excess should be re-invested here as well. */ function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _amountFreed, uint256 _loss) { uint256 _balance = want.balanceOf(address(this)); if (_balance >= _amountNeeded) { return (_amountNeeded, 0); } else { uint256 received = _withdrawSome(_amountNeeded - _balance).add(_balance); if (received >= _amountNeeded) { return (_amountNeeded, 0); } else { return (received, 0); } } } function harvestTrigger(uint256 callCost) public view override returns (bool) { uint256 wantCallCost = _callCostToWant(callCost); return super.harvestTrigger(wantCallCost); } function ethToWant(uint256 _amount) internal view returns (uint256) { address[] memory path = new address[](2); path[0] = weth; path[1] = address(want); uint256[] memory amounts = IUni(uniswapRouter).getAmountsOut(_amount, path); return amounts[amounts.length - 1]; } function _callCostToWant(uint256 callCost) internal view returns (uint256) { uint256 wantCallCost; if (address(want) == weth) { wantCallCost = callCost; } else if (wantToEthOracle == address(0)) { wantCallCost = ethToWant(callCost); } else { wantCallCost = IWantToEth(wantToEthOracle).ethToWant(callCost); } return wantCallCost; } function tendTrigger(uint256 callCost) public view override returns (bool) { if (harvestTrigger(callCost)) { return false; } (uint256 lowest, uint256 lowestApr, , uint256 potential) = estimateAdjustPosition(); if (potential > lowestApr) { uint256 nav = lenders[lowest].nav(); uint256 profitIncrease = (nav.mul(potential) - nav.mul(lowestApr)).div(1e18).mul(maxReportDelay).div(SECONDSPERYEAR); uint256 wantCallCost = _callCostToWant(callCost); return (wantCallCost.mul(profitFactor) < profitIncrease); } } /* * revert if we can't withdraw full balance */ function prepareMigration(address _newStrategy) internal override { uint256 outstanding = vault.strategies(address(this)).totalDebt; (, uint256 loss, uint256 wantBalance) = prepareReturn(outstanding); } function protectedTokens() internal view override returns (address[] memory) { address[] memory protected = new address[](1); protected[0] = address(want); return protected; } function expectedReturn() public view returns (uint256) { uint256 estimateAssets = estimatedTotalAssets(); uint256 debt = vault.strategies(address(this)).totalDebt; if (debt > estimateAssets) { return 0; } else { return estimateAssets - debt; } } }
* @notice Adjust the Strategy's position. The purpose of tending isn't to realize gains, but to maximize yield by reinvesting any returns. See comments on `adjustPosition()`. This may only be called by governance, the strategist, or the keeper./
function tend() external onlyKeepers { adjustPosition(vault.debtOutstanding()); }
398,590
[ 1, 10952, 326, 19736, 1807, 1754, 18, 1021, 13115, 434, 268, 2846, 5177, 1404, 358, 225, 2863, 554, 314, 4167, 16, 1496, 358, 943, 10153, 2824, 635, 283, 5768, 10100, 1281, 1135, 18, 225, 2164, 5678, 603, 1375, 13362, 2555, 1435, 8338, 225, 1220, 2026, 1338, 506, 2566, 635, 314, 1643, 82, 1359, 16, 326, 609, 1287, 376, 16, 578, 326, 417, 9868, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 268, 409, 1435, 3903, 1338, 11523, 414, 288, 203, 540, 203, 3639, 5765, 2555, 12, 26983, 18, 323, 23602, 1182, 15167, 10663, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; // ---------------------------------------------------------------------------- // TOKENMOM DECENTRALIZED EXCHANGE Token(TM) Smart Contract V.1.1 // 토큰맘 탈중앙화거래소 토큰(TM) 스마트 컨트랙트 버전1.1 // Exchange URL : https://tokenmom.com // Trading FEE : 0.00% Event (Maker and Taker) // Symbol : TM // Name : TOKENMOM Token // Decimals : 18 // Total supply : 2,000,000,000 // 40% 800,000,000 Free TM token to Tokenmom users(Rewards & Referral) // 30% 600,000,000 Founder, team, exchange maintenance // 20% 400,000,000 Price stability and maintenance of TM Token(Burning) // 10% 200,000,000 Reserved funds to prepare for problems // 100% 2,000,000,000 TOTAL SUPPLY // ---------------------------------------------------------------------------- /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { _owner = msg.sender; } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(_owner); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer( IERC20 token, address to, uint256 value ) internal { require(token.transfer(to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { require(token.approve(spender, value)); } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } contract SignerRole { using Roles for Roles.Role; event SignerAdded(address indexed account); event SignerRemoved(address indexed account); Roles.Role private signers; constructor() public { _addSigner(msg.sender); } modifier onlySigner() { require(isSigner(msg.sender)); _; } function isSigner(address account) public view returns (bool) { return signers.has(account); } function addSigner(address account) public onlySigner { _addSigner(account); } function renounceSigner() public { _removeSigner(msg.sender); } function _addSigner(address account) internal { signers.add(account); emit SignerAdded(account); } function _removeSigner(address account) internal { signers.remove(account); emit SignerRemoved(account); } } contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private minters; constructor() public { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender)); _; } function isMinter(address account) public view returns (bool) { return minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { minters.remove(account); emit MinterRemoved(account); } } contract PauserRole { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private pausers; constructor() public { _addPauser(msg.sender); } modifier onlyPauser() { require(isPauser(msg.sender)); _; } function isPauser(address account) public view returns (bool) { return pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { pausers.remove(account); emit PauserRemoved(account); } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address owner, address spender ) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { require(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(value <= _balances[from]); require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != 0); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != 0); require(value <= _balances[account]); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); } } /** * @title TokenTimelock * @dev TokenTimelock is a token holder contract that will allow a * beneficiary to extract the tokens after a given release time */ contract TokenTimelock { using SafeERC20 for IERC20; // ERC20 basic token contract being held IERC20 private _token; // beneficiary of tokens after they are released address private _beneficiary; // timestamp when token release is enabled uint256 private _releaseTime; constructor( IERC20 token, address beneficiary, uint256 releaseTime ) public { // solium-disable-next-line security/no-block-members require(releaseTime > block.timestamp); _token = token; _beneficiary = beneficiary; _releaseTime = releaseTime; } /** * @return the token being held. */ function token() public view returns(IERC20) { return _token; } /** * @return the beneficiary of the tokens. */ function beneficiary() public view returns(address) { return _beneficiary; } /** * @return the time when the tokens are released. */ function releaseTime() public view returns(uint256) { return _releaseTime; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public { // solium-disable-next-line security/no-block-members require(block.timestamp >= _releaseTime); uint256 amount = _token.balanceOf(address(this)); require(amount > 0); _token.safeTransfer(_beneficiary, amount); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is PauserRole { event Paused(); event Unpaused(); bool private _paused = false; /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns(bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(); } } /** * @title ERC20Mintable * @dev ERC20 minting logic */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address to, uint256 value ) public onlyMinter returns (bool) { _mint(to, value); return true; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract ERC20Burnable is ERC20 { /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The address which you want to send tokens from * @param value uint256 The amount of token to be burned */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } } /** * @title Pausable token * @dev ERC20 modified with pausable transfers. **/ contract ERC20Pausable is ERC20, Pausable { function transfer( address to, uint256 value ) public whenNotPaused returns (bool) { return super.transfer(to, value); } function transferFrom( address from, address to, uint256 value ) public whenNotPaused returns (bool) { return super.transferFrom(from, to, value); } function approve( address spender, uint256 value ) public whenNotPaused returns (bool) { return super.approve(spender, value); } function increaseAllowance( address spender, uint addedValue ) public whenNotPaused returns (bool success) { return super.increaseAllowance(spender, addedValue); } function decreaseAllowance( address spender, uint subtractedValue ) public whenNotPaused returns (bool success) { return super.decreaseAllowance(spender, subtractedValue); } } contract TMtoken is ERC20Pausable, ERC20Burnable, ERC20Mintable { string public constant name = "Tokenmom"; string public constant symbol = "TM"; uint8 public constant decimals = 18; uint256 public constant INITIAL_SUPPLY = 2000000000 * (10 ** uint256(decimals)); /** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor() public { _mint(msg.sender, INITIAL_SUPPLY); } }
* @title Pausable @dev Base contract which allows children to implement an emergency stop mechanism./
contract Pausable is PauserRole { event Paused(); event Unpaused(); bool private _paused = false; function paused() public view returns(bool) { return _paused; } modifier whenNotPaused() { require(!_paused); _; } modifier whenPaused() { require(_paused); _; } function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(); } function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(); } }
1,459,231
[ 1, 16507, 16665, 225, 3360, 6835, 1492, 5360, 2325, 358, 2348, 392, 801, 24530, 2132, 12860, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 21800, 16665, 353, 21800, 1355, 2996, 288, 203, 225, 871, 21800, 3668, 5621, 203, 225, 871, 1351, 8774, 3668, 5621, 203, 203, 225, 1426, 3238, 389, 8774, 3668, 273, 629, 31, 203, 203, 225, 445, 17781, 1435, 1071, 1476, 1135, 12, 6430, 13, 288, 203, 565, 327, 389, 8774, 3668, 31, 203, 225, 289, 203, 203, 225, 9606, 1347, 1248, 28590, 1435, 288, 203, 565, 2583, 12, 5, 67, 8774, 3668, 1769, 203, 565, 389, 31, 203, 225, 289, 203, 203, 225, 9606, 1347, 28590, 1435, 288, 203, 565, 2583, 24899, 8774, 3668, 1769, 203, 565, 389, 31, 203, 225, 289, 203, 203, 225, 445, 11722, 1435, 1071, 1338, 16507, 1355, 1347, 1248, 28590, 288, 203, 565, 389, 8774, 3668, 273, 638, 31, 203, 565, 3626, 21800, 3668, 5621, 203, 225, 289, 203, 203, 225, 445, 640, 19476, 1435, 1071, 1338, 16507, 1355, 1347, 28590, 288, 203, 565, 389, 8774, 3668, 273, 629, 31, 203, 565, 3626, 1351, 8774, 3668, 5621, 203, 225, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: None // HungryBunz Implementation V1 pragma solidity ^0.8.0; import "./Ownable.sol"; import "./PaymentSplitter.sol"; import "./ERC721.sol"; import "./ECDSA.sol"; import "./Strings.sol"; import "./Initializable.sol"; contract OwnableDelegateProxy { } contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } interface ISnax { function computeMultiplier(address requester, bytes16 targetStats, uint16[] memory team) external view returns (uint256); function feed(bytes16 stats, uint256 wholeBurn) external view returns (bytes16); } interface IItem { function applyProperties(bytes32 properties, uint16 item) external view returns (bytes32); } interface nom { function burn(address account, uint256 amount) external; function unstake(uint16[] memory tokenIds, address targetAccount) external; } interface IMetadataGen { function generateStats(address requester, uint16 newTokenId, uint32 password) external view returns (bytes16); function generateAttributes(address requester, uint16 newTokenId, uint32 password) external view returns (bytes16); } interface IMetadataRenderer { function renderMetadata(uint16 tokenId, bytes16 atts, bytes16 stats) external view returns (string memory); } interface IEvolve { function evolve(uint8 next1of1, uint16 burntId, address owner, bytes32 t1, bytes32 t2) external view returns(bytes32); } contract HungryBunz is Initializable, PaymentSplitter, Ownable, ERC721 { //****************************************************** //CRITICAL CONTRACT PARAMETERS //****************************************************** using ECDSA for bytes32; using Strings for uint256; bool _saleStarted; bool _saleEnd; bool _metadataRevealed; bool _transferPaused; bool _bypassMintAuth; uint8 _season; //Defines rewards season uint8 _1of1Index; //Next available 1 of 1 uint16 _totalSupply; uint16 _maxSupply; uint256 _maxPerWallet; uint256 _baseMintPrice; uint256 _nameTagPrice; //Address rather than interface because this is used as an address //for sender checks more often than used as interface. address _nomContractAddress; //Address rather than interface because this is used as an address //for sender checks more often than used as interface. address _xLayerGateway; address _openSea; address _signerAddress; //Public address for mint auth signature IItem items; ISnax snax; IMetadataRenderer renderer; IMetadataGen generator; IEvolve _evolver; ProxyRegistry _osProxies; //****************************************************** //GAMEPLAY MECHANICS //****************************************************** uint8 _maxRank; //Maximum rank setting to allow additional evolutions over time... mapping(uint8 => mapping(uint8 => uint16)) _evolveThiccness; //Required thiccness total to evolve by current rank mapping(uint8 => uint8) _1of1Allotted; //Allocated 1 of 1 pieces per season mapping(uint8 => bool) _1of1sOnThisLayer; //Permit 1/1s on this layer and season. mapping(uint8 => uint8) _maxStakeRankBySeason; //****************************************************** //ANTI BOT AND FAIR LAUNCH HASH TABLES AND ARRAYS //****************************************************** mapping(address => uint256) tokensMintedByAddress; //Tracks total NFTs minted to limit individual wallets. //****************************************************** //METADATA HASH TABLES //****************************************************** //Bools stored as uint256 to shave a few units off gas fees. mapping(uint16 => bytes32) metadataById; //Stores critical metadata by ID mapping(uint16 => bytes32) _lockedTokens; //Tracks tokens locked for staking mapping(uint16 => uint256) _inactiveOnThisChain; //Tracks which tokens are active on current chain mapping(bytes16 => uint256) _usedCombos; //Stores attribute combo hashes to guarantee uniqueness mapping(uint16 => string) namedBunz; //Stores names for bunz //****************************************************** //CONTRACT CONSTRUCTOR AND INITIALIZER FOR PROXY //****************************************************** constructor() { //Initialize ownable on implementation //to prevent any misuse of implementation //contract. ownableInit(); } function initHungryBunz ( address[] memory payees, uint256[] memory paymentShares ) external initializer { //Require to prevent users from initializing //implementation contract require(owner() == address(0) || owner() == msg.sender, "No."); ownableInit(); initPaymentSplitter(payees, paymentShares); initERC721("HungryBunz", "BUNZ"); _maxRank = 2; _maxStakeRankBySeason[0] = 1; _transferPaused = true; _signerAddress = 0xF658480075BA1158f12524409066Ca495b54b0dD; _baseMintPrice = 0.06 ether; _maxSupply = 8888; _maxPerWallet = 5; _nameTagPrice = 200 * 10**18; _evolveThiccness[0][1] = 5000; _evolveThiccness[0][2] = 30000; //Guesstimate on targets for season 1 _evolveThiccness[1][1] = 15000; _evolveThiccness[1][2] = 30000; _1of1Index = 1; //Initialize at 1 //WL Opensea Proxies for Cheaper Trading _openSea = 0xa5409ec958C83C3f309868babACA7c86DCB077c1; _osProxies = ProxyRegistry(_openSea); } //****************************************************** //OVERRIDES TO HANDLE CONFLICTS BETWEEN IMPORTS //****************************************************** function _burn(uint256 tokenId) internal virtual override(ERC721) { ERC721._burn(tokenId); delete metadataById[uint16(tokenId)]; _totalSupply -= 1; } //Access to ERC721 implementation for use within app contracts. function applicationOwnerOf(uint256 tokenId) public view returns (address) { return ERC721.ownerOf(tokenId); } //Override ownerOf to accomplish lower cost alternative to lock tokens for staking. function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) { address owner = ERC721.ownerOf(tokenId); if (lockedForStaking(tokenId)) { owner = address(uint160(owner) - 1); } else if (_inactiveOnThisChain[uint16(tokenId)] == 1) { owner = address(0); } return owner; } //Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. function isApprovedForAll( address owner, address operator ) public view override(ERC721) returns (bool) { if (address(_osProxies.proxies(owner)) == operator) { return true; } return ERC721.isApprovedForAll(owner, operator); } //Override for simulated transfers and burns. function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual override(ERC721) returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); //Transfers not allowed while inactive on this chain. Transfers //potentially allowed when spender is foraging contract and //token is locked for staking. return ((spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender) || spender == address(this)) && (!lockedForStaking(tokenId) || spender == _nomContractAddress) && _inactiveOnThisChain[uint16(tokenId)] == 0 && !_transferPaused); } //****************************************************** //OWNER ONLY FUNCTIONS TO CONNECT CHILD CONTRACTS. //****************************************************** function ccNom(address contractAddress) public onlyOwner { //Not cast to interface as this will need to be cast to address //more often than not. _nomContractAddress = contractAddress; } function ccGateway(address contractAddress) public onlyOwner { //Notably not cast to interface because this contract never calls //functions on gateway. _xLayerGateway = contractAddress; } function ccSnax(ISnax contractAddress) public onlyOwner { snax = contractAddress; } function ccItems(IItem contractAddress) public onlyOwner { items = contractAddress; } function ccGenerator(IMetadataGen contractAddress) public onlyOwner { generator = contractAddress; } function ccRenderer(IMetadataRenderer newRenderer) public onlyOwner { renderer = newRenderer; } function ccEvolution(IEvolve newEvolver) public onlyOwner { _evolver = newEvolver; } function getInterfaces() external view returns (bytes memory) { return abi.encodePacked( _nomContractAddress, _xLayerGateway, address(snax), address(items), address(generator), address(renderer), address(_evolver) ); } //****************************************************** //OWNER ONLY FUNCTIONS TO MANAGE CRITICAL PARAMETERS //****************************************************** function startSale() public onlyOwner { require(_saleEnd == false, "Cannot restart sale."); _saleStarted = true; } function endSale() public onlyOwner { _saleStarted = false; _saleEnd = true; } function enableTransfer() public onlyOwner { _transferPaused = false; } //Emergency transfer pause to prevent innapropriate transfer of tokens. function pauseTransfer() public onlyOwner { _transferPaused = true; } function changeWalletLimit(uint16 newLimit) public onlyOwner { //Set to 1 higher than limit for cheaper less than check! _maxPerWallet = newLimit; } function reduceSupply(uint16 newSupply) public onlyOwner { require (newSupply < _maxSupply, "Can only reduce supply"); require (newSupply > _totalSupply, "Cannot reduce below current!"); _maxSupply = newSupply; } function update1of1Index(uint8 oneOfOneIndex) public onlyOwner { //This function is provided exclusively so that owner may //update 1of1Index to facilitate creation of 1of1s on L2 //if this is deemed to be a feature of interest to community _1of1Index = oneOfOneIndex; } function startNewSeason(uint8 oneOfOneCount, bool enabledOnThisLayer, uint8 maxStakeRank) public onlyOwner { //Require all 1 of 1s for current season claimed before //starting a new season. L2 seasons will require sync. require(_1of1Index == _1of1Allotted[_season], "No."); _season++; _1of1Allotted[_season] = oneOfOneCount + _1of1Index; _1of1sOnThisLayer[_season] = enabledOnThisLayer; _maxStakeRankBySeason[_season] = maxStakeRank; } function addRank(uint8 newRank) public onlyOwner { //Used to enable third, fourth, etc. evolution levels. _maxRank = newRank; } function updateEvolveThiccness(uint8 rank, uint8 season, uint16 threshold) public onlyOwner { //Rank as current. E.G. (1, 10000) sets threshold to evolve to rank 2 //to 10000 pounds or thiccness points _evolveThiccness[season][rank] = threshold; } function setPriceToName(uint256 newPrice) public onlyOwner { _nameTagPrice = newPrice; } function reveal() public onlyOwner { _metadataRevealed = true; } function bypassMintAuth() public onlyOwner { _bypassMintAuth = true; } //****************************************************** //VIEWS FOR CRITICAL INFORMATION //****************************************************** function baseMintPrice() public view returns (uint256) { return _baseMintPrice; } function totalMintPrice(uint8 numberOfTokens) public view returns (uint256) { return _baseMintPrice * numberOfTokens; } function totalSupply() public view returns (uint256) { return _totalSupply; } function maxSupply() public view returns (uint256) { return _maxSupply; } //****************************************************** //ANTI-BOT PASSWORD HANDLERS //****************************************************** function hashTransaction(address sender, uint256 qty, bytes8 salt) private pure returns(bytes32) { bytes32 hash = keccak256(abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked(sender, qty, salt))) ); return hash; } function matchAddresSigner(bytes32 hash, bytes memory signature) public view returns(bool) { return (_signerAddress == hash.recover(signature)); } //****************************************************** //TOKENURI OVERRIDE RELOCATED TO BELOW UTILITY FUNCTIONS //****************************************************** function tokenURI(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "Token Doesn't Exist"); //Heavy lifting is done by rendering contract. bytes16 atts = serializeAtts(uint16(tokenId)); bytes16 stats = serializeStats(uint16(tokenId)); return renderer.renderMetadata(uint16(tokenId), atts, stats); } function _writeSerializedAtts(uint16 tokenId, bytes16 newAtts) internal { bytes16 currentStats = serializeStats(tokenId); metadataById[tokenId] = bytes32(abi.encodePacked(newAtts, currentStats)); } function writeSerializedAtts(uint16 tokenId, bytes16 newAtts) external { require(msg.sender == _xLayerGateway, "Not Gateway!"); _writeSerializedAtts(tokenId, newAtts); } function serializeAtts(uint16 tokenId) public view returns (bytes16) { return _metadataRevealed ? bytes16(metadataById[tokenId]) : bytes16(0); } function _writeSerializedStats(uint16 tokenId, bytes16 newStats) internal { bytes16 currentAtts = serializeAtts(tokenId); metadataById[tokenId] = bytes32(abi.encodePacked(currentAtts, newStats)); } function writeSerializedStats(uint16 tokenId, bytes16 newStats) external { require(msg.sender == _xLayerGateway, "Not Gateway!"); _writeSerializedStats(tokenId, newStats); } function serializeStats(uint16 tokenId) public view returns (bytes16) { return _metadataRevealed ? bytes16(metadataById[tokenId] << 128) : bytes16(0); } function propertiesBytes(uint16 tokenId) external view returns(bytes32) { return metadataById[tokenId]; } //****************************************************** //STAKING VIEWS //****************************************************** function lockedForStaking (uint256 tokenId) public view returns(bool) { return uint8(bytes1(_lockedTokens[uint16(tokenId)])) == 1; } //Check stake checks both staking status and ownership. function checkStake (uint16 tokenId) external view returns (address) { return lockedForStaking(tokenId) ? applicationOwnerOf(tokenId) : address(0); } //Returns staking timestamp function stakeStart (uint16 tokenId) public view returns(uint248) { return uint248(bytes31(_lockedTokens[tokenId] << 8)); } //****************************************************** //STAKING LOCK / UNLOCK AND TIMESTAMP FUNCTION //****************************************************** function updateStakeStart (uint16 tokenId, uint248 newTime) external { uint8 stakeStatus = uint8(bytes1(_lockedTokens[tokenId])); _lockedTokens[tokenId] = bytes32(abi.encodePacked(stakeStatus, newTime)); } function lockForStaking (uint16 tokenId) external { //Nom contract performs owner of check to prevent malicious locking require(msg.sender == _nomContractAddress, "Unauthorized"); require(!lockedForStaking(tokenId), "Already locked!"); //Metadata byte 16 is rank, 17 is season. require(_maxStakeRankBySeason[uint8(metadataById[tokenId][17])] >= uint8(metadataById[tokenId][16]), "Cannot Stake"); bytes31 currentTimestamp = bytes31(_lockedTokens[tokenId] << 8); //Food coma period will persist after token transfer. uint248 stakeTimestamp = uint248(currentTimestamp) < block.timestamp ? uint248(block.timestamp) : uint248(currentTimestamp); _lockedTokens[tokenId] = bytes32(abi.encodePacked(uint8(1), stakeTimestamp)); //Event with ownerOf override clears secondary listings. emit Transfer(applicationOwnerOf(tokenId), address(uint160(applicationOwnerOf(tokenId)) - 1), tokenId); } function unlock (uint16 tokenId, uint248 newTime) external { //Nom contract performs owner of check to prevent malicious unlocking require(msg.sender == _nomContractAddress, "Unauthorized"); require(lockedForStaking(tokenId), "Not locked!"); _lockedTokens[tokenId] = bytes32(abi.encodePacked(uint8(0), newTime)); //Event with ownerOf override restores token in marketplace accounts emit Transfer(address(uint160(applicationOwnerOf(tokenId)) - 1), applicationOwnerOf(tokenId), tokenId); } //****************************************************** //L2 FUNCTIONALITY //****************************************************** function setInactiveOnThisChain(uint16 tokenId) external { //This can only be called by the gateway contract to prevent exploits. //Gateway will check ownership, and setting inactive is a pre-requisite //to issuing the message to mint token on the other chain. By verifying //that we aren't trying to re-teleport here, we save back and forth to //check the activity status of the token on the gateway contract. require(msg.sender == _xLayerGateway, "Not Gateway!"); require(_inactiveOnThisChain[tokenId] == 0, "Already inactive!"); //Unstake token to mitigate very minimal exploit by staking then immediately //bridging to another layer to accrue slightly more tokens in a given time. uint16[] memory lockedTokens = new uint16[](1); lockedTokens[0] = tokenId; nom(_nomContractAddress).unstake(lockedTokens, applicationOwnerOf(tokenId)); _inactiveOnThisChain[tokenId] = 1; //Event with ownerOf override clears secondary listings. emit Transfer(applicationOwnerOf(tokenId), address(0), tokenId); } function setActiveOnThisChain(uint16 tokenId, bytes memory metadata, address sender) external { require(msg.sender == _xLayerGateway, "Not Gateway!"); if (_exists(uint256(tokenId))) { require(_inactiveOnThisChain[tokenId] == 1, "Already active"); } _inactiveOnThisChain[tokenId] = 0; if(!_exists(uint256(tokenId))) { _safeMint(sender, tokenId); } else { address localOwner = applicationOwnerOf(tokenId); if (localOwner != sender) { //This indicates a transaction occurred //on the other layer. Transfer. safeTransferFrom(localOwner, sender, tokenId); } } metadataById[tokenId] = bytes32(metadata); uint16 burntId = uint16(bytes2(abi.encodePacked(metadata[14], metadata[15]))); if (_exists(uint256(burntId))) { _burn(burntId); } //Event with ownerOf override restores token in marketplace accounts emit Transfer(address(0), applicationOwnerOf(tokenId), tokenId); } //****************************************************** //MINT FUNCTIONS //****************************************************** function _mintToken(address to, uint32 password, uint16 newId) internal { //Generate data in mint function to reduce calls. Cost 40k. //While loop and additional write operation is necessary //evil to prevent duplicates. bytes16 newAtts; while(newAtts == 0 || _usedCombos[newAtts] == 1) { newAtts = generator.generateAttributes(to, newId, password); password++; } _usedCombos[newAtts] = 1; bytes16 newStats = generator.generateStats(to, newId, password); metadataById[newId] = bytes32(abi.encodePacked(newAtts, newStats)); //Cost 20k. _safeMint(to, newId); } function publicAccessMint(uint8 numberOfTokens, bytes memory signature, bytes8 salt) public payable { //Between the use of msg.sender in the tx hash for purchase authorization, //and the requirements for wallet limiter, saving the salt is an undesirable //gas add. Users may re-use the same hash for multiple Txs if they prefer, //instead of maxing out their mint the first time. bytes32 txHash = hashTransaction(msg.sender, numberOfTokens, salt); require(_saleStarted, "Sale not live."); if (!_bypassMintAuth) { require(matchAddresSigner(txHash, signature), "Unauthorized!"); } require((numberOfTokens + tokensMintedByAddress[msg.sender] < _maxPerWallet), "Exceeded max mint."); require(_totalSupply + numberOfTokens <= _maxSupply, "Not enough supply"); require(msg.value >= totalMintPrice(numberOfTokens), "Insufficient funds."); //Set tokens minted by address before calling internal mint //to revert on attempted reentry to bypass wallet limit. uint16 offset = _totalSupply; tokensMintedByAddress[msg.sender] += numberOfTokens; _totalSupply += numberOfTokens; //Set once to save a few k gas for (uint i = 0; i < numberOfTokens; i++) { offset++; _mintToken(msg.sender, uint32(bytes4(signature)), offset); } } //****************************************************** //BURN NOM FOR STAT BOOSTS //****************************************************** //Team must be passed as an argument since gas fees to enumerate a //user's collection with Enumerable or similar are too high to justify. //Sanitization of the input array is done on the snax contract. function consume(uint16 consumer, uint256 burn, uint16[] memory team) public { //We only check that a token is active on this chain. //You may burn NOM to boost friends' NFTs if you wish. //You may also burn NOM to feed currently staked Bunz require(_inactiveOnThisChain[consumer] == 0, "Not active on this chain!"); //Attempt to burn requisite amount of NOM. Will revert if //balance insufficient. This contract is approved burner //on NOM contract by default. nom(_nomContractAddress).burn(msg.sender, burn); uint256 wholeBurnRaw = burn / 10 ** 18; //Convert to integer units. bytes16 currentStats = serializeStats(consumer); //Computation done in snax contract for upgradability. Stack depth //limits require us to break the multiplier calc out into a separate //call to the snax contract. uint256 multiplier = snax.computeMultiplier(msg.sender, currentStats, team); //Returns BPS uint256 wholeBurn = (wholeBurnRaw * multiplier) / 10000; //Snax contract will take a tokenId, retrieve critical stats //and then modify stats, primarily thiccness, based on total //tokens burned. Output bytes are written back to struct. bytes16 transformedStats = snax.feed(currentStats, wholeBurn); _writeSerializedStats(consumer, transformedStats); } //****************************************************** //ATTACH ITEM //****************************************************** function attach(uint16 base, uint16 consumableItem) public { //This function will call another function on the item //NFT contract which will burn an item, apply its properties //to the base NFT, and return these values. require(msg.sender == applicationOwnerOf(base), "Don't own this token"); //Owner of check performed in item contract require(_inactiveOnThisChain[base] == 0, "Not active on this chain!"); bytes32 transformedProperties = items.applyProperties(metadataById[base], consumableItem); metadataById[base] = transformedProperties; } //****************************************************** //NAME BUNZ //****************************************************** function getNameTagPrice() public view returns(uint256) { return _nameTagPrice; } function name(uint16 tokenId, string memory newName) public { require(msg.sender == applicationOwnerOf(tokenId), "Don't own this token"); //Owner of check performed in item contract require(_inactiveOnThisChain[tokenId] == 0, "Not active on this chain!"); //Attempt to burn requisite amount of NOM. Will revert if //balance insufficient. This contract is approved burner //on NOM contract by default. nom(_nomContractAddress).burn(msg.sender, _nameTagPrice); namedBunz[tokenId] = newName; } //Hook for name not presently used in metadata render contract. //Provided for future use. function getTokenName(uint16 tokenId) public view returns(string memory) { return namedBunz[tokenId]; } //****************************************************** //PRESTIGE SYSTEM //****************************************************** function prestige(uint16[] memory tokenIds) public { //This is ugly, but the gas savings elsewhere justify this spaghetti. for(uint16 i = 0; i < tokenIds.length; i++) { if (uint8(metadataById[tokenIds[i]][17]) != _season) { bytes16 currentAtts = serializeAtts(tokenIds[i]); bytes12 currentStats = bytes12(metadataById[tokenIds[i]] << 160); //Atts and rank (byte 16) stay the same. Season (byte 17) and thiccness (bytes 18 and 19) change. metadataById[tokenIds[i]] = bytes32(abi.encodePacked( currentAtts, metadataById[tokenIds[i]][16], bytes1(_season), bytes2(0), currentStats )); } } } //****************************************************** //EVOLUTION MECHANISM //****************************************************** function evolve(uint16 firstToken, uint16 secondToken) public { uint8 rank = uint8(metadataById[firstToken][16]); require((rank == uint8(metadataById[secondToken][16])) && (rank < _maxRank), "Can't evolve these bunz"); uint8 season1 = uint8(metadataById[firstToken][17]); uint8 season = uint8(metadataById[secondToken][17]) > season1 ? uint8(metadataById[secondToken][17]) : season1; uint16 thiccness = uint16(bytes2(abi.encodePacked(metadataById[firstToken][18], metadataById[firstToken][19]))) + uint16(bytes2(abi.encodePacked(metadataById[secondToken][18], metadataById[secondToken][19]))); //ownerOf will return the 0 address if tokens are on another layer, and address -1 if staked. //Forcing unstake before evolve does not add enough to gas fees to justify the complex //logic to gracefully handle token burn while staked without introducing possible attack //vectors. require(ownerOf(firstToken) == msg.sender && ownerOf(secondToken) == msg.sender, "Not called by owner."); require(ownerOf(firstToken) == applicationOwnerOf(firstToken), "Unlucky"); require(thiccness >= _evolveThiccness[season][rank], "Not thicc enough."); //Below logic uses the higher season of the two tokens, since otherwise //tying this to global _season would allow users to earn 1/1s without //prestiging. uint8 next1of1 = (_1of1Index <= _1of1Allotted[season]) && _1of1sOnThisLayer[season] ? _1of1Index : 0; bytes32 evolvedToken = _evolver.evolve(next1of1, secondToken, msg.sender, metadataById[firstToken], metadataById[secondToken]); if (uint8(evolvedToken[8]) != 0) { _1of1Index++; } metadataById[firstToken] = evolvedToken; _burn(secondToken); } }
******************************************************OWNER ONLY FUNCTIONS TO CONNECT CHILD CONTRACTS.******************************************************Not cast to interface as this will need to be cast to addressmore often than not.
function ccNom(address contractAddress) public onlyOwner { _nomContractAddress = contractAddress; }
12,149,218
[ 1, 29602, 20747, 13690, 55, 8493, 21593, 6469, 11382, 8020, 2849, 1268, 55, 18, 1248, 4812, 358, 1560, 487, 333, 903, 1608, 358, 506, 4812, 358, 1758, 10161, 16337, 2353, 486, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4946, 26685, 12, 2867, 6835, 1887, 13, 1071, 1338, 5541, 288, 203, 3639, 389, 12306, 8924, 1887, 273, 6835, 1887, 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 ]
pragma solidity ^0.8.0; // SPDX-License-Identifier: MIT import "./interfaces/IFinancing.sol"; import "../core/DaoRegistry.sol"; import "../extensions/bank/Bank.sol"; import "../adapters/interfaces/IVoting.sol"; import "../guards/AdapterGuard.sol"; import "./modifiers/Reimbursable.sol"; import "../helpers/DaoHelper.sol"; /** MIT License Copyright (c) 2020 Openlaw Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ contract FinancingContract is IFinancing, AdapterGuard, Reimbursable { struct ProposalDetails { address applicant; // the proposal applicant address, can not be a reserved address uint256 amount; // the amount requested for funding address token; // the token address in which the funding must be sent to } // keeps track of all financing proposals handled by each dao mapping(address => mapping(bytes32 => ProposalDetails)) public proposals; /** * @notice Creates and sponsors a financing proposal. * @dev Applicant address must not be reserved. * @dev Token address must be allowed/supported by the DAO Bank. * @dev Requested amount must be greater than zero. * @dev Only members of the DAO can sponsor a financing proposal. * @param dao The DAO Address. * @param proposalId The proposal id. * @param applicant The applicant address. * @param token The token to receive the funds. * @param amount The desired amount. * @param data Additional details about the financing proposal. */ // slither-disable-next-line reentrancy-benign function submitProposal( DaoRegistry dao, bytes32 proposalId, address applicant, address token, uint256 amount, bytes memory data ) external override reimbursable(dao) { require(amount > 0, "invalid requested amount"); BankExtension bank = BankExtension( dao.getExtensionAddress(DaoHelper.BANK) ); require(bank.isTokenAllowed(token), "token not allowed"); require( DaoHelper.isNotReservedAddress(applicant), "applicant using reserved address" ); dao.submitProposal(proposalId); ProposalDetails storage proposal = proposals[address(dao)][proposalId]; proposal.applicant = applicant; proposal.amount = amount; proposal.token = token; IVoting votingContract = IVoting( dao.getAdapterAddress(DaoHelper.VOTING) ); address sponsoredBy = votingContract.getSenderAddress( dao, address(this), data, msg.sender ); dao.sponsorProposal(proposalId, sponsoredBy, address(votingContract)); votingContract.startNewVotingForProposal(dao, proposalId, data); } /** * @notice Processing a financing proposal to grant the requested funds. * @dev Only proposals that were not processed are accepted. * @dev Only proposals that were sponsored are accepted. * @dev Only proposals that passed can get processed and have the funds released. * @param dao The DAO Address. * @param proposalId The proposal id. */ // slither-disable-next-line reentrancy-benign function processProposal(DaoRegistry dao, bytes32 proposalId) external override reimbursable(dao) { ProposalDetails memory details = proposals[address(dao)][proposalId]; IVoting votingContract = IVoting(dao.votingAdapter(proposalId)); require(address(votingContract) != address(0), "adapter not found"); require( votingContract.voteResult(dao, proposalId) == IVoting.VotingState.PASS, "proposal needs to pass" ); dao.processProposal(proposalId); BankExtension bank = BankExtension( dao.getExtensionAddress(DaoHelper.BANK) ); bank.subtractFromBalance( DaoHelper.GUILD, details.token, details.amount ); bank.addToBalance(details.applicant, details.token, details.amount); } }
* @notice Creates and sponsors a financing proposal. @dev Applicant address must not be reserved. @dev Token address must be allowed/supported by the DAO Bank. @dev Requested amount must be greater than zero. @dev Only members of the DAO can sponsor a financing proposal. @param dao The DAO Address. @param proposalId The proposal id. @param applicant The applicant address. @param token The token to receive the funds. @param amount The desired amount. @param data Additional details about the financing proposal./ slither-disable-next-line reentrancy-benign
function submitProposal( DaoRegistry dao, bytes32 proposalId, address applicant, address token, uint256 amount, bytes memory data ) external override reimbursable(dao) { require(amount > 0, "invalid requested amount"); BankExtension bank = BankExtension( dao.getExtensionAddress(DaoHelper.BANK) ); require(bank.isTokenAllowed(token), "token not allowed"); require( DaoHelper.isNotReservedAddress(applicant), "applicant using reserved address" ); dao.submitProposal(proposalId); ProposalDetails storage proposal = proposals[address(dao)][proposalId]; proposal.applicant = applicant; proposal.amount = amount; proposal.token = token; IVoting votingContract = IVoting( dao.getAdapterAddress(DaoHelper.VOTING) ); address sponsoredBy = votingContract.getSenderAddress( dao, address(this), data, msg.sender ); dao.sponsorProposal(proposalId, sponsoredBy, address(votingContract)); votingContract.startNewVotingForProposal(dao, proposalId, data); }
13,084,723
[ 1, 2729, 471, 272, 500, 87, 1383, 279, 574, 304, 2822, 14708, 18, 225, 1716, 1780, 970, 1758, 1297, 486, 506, 8735, 18, 225, 3155, 1758, 1297, 506, 2935, 19, 4127, 635, 326, 463, 20463, 25610, 18, 225, 25829, 3844, 1297, 506, 6802, 2353, 3634, 18, 225, 5098, 4833, 434, 326, 463, 20463, 848, 272, 500, 2467, 279, 574, 304, 2822, 14708, 18, 225, 15229, 1021, 463, 20463, 5267, 18, 225, 14708, 548, 1021, 14708, 612, 18, 225, 513, 1780, 970, 1021, 513, 1780, 970, 1758, 18, 225, 1147, 1021, 1147, 358, 6798, 326, 284, 19156, 18, 225, 3844, 1021, 6049, 3844, 18, 225, 501, 15119, 3189, 2973, 326, 574, 304, 2822, 14708, 18, 19, 2020, 2927, 17, 8394, 17, 4285, 17, 1369, 283, 8230, 12514, 17, 19425, 724, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4879, 14592, 12, 203, 3639, 463, 6033, 4243, 15229, 16, 203, 3639, 1731, 1578, 14708, 548, 16, 203, 3639, 1758, 513, 1780, 970, 16, 203, 3639, 1758, 1147, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 1731, 3778, 501, 203, 565, 262, 3903, 3849, 283, 381, 70, 25152, 429, 12, 2414, 83, 13, 288, 203, 3639, 2583, 12, 8949, 405, 374, 16, 315, 5387, 3764, 3844, 8863, 203, 3639, 25610, 3625, 11218, 273, 25610, 3625, 12, 203, 5411, 15229, 18, 588, 3625, 1887, 12, 11412, 2276, 18, 38, 20201, 13, 203, 3639, 11272, 203, 3639, 2583, 12, 10546, 18, 291, 1345, 5042, 12, 2316, 3631, 315, 2316, 486, 2935, 8863, 203, 3639, 2583, 12, 203, 5411, 463, 6033, 2276, 18, 291, 1248, 10435, 1887, 12, 438, 1780, 970, 3631, 203, 5411, 315, 438, 1780, 970, 1450, 8735, 1758, 6, 203, 3639, 11272, 203, 3639, 15229, 18, 9297, 14592, 12, 685, 8016, 548, 1769, 203, 203, 3639, 19945, 3790, 2502, 14708, 273, 450, 22536, 63, 2867, 12, 2414, 83, 13, 6362, 685, 8016, 548, 15533, 203, 3639, 14708, 18, 438, 1780, 970, 273, 513, 1780, 970, 31, 203, 3639, 14708, 18, 8949, 273, 3844, 31, 203, 3639, 14708, 18, 2316, 273, 1147, 31, 203, 203, 3639, 21602, 17128, 331, 17128, 8924, 273, 21602, 17128, 12, 203, 5411, 15229, 18, 588, 4216, 1887, 12, 11412, 2276, 18, 58, 1974, 1360, 13, 203, 3639, 11272, 203, 3639, 1758, 272, 500, 87, 7653, 858, 273, 331, 17128, 8924, 18, 588, 12021, 1887, 12, 203, 5411, 2 ]
./full_match/23295/0xd64a57003526ECe2e360b25A556963aB6E38407E/sources/contracts/HealDAOv1.sol
Comma-separated locations
string locationList;
7,103,087
[ 1, 15594, 17, 24622, 7838, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 533, 2117, 682, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0x3d058da8c242572612Cf784312b91D461Ac4d8B2/sources/src/contracts/token/IndexToken.sol
@notice Ownable function to set the limit at which the total supply cannot exceed @param _supplyCeiling uint256
function setSupplyCeiling(uint256 _supplyCeiling) external override onlyOwner { supplyCeiling = _supplyCeiling; emit SupplyCeilingSet(_supplyCeiling); }
3,758,824
[ 1, 5460, 429, 445, 358, 444, 326, 1800, 622, 1492, 326, 2078, 14467, 2780, 9943, 225, 389, 2859, 1283, 39, 73, 4973, 2254, 5034, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 444, 3088, 1283, 39, 73, 4973, 12, 11890, 5034, 389, 2859, 1283, 39, 73, 4973, 13, 3903, 3849, 1338, 5541, 288, 203, 3639, 14467, 39, 73, 4973, 273, 389, 2859, 1283, 39, 73, 4973, 31, 203, 3639, 3626, 3425, 1283, 39, 73, 4973, 694, 24899, 2859, 1283, 39, 73, 4973, 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 ]
./partial_match/4/0x1478e99Aadc30829a77FB2Bb19C3B964509F4898/sources/animalMain.sol
TO DO 請使用require判斷要轉的動物id是不是轉移者的增加受贈者的擁有動物數量減少轉出者的擁有動物數量動物所有權轉移
function transfer(address _to, uint256 _tokenId) public { require(animalToOwner[_tokenId]==msg.sender); ownerAnimalCount[_to]=ownerAnimalCount[_to].add(1); ownerAnimalCount[msg.sender]=ownerAnimalCount[msg.sender].sub(1); animalToOwner[_tokenId] = _to; emit Transfer(msg.sender, _to, _tokenId); }
16,972,802
[ 1, 4296, 5467, 225, 169, 109, 238, 165, 126, 128, 168, 247, 106, 6528, 166, 235, 102, 167, 249, 120, 169, 104, 228, 169, 126, 236, 168, 253, 231, 166, 238, 248, 168, 236, 107, 350, 167, 251, 112, 165, 121, 240, 167, 251, 112, 169, 126, 236, 168, 105, 124, 169, 227, 232, 168, 253, 231, 166, 100, 257, 166, 237, 259, 166, 242, 250, 169, 117, 235, 169, 227, 232, 168, 253, 231, 167, 246, 228, 167, 255, 236, 166, 238, 248, 168, 236, 107, 167, 248, 121, 170, 234, 242, 167, 121, 254, 166, 113, 244, 169, 126, 236, 166, 234, 123, 169, 227, 232, 168, 253, 231, 167, 246, 228, 167, 255, 236, 166, 238, 248, 168, 236, 107, 167, 248, 121, 170, 234, 242, 166, 238, 248, 168, 236, 107, 167, 236, 227, 167, 255, 236, 167, 110, 237, 169, 126, 236, 168, 105, 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, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 2316, 548, 13, 1071, 288, 203, 4202, 203, 565, 2583, 12, 304, 2840, 774, 5541, 63, 67, 2316, 548, 65, 631, 3576, 18, 15330, 1769, 203, 203, 565, 3410, 979, 2840, 1380, 63, 67, 869, 65, 33, 8443, 979, 2840, 1380, 63, 67, 869, 8009, 1289, 12, 21, 1769, 203, 565, 3410, 979, 2840, 1380, 63, 3576, 18, 15330, 65, 33, 8443, 979, 2840, 1380, 63, 3576, 18, 15330, 8009, 1717, 12, 21, 1769, 203, 203, 565, 392, 2840, 774, 5541, 63, 67, 2316, 548, 65, 273, 389, 869, 31, 203, 203, 565, 3626, 12279, 12, 3576, 18, 15330, 16, 389, 869, 16, 389, 2316, 548, 1769, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* This file is part of The Colony Network. The Colony Network is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. The Colony Network is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with The Colony Network. If not, see <http://www.gnu.org/licenses/>. */ pragma solidity ^0.4.23; pragma experimental "v0.5.0"; import "./ColonyStorage.sol"; import "./EtherRouter.sol"; contract Colony is ColonyStorage, PatriciaTreeProofs { // This function, exactly as defined, is used in build scripts. Take care when updating. // Version number should be upped with every change in Colony or its dependency contracts or libraries. function version() public pure returns (uint256) { return 1; } function setOwnerRole(address _user) public stoppable auth { // To allow only one address to have owner role at a time, we have to remove current owner from their role ColonyAuthority colonyAuthority = ColonyAuthority(authority); colonyAuthority.setUserRole(msg.sender, OWNER_ROLE, false); colonyAuthority.setUserRole(_user, OWNER_ROLE, true); } function setAdminRole(address _user) public stoppable auth { ColonyAuthority(authority).setUserRole(_user, ADMIN_ROLE, true); } // Can only be called by the owner role. function removeAdminRole(address _user) public stoppable auth { ColonyAuthority(authority).setUserRole(_user, ADMIN_ROLE, false); } function setToken(address _token) public stoppable auth { token = ERC20Extended(_token); } function getToken() public view returns (address) { return token; } function initialiseColony(address _address) public stoppable { require(colonyNetworkAddress == 0x0, "colony-initialise-bad-address"); colonyNetworkAddress = _address; // Initialise the task update reviewers setFunctionReviewers(bytes4(keccak256("setTaskBrief(uint256,bytes32)")), MANAGER, WORKER); setFunctionReviewers(bytes4(keccak256("setTaskDueDate(uint256,uint256)")), MANAGER, WORKER); setFunctionReviewers(bytes4(keccak256("setTaskSkill(uint256,uint256)")), MANAGER, WORKER); setFunctionReviewers(bytes4(keccak256("setTaskDomain(uint256,uint256)")), MANAGER, WORKER); // We are setting a manager to both reviewers, but it will require just one signature from manager setFunctionReviewers(bytes4(keccak256("setTaskManagerPayout(uint256,address,uint256)")), MANAGER, MANAGER); setFunctionReviewers(bytes4(keccak256("setTaskEvaluatorPayout(uint256,address,uint256)")), MANAGER, EVALUATOR); setFunctionReviewers(bytes4(keccak256("setTaskWorkerPayout(uint256,address,uint256)")), MANAGER, WORKER); setFunctionReviewers(bytes4(keccak256("removeTaskEvaluatorRole(uint256)")), MANAGER, EVALUATOR); setFunctionReviewers(bytes4(keccak256("removeTaskWorkerRole(uint256)")), MANAGER, WORKER); setFunctionReviewers(bytes4(keccak256("cancelTask(uint256)")), MANAGER, WORKER); setRoleAssignmentFunction(bytes4(keccak256("setTaskManagerRole(uint256,address)"))); setRoleAssignmentFunction(bytes4(keccak256("setTaskEvaluatorRole(uint256,address)"))); setRoleAssignmentFunction(bytes4(keccak256("setTaskWorkerRole(uint256,address)"))); // Initialise the root domain IColonyNetwork colonyNetwork = IColonyNetwork(colonyNetworkAddress); uint256 rootLocalSkill = colonyNetwork.getSkillCount(); initialiseDomain(rootLocalSkill); // Set initial colony reward inverse amount to the max indicating a zero rewards to start with rewardInverse = 2**256 - 1; } function bootstrapColony(address[] _users, int[] _amounts) public stoppable auth isInBootstrapPhase { require(_users.length == _amounts.length, "colony-bootstrap-bad-inputs"); for (uint i = 0; i < _users.length; i++) { require(_amounts[i] >= 0, "colony-bootstrap-bad-amount-input"); token.transfer(_users[i], uint(_amounts[i])); IColonyNetwork(colonyNetworkAddress).appendReputationUpdateLog(_users[i], _amounts[i], domains[1].skillId); } } function mintTokens(uint _wad) public stoppable auth { return token.mint(_wad); } function mintTokensForColonyNetwork(uint _wad) public stoppable { // Only the colony Network can call this function require(msg.sender == colonyNetworkAddress, "colony-access-denied-only-network-allowed"); // Function only valid on the Meta Colony require(this == IColonyNetwork(colonyNetworkAddress).getMetaColony(), "colony-access-denied-only-meta-colony-allowed"); token.mint(_wad); token.transfer(colonyNetworkAddress, _wad); } function registerColonyLabel(string colonyName) public stoppable auth { IColonyNetwork(colonyNetworkAddress).registerColonyLabel(colonyName); } function addGlobalSkill(uint _parentSkillId) public stoppable auth returns (uint256) { IColonyNetwork colonyNetwork = IColonyNetwork(colonyNetworkAddress); return colonyNetwork.addSkill(_parentSkillId, true); } function setNetworkFeeInverse(uint256 _feeInverse) public stoppable auth { IColonyNetwork colonyNetwork = IColonyNetwork(colonyNetworkAddress); return colonyNetwork.setFeeInverse(_feeInverse); } function addNetworkColonyVersion(uint256 _version, address _resolver) public stoppable auth { IColonyNetwork colonyNetwork = IColonyNetwork(colonyNetworkAddress); return colonyNetwork.addColonyVersion(_version, _resolver); } function addDomain(uint256 _parentDomainId) public stoppable auth domainExists(_parentDomainId) { // Note: Remove when we want to allow more domain hierarchy levels require(_parentDomainId == 1, "colony-parent-domain-not-root"); uint256 parentSkillId = domains[_parentDomainId].skillId; // Setup new local skill IColonyNetwork colonyNetwork = IColonyNetwork(colonyNetworkAddress); uint256 newLocalSkill = colonyNetwork.addSkill(parentSkillId, false); // Add domain to local mapping initialiseDomain(newLocalSkill); } function getDomain(uint256 _id) public view returns (uint256, uint256) { Domain storage d = domains[_id]; return (d.skillId, d.potId); } function getDomainCount() public view returns (uint256) { return domainCount; } modifier verifyKey(bytes key) { uint256 colonyAddress; uint256 skillid; uint256 userAddress; assembly { colonyAddress := mload(add(key,32)) skillid := mload(add(key,52)) // Colony address was 20 bytes long, so add 20 bytes userAddress := mload(add(key,84)) // Skillid was 32 bytes long, so add 32 bytes } colonyAddress >>= 96; userAddress >>= 96; // Require that the user is proving their own reputation in this colony. require(address(colonyAddress) == address(this), "colony-invalid-reputation-key-colony-address"); require(address(userAddress) == msg.sender, "colony-invalid-reputation-key-user-address"); _; } function verifyReputationProof(bytes key, bytes value, uint branchMask, bytes32[] siblings) // solium-disable-line security/no-assign-params public view stoppable verifyKey(key) returns (bool) { // Get roothash from colonynetwork bytes32 rootHash = IColonyNetwork(colonyNetworkAddress).getReputationRootHash(); bytes32 impliedHash = getImpliedRoot(key, value, branchMask, siblings); require(rootHash==impliedHash, "colony-invalid-reputation-proof"); return true; } function upgrade(uint256 _newVersion) public always auth { // Upgrades can only go up in version uint256 currentVersion = version(); require(_newVersion > currentVersion, "colony-version-must-be-newer"); // Requested version has to be registered address newResolver = IColonyNetwork(colonyNetworkAddress).getColonyVersionResolver(_newVersion); require(newResolver != 0x0, "colony-version-must-be-registered"); EtherRouter e = EtherRouter(address(this)); e.setResolver(newResolver); } function checkNotAdditionalProtectedVariable(uint256 _slot) public view recovery { bool protected = false; uint256 networkAddressSlot; assembly { // Use this if statement once https://github.com/sc-forks/solidity-coverage/issues/287 fixed // if eq(slot, colonyNetworkAddress_slot) { protected := 1 } networkAddressSlot := colonyNetworkAddress_slot } if (networkAddressSlot==_slot) { protected = true; } require(!protected, "colony-protected-variable"); } function setFunctionReviewers(bytes4 _sig, uint8 _firstReviewer, uint8 _secondReviewer) private { uint8[2] memory _reviewers = [_firstReviewer, _secondReviewer]; reviewers[_sig] = _reviewers; } function setRoleAssignmentFunction(bytes4 _sig) private { roleAssignmentSigs[_sig] = true; } function initialiseDomain(uint256 _skillId) private skillExists(_skillId) { // Create a new pot potCount += 1; // Create a new domain with the given skill and new pot domainCount += 1; domains[domainCount] = Domain({ skillId: _skillId, potId: potCount }); emit DomainAdded(domainCount); emit PotAdded(potCount); } }
Upgrades can only go up in version Requested version has to be registered
function upgrade(uint256 _newVersion) public always auth { uint256 currentVersion = version(); require(_newVersion > currentVersion, "colony-version-must-be-newer"); address newResolver = IColonyNetwork(colonyNetworkAddress).getColonyVersionResolver(_newVersion); require(newResolver != 0x0, "colony-version-must-be-registered"); EtherRouter e = EtherRouter(address(this)); e.setResolver(newResolver); }
12,551,829
[ 1, 1211, 13088, 848, 1338, 1960, 731, 316, 1177, 25829, 1177, 711, 358, 506, 4104, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 8400, 12, 11890, 5034, 389, 2704, 1444, 13, 1071, 3712, 1357, 288, 203, 565, 2254, 5034, 23344, 273, 1177, 5621, 203, 565, 2583, 24899, 2704, 1444, 405, 23344, 16, 315, 1293, 6598, 17, 1589, 17, 11926, 17, 2196, 17, 2704, 264, 8863, 203, 565, 1758, 394, 4301, 273, 467, 914, 6598, 3906, 12, 1293, 6598, 3906, 1887, 2934, 588, 914, 6598, 1444, 4301, 24899, 2704, 1444, 1769, 203, 565, 2583, 12, 2704, 4301, 480, 374, 92, 20, 16, 315, 1293, 6598, 17, 1589, 17, 11926, 17, 2196, 17, 14327, 8863, 203, 565, 512, 1136, 8259, 425, 273, 512, 1136, 8259, 12, 2867, 12, 2211, 10019, 203, 565, 425, 18, 542, 4301, 12, 2704, 4301, 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 ]
// Copyright 2021 Cartesi Pte. Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. /// @title Input Implementation pragma solidity ^0.8.0; import "./Input.sol"; import "./DescartesV2.sol"; // TODO: this contract seems to be very unsafe, need to think about security implications contract InputImpl is Input { DescartesV2 immutable descartesV2; // descartes 2 contract using this input contract // always needs to keep track of two input boxes: // 1 for the input accumulation of next epoch // and 1 for the messages during current epoch. To save gas we alternate // between inputBox0 and inputBox1 bytes32[] inputBox0; bytes32[] inputBox1; uint256 immutable inputDriveSize; // size of input flashdrive uint256 currentInputBox; /// @param _descartesV2 address of descartesV2 contract that will manage inboxes /// @param _log2Size size of the input drive of the machine constructor(address _descartesV2, uint256 _log2Size) { require(_log2Size >= 3 && _log2Size <= 64, "log size: [3,64]"); descartesV2 = DescartesV2(_descartesV2); inputDriveSize = (1 << _log2Size); } /// @notice add input to processed by next epoch /// @param _input input to be understood by offchain machine /// @dev offchain code is responsible for making sure /// that input size is power of 2 and multiple of 8 since // the offchain machine has a 8 byte word function addInput(bytes calldata _input) public override returns (bytes32) { require( _input.length > 0 && _input.length <= inputDriveSize, "input len: (0,driveSize]" ); // keccak 64 bytes into 32 bytes bytes32 keccakMetadata = keccak256(abi.encode(msg.sender, block.timestamp)); bytes32 keccakInput = keccak256(_input); bytes32 inputHash = keccak256(abi.encode(keccakMetadata, keccakInput)); // notifyInput returns true if that input // belongs to a new epoch if (descartesV2.notifyInput()) { swapInputBox(); } // add input to correct inbox currentInputBox == 0 ? inputBox0.push(inputHash) : inputBox1.push(inputHash); emit InputAdded( descartesV2.getCurrentEpoch(), msg.sender, block.timestamp, _input ); return inputHash; } /// @notice get input inside inbox of currently proposed claim /// @param _index index of input inside that inbox /// @return hash of input at index _index /// @dev currentInputBox being zero means that the inputs for /// the claimed epoch are on input box one function getInput(uint256 _index) public view override returns (bytes32) { return currentInputBox == 0 ? inputBox1[_index] : inputBox0[_index]; } /// @notice get number of inputs inside inbox of currently proposed claim /// @return number of inputs on that input box /// @dev currentInputBox being zero means that the inputs for /// the claimed epoch are on input box one function getNumberOfInputs() public view override returns (uint256) { return currentInputBox == 0 ? inputBox1.length : inputBox0.length; } /// @notice get inbox currently receiveing inputs /// @return input inbox currently receiveing inputs function getCurrentInbox() public view override returns (uint256) { return currentInputBox; } /// @notice called when a new input accumulation phase begins /// swap inbox to receive inputs for upcoming epoch /// @dev can only be called by DescartesV2 contract function onNewInputAccumulation() public override { onlyDescartesV2(); swapInputBox(); } /// @notice called when a new epoch begins, clears deprecated inputs /// @dev can only be called by DescartesV2 contract function onNewEpoch() public override { // clear input box for new inputs // the current input box should be accumulating inputs // for the new epoch already. So we clear the other one. onlyDescartesV2(); currentInputBox == 0 ? delete inputBox1 : delete inputBox0; } /// @notice check if message sender is DescartesV2 function onlyDescartesV2() internal view { require(msg.sender == address(descartesV2), "Only descartesV2"); } /// @notice changes current input box function swapInputBox() internal { currentInputBox == 0 ? currentInputBox = 1 : currentInputBox = 0; } }
@notice add input to processed by next epoch @param _input input to be understood by offchain machine @dev offchain code is responsible for making sure that input size is power of 2 and multiple of 8 since the offchain machine has a 8 byte word keccak 64 bytes into 32 bytes notifyInput returns true if that input belongs to a new epoch
function addInput(bytes calldata _input) public override returns (bytes32) { require( _input.length > 0 && _input.length <= inputDriveSize, "input len: (0,driveSize]" ); bytes32 keccakMetadata = keccak256(abi.encode(msg.sender, block.timestamp)); bytes32 keccakInput = keccak256(_input); bytes32 inputHash = keccak256(abi.encode(keccakMetadata, keccakInput)); if (descartesV2.notifyInput()) { swapInputBox(); } ? inputBox0.push(inputHash) : inputBox1.push(inputHash); emit InputAdded( descartesV2.getCurrentEpoch(), msg.sender, block.timestamp, _input ); return inputHash; }
13,027,599
[ 1, 1289, 810, 358, 5204, 635, 1024, 7632, 225, 389, 2630, 810, 358, 506, 31727, 4773, 635, 3397, 5639, 5228, 225, 3397, 5639, 981, 353, 14549, 364, 10480, 3071, 1377, 716, 810, 963, 353, 7212, 434, 576, 471, 3229, 434, 1725, 3241, 326, 3397, 5639, 5228, 711, 279, 1725, 1160, 2076, 417, 24410, 581, 5178, 1731, 1368, 3847, 1731, 5066, 1210, 1135, 638, 309, 716, 810, 11081, 358, 279, 394, 7632, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 1210, 12, 3890, 745, 892, 389, 2630, 13, 1071, 3849, 1135, 261, 3890, 1578, 13, 288, 203, 3639, 2583, 12, 203, 5411, 389, 2630, 18, 2469, 405, 374, 597, 389, 2630, 18, 2469, 1648, 810, 24681, 1225, 16, 203, 5411, 315, 2630, 562, 30, 261, 20, 16, 25431, 1225, 4279, 203, 3639, 11272, 203, 203, 3639, 1731, 1578, 417, 24410, 581, 2277, 273, 203, 5411, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 12, 3576, 18, 15330, 16, 1203, 18, 5508, 10019, 203, 3639, 1731, 1578, 417, 24410, 581, 1210, 273, 417, 24410, 581, 5034, 24899, 2630, 1769, 203, 203, 3639, 1731, 1578, 810, 2310, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 12, 79, 24410, 581, 2277, 16, 417, 24410, 581, 1210, 10019, 203, 203, 3639, 309, 261, 5569, 485, 281, 58, 22, 18, 12336, 1210, 10756, 288, 203, 5411, 7720, 1210, 3514, 5621, 203, 3639, 289, 203, 203, 5411, 692, 810, 3514, 20, 18, 6206, 12, 2630, 2310, 13, 203, 5411, 294, 810, 3514, 21, 18, 6206, 12, 2630, 2310, 1769, 203, 203, 3639, 3626, 2741, 8602, 12, 203, 5411, 3044, 485, 281, 58, 22, 18, 588, 3935, 14638, 9334, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 1203, 18, 5508, 16, 203, 5411, 389, 2630, 203, 3639, 11272, 203, 203, 3639, 327, 810, 2310, 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 ]
./partial_match/1/0x9c12d9b1223130B641154d8d3DB35F91D81c8dfd/sources/InBitToken.sol
@dev Returns the total amount of all unlockable tokens for a specified address. @param _of The address to query the unlockable token count of
function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens) { for (uint256 i = 0; i < lockReason[_of].length; i++) { unlockableTokens = unlockableTokens.add(tokensUnlockable(_of, lockReason[_of][i])); } }
16,074,275
[ 1, 1356, 326, 2078, 3844, 434, 777, 7186, 429, 2430, 364, 279, 1269, 1758, 18, 225, 389, 792, 1021, 1758, 358, 843, 326, 7186, 429, 1147, 1056, 434, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 336, 7087, 429, 5157, 12, 2867, 389, 792, 13, 203, 565, 1071, 203, 565, 1476, 203, 565, 1135, 261, 11890, 5034, 7186, 429, 5157, 13, 203, 225, 288, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 2176, 8385, 63, 67, 792, 8009, 2469, 31, 277, 27245, 288, 203, 1377, 7186, 429, 5157, 273, 7186, 429, 5157, 18, 1289, 12, 7860, 7087, 429, 24899, 792, 16, 2176, 8385, 63, 67, 792, 6362, 77, 5717, 1769, 203, 565, 289, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xCD56A62CE22dBc5c585C6a3b081C3F68D510a0Dd/sources/Bjork.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Bjork", "Bjork") { 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 = 15; uint256 _buyDevFee = 1; uint256 _sellMarketingFee = 5; uint256 _sellLiquidityFee = 15; uint256 _sellDevFee = 1; uint256 _earlySellLiquidityFee = 0; uint256 _earlySellMarketingFee = 0; uint256 totalSupply = 1 * 1e8 * 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; 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);
9,661,665
[ 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, 38, 78, 778, 3113, 315, 38, 78, 778, 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, 4711, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 8870, 14667, 273, 404, 31, 203, 2 ]
pragma solidity ^0.8.10; import "../node_modules/openzeppelin-solidity/contracts/utils/math/SafeMath.sol"; import "./FlightSuretyDataContract.sol"; import {FlightStatusCodes} from "./FlightStatusCodes.sol"; contract FlightSuretyData is FlightSuretyDataContract { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract address private authorizedCaller; bool private operational = true; // Blocks all state changes throughout the contract if false // Flight status codees mapping(address => uint256) private usersBalance; mapping(address => uint256) private airlineFunds; //map of insurance keys to all users who have acquired it mapping(bytes32 => Insurance[]) private insuranceUsers; mapping(bytes32 => Flight) private flights; mapping(bytes32 => Airline) private registeredAirlines; mapping(string => address) private airlinesNamestoAddress; mapping(bytes32 => uint128) private airlineRegisterVotes; mapping(bytes32 => bool) private airlineRegisterVotesHistory; FlightStatusCodes.FlightInfo[] private flightLists; uint128 private airlineCount; struct Flight { bool isRegistered; uint8 statusCode; uint256 updatedTimestamp; address airline; } struct Insurance { address user; uint256 paidAmount; uint256 reimbursedAmount; } struct Airline { address airlineAddress; string name; bool hasPaidFunds; } /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner */ constructor(address firstAirline, string memory airlineName) { addAirline(firstAirline, airlineName); contractOwner = msg.sender; authorizedCaller = msg.sender; } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier requireAuthorizedCaller() { require( msg.sender == authorizedCaller, "Caller is not authorized" ); _; // All modifiers require an "_" which indicates where the function body will be added } /********************************************************************************************/ /* 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 requireContractOwner { operational = mode; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline(address airline, string calldata name) external { addAirline(airline, name); } function authorizeCaller(address caller) external requireContractOwner { authorizedCaller = caller; } function addAirlineRegisterVote(address airline, address requester) external requireAuthorizedCaller { bytes32 key = getAirlineKey(airline); bytes32 voteHistoryKey = keccak256( abi.encodePacked(airline, requester) ); airlineRegisterVotes[key] = airlineRegisterVotes[key] + 1; airlineRegisterVotesHistory[voteHistoryKey] = true; } function hasAlreadyVoted(address airline, address requester) external view requireAuthorizedCaller returns (bool) { bytes32 voteHistoryKey = keccak256( abi.encodePacked(airline, requester) ); return airlineRegisterVotesHistory[voteHistoryKey]; } function getAirlineRegisterVote(address airline) external view requireAuthorizedCaller returns (uint128) { bytes32 key = getAirlineKey(airline); return airlineRegisterVotes[key]; } function getAirlineCount() external view returns (uint128) { return airlineCount; } function addAirline(address airline, string memory name) internal { bytes32 key = getAirlineKey(airline); registeredAirlines[key] = Airline(airline, name, false); airlinesNamestoAddress[name] = airline; } function isAirlineRegistered(address airline) external view requireAuthorizedCaller returns (bool) { bytes32 key = getAirlineKey(airline); return registeredAirlines[key].airlineAddress != address(0); } function isAirlineFunded(address airline) external view requireAuthorizedCaller returns (bool) { bytes32 key = getAirlineKey(airline); return registeredAirlines[key].airlineAddress != address(0) && registeredAirlines[key].hasPaidFunds == true; } function setAirlineAsFunded(address airline) external requireAuthorizedCaller { setAirlineAsFundedInternal(airline); } function setAirlineAsFundedInternal(address airline) internal { bytes32 key = getAirlineKey(airline); Airline memory foundAirline = registeredAirlines[key]; registeredAirlines[key] = Airline(airline, foundAirline.name, true); airlineCount++; } function airlineAddressFromName(string calldata name) external view requireAuthorizedCaller returns (address) { return airlinesNamestoAddress[name]; } /** * @dev Register a future flight for insuring. * */ function addFlight( address flightAirline, string calldata flight, uint256 timestamp ) external requireAuthorizedCaller { // Generate a unique key for storing the flight bytes32 key = getFlightKey(flightAirline, flight); flights[key].isRegistered = true; flights[key].statusCode = FlightStatusCodes.STATUS_CODE_UNKNOWN; flights[key].updatedTimestamp = timestamp; flights[key].airline = flightAirline; bytes32 airlineKey = getAirlineKey(flightAirline); flightLists.push( FlightStatusCodes.FlightInfo( flight, registeredAirlines[airlineKey].name ) ); } function updateFlightStatus( address airline, string calldata flight, uint256 timestamp, uint8 statusCode ) external requireAuthorizedCaller { bytes32 key = getFlightKey(airline, flight); flights[key].statusCode = statusCode; flights[key].updatedTimestamp = timestamp; } function getFlight(address airline, string calldata flight) external view requireAuthorizedCaller returns ( address returnAirline, string calldata retFlight, uint8 status, uint256 timestamp ) { // Generate a unique key for storing the flight bytes32 key = getFlightKey(airline, flight); return ( flights[key].airline, flight, flights[key].statusCode, flights[key].updatedTimestamp ); } function getFlightsList() external view requireAuthorizedCaller returns (FlightStatusCodes.FlightInfo[] memory) { return flightLists; } /** * @dev Buy insurance for a flight * */ function addUserInsurance( string calldata flight, address airline, address user, uint256 amount ) external requireAuthorizedCaller { bytes32 key = getInsuranceKey(airline, flight); insuranceUsers[key].push(Insurance(user, amount, 0)); } /** * @dev Credits payouts to insurees */ function creditInsurees(address airline, string calldata flight) external requireAuthorizedCaller { bytes32 key = getInsuranceKey(airline, flight); Insurance[] memory userInsurances = insuranceUsers[key]; for (uint256 i = 0; i < userInsurances.length; i++) { address insuranceUser = userInsurances[i].user; uint256 reimbursedAmount = userInsurances[i].reimbursedAmount; uint256 insuranceAmount = userInsurances[i].paidAmount; if (reimbursedAmount == 0) { uint256 credit = (insuranceAmount * 3) / 2; usersBalance[insuranceUser] += credit; insuranceUsers[key][i] = Insurance(insuranceUser, insuranceAmount, credit); } } } /** * @dev Transfers eligible payout funds to insuree * */ function withdrawUserBalance(uint256 amount, address user) external requireAuthorizedCaller { usersBalance[user] = usersBalance[user] - amount; } function getUserBalance(address user) external view requireAuthorizedCaller returns (uint256 amount) { return usersBalance[user]; } function addAirlineFunds(address airline, uint256 amount) external requireAuthorizedCaller { airlineFunds[airline] += amount; } function getAirlineFunds(address airline) external view requireAuthorizedCaller returns (uint256) { return airlineFunds[airline]; } function getFlightKey(address airline, string calldata flight) internal pure returns (bytes32) { return keccak256(abi.encodePacked(airline, flight)); } function getAirlineKey(address airline) internal pure returns (bytes32) { return keccak256(abi.encodePacked(airline)); } function getInsuranceKey(address airline, string calldata flight) internal pure returns (bytes32) { return keccak256(abi.encodePacked(airline, flight)); } }
Generate a unique key for storing the flight
function getFlight(address airline, string calldata flight) external view requireAuthorizedCaller returns ( address returnAirline, string calldata retFlight, uint8 status, uint256 timestamp ) { bytes32 key = getFlightKey(airline, flight); return ( flights[key].airline, flight, flights[key].statusCode, flights[key].updatedTimestamp ); }
6,379,283
[ 1, 4625, 279, 3089, 498, 364, 15729, 326, 25187, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 336, 24243, 12, 2867, 23350, 1369, 16, 533, 745, 892, 25187, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 2583, 15341, 11095, 203, 3639, 1135, 261, 203, 5411, 1758, 327, 29752, 1369, 16, 203, 5411, 533, 745, 892, 325, 24243, 16, 203, 5411, 2254, 28, 1267, 16, 203, 5411, 2254, 5034, 2858, 203, 3639, 262, 203, 565, 288, 203, 3639, 1731, 1578, 498, 273, 336, 24243, 653, 12, 1826, 1369, 16, 25187, 1769, 203, 3639, 327, 261, 203, 5411, 1183, 10730, 63, 856, 8009, 1826, 1369, 16, 203, 5411, 25187, 16, 203, 5411, 1183, 10730, 63, 856, 8009, 30120, 16, 203, 5411, 1183, 10730, 63, 856, 8009, 7007, 4921, 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 ]
./full_match/1/0xc106e720761D71a8E9a8fA45ED18D1Ab85D27832/sources/src/Kong/Distributor.sol
mint and send tokens
treasury.mint(staking, nextReward());
17,105,980
[ 1, 81, 474, 471, 1366, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 202, 27427, 345, 22498, 18, 81, 474, 12, 334, 6159, 16, 1024, 17631, 1060, 10663, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; // ------------- // FANCY BEE DAO // // This DAO esponsible for managing the treasury and all other contracts including: // - BeeNFTs, // - HiveNFTs, // - OutfitNFTs // // All operations that involve a royalty to the DAO must be mediated // thought this contract. // // The DAO is goverened though voting, where: // - each bee has a vote // - each Hive has a weighted vote. // ------------- // TODO delete these until compile fails :) // TODO may need to add interfaces for dependancies in different files. import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; // import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; // import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; // import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; // import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; // import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; // import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Snapshot.sol"; // import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol"; // import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; // import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; // import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; // import "./Royalty.sol"; import "./FancyBee.sol"; import "./OutfitNFT.sol"; contract FancyBDAO is Ownable { mapping (uint16=> uint256) public hiveBalance; mapping (uint16=> uint16) public hivePercent; mapping (uint16=> address) public reverseHiveMap; uint16 hiveCount = 0; uint256 public treasury; //Amount to be distributed uint256 public retained; //Amount held for DAO uint256 public daoPercent;// % to be retained by DAO uint256 public nextDistribution; // Timer to prevent high gas fees FancyBee public beeNFT; //contract address for beeNFT OutfitNFT public outfitNFT; //contract address for outfitNFT // TODO: define governance by bees not ERC20 // FancyBsGov public votingToken; // FancyBsGovenor public governor; constructor(){ //Create NFTs owned by the DAO // votingToken = new FancyBsGov(); // governor = new FancyBsGovenor(votingToken); } function initAddresses(FancyBee beeAddress, OutfitNFT outfitAddress) public { require(beeNFT == FancyBee(0), "Already initialized."); beeNFT = beeAddress; outfitNFT = outfitAddress; nextDistribution = block.timestamp + 604800; // only allow distribution weekly } //Recieve all ETH there. (TODO: ERC20s are permissioned and accumulated in the ERC20 contract) receive() external payable { treasury += msg.value; } // // Interface to Beekeeper // function dressMe(uint256 _beeID, uint256 _outfitID) public payable { // FancyBeeInterface fancyBee = FancyBeeInterface(beeNFT); // FancyBeeInterface outfit = FancyBeeInterface(outfitNFT); require(beeNFT.tokenExists(_beeID), "Bee does not exist."); require(outfitNFT.tokenExists(_outfitID), "Outfit does not exist."); require( msg.value != 10^16, "Please send exactly x 0.01 ETH."); outfitNFT.attachToBee(_outfitID, address(beeNFT), _beeID); beeNFT.attachOutfit(_beeID, address(outfitNFT), _outfitID); beeNFT.setTokenURI(_beeID ,outfitNFT.getTokenURI(_outfitID)); treasury += msg.value; } // // voting // uint256 proposalTimer; mapping (uint256=> uint256) beeLastVoted; uint256 proposalAmount; address proposalRecipient; uint32 yesVotes; uint32 noVotes; uint32 numVotes; function proposeDistribution(uint256 _beeID, address _recipient, uint256 _amount) public { require(proposalTimer != 0, "One at a time"); // TODO FIX this - require(beeNFT.isOwnedBy(_beeID, msg.sender), "Only Bees"); //TODO how do we tell. require(_amount + 10^16 <= retained); proposalTimer = block.timestamp + 604800; // 1 Week to vote. yesVotes = 0; noVotes = 0; numVotes = 0; proposalRecipient = _recipient; proposalAmount = _amount; retained -= (_amount + 10^16); //reserve funds. } function voteDistribution(uint256 _beeID, bool _vote) public payable{ // TODO FIX this - require(beeNFT.isOwnedBy(_beeID, msg.sender), "Only Bees"); //TODO how do we tell. require(beeLastVoted[_beeID] != proposalTimer, "Double vote"); beeLastVoted[_beeID] = proposalTimer; if (_vote) { yesVotes++; }else{ noVotes++; } numVotes++; } function executeProposal(uint256 _beeID) public payable{ require(block.timestamp > proposalTimer, "Too soon"); require(proposalTimer >0, "No proposal"); proposalTimer = 0; //prevent re-entry require(numVotes>100, "less than 100 votes"); if (yesVotes>noVotes && numVotes > 100){ // Send the reward (bool sent1, bytes memory tmp1) = msg.sender.call{value: 10^16}(""); require(sent1, "Failed to send Reward"); //Send the funds (bool sent2, bytes memory tmp2) = proposalRecipient.call{value: proposalAmount}(""); require(sent2, "Failed to send to Recipient"); }else{ //restore funds retained += proposalAmount + 10^16; } } // // Governance functions - these are functions that the Governance contract is able to call // function distributeFunds(uint256 _beeID) public { if (treasury >0){ //check for recursion here. require(treasury >3*10^18, "Less that 3 ETH"); //TODO Don't need this if reward is 0.25% require(block.timestamp > nextDistribution, "Too early"); // TODO FIX this - require(beeNFT.isOwnedBy(_beeID, msg.sender), "Only Bees"); //TODO how do we tell. uint _reward = 10^16; // TODO make the reward ~0.25% percentage of the total. uint256 _treasury = treasury - _reward; treasury = 0; //protect from reentrance by removing any funds. // Send the reward (bool sent1, bytes memory tmp1) = msg.sender.call{value: _reward}(""); require(sent1, "Failed to send Ether"); // take the amount for the DAO. uint256 amt = _treasury -_treasury*10000/daoPercent; //Calculate amount for each hive uint256 t = amt/hiveCount; //Send portion to each hive royalty address. for (uint16 i=0; i<hiveCount; i++){ _treasury -= t; (bool sent2, bytes memory tmp2) = reverseHiveMap[i].call{value: t}(""); require(sent2, "Failed to send Ether"); } retained += _treasury; } } /* TODO function addCharity(address _addr) public onlyOwner{ hiveID[_addr] = hiveNFT.mintToken(); hiveMap[_addr].balance = 0; hivePercent[_addr] = 5; //default reverseHiveMap[hiveCount] = _addr; hiveCount++; } function setCharityPercent(address _addr, uint8 _p ) public onlyOwner{ hiveMap[_addr].percent = _p; } function setDAOPercent(uint8 _p) public onlyOwner{ daoPercent = _p; } */ } interface FancyBeeInterface { function setTokenURI(uint256 _tokenId, string memory _tokenURI) external returns (string memory); function getTokenURI(uint _outfitId) external view returns (string memory); function tokenExists(uint256 _tokenId) external view returns (bool); }
% to be retained by DAO
uint256 public daoPercent;
6,479,597
[ 1, 9, 358, 506, 25227, 635, 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, 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, 2254, 5034, 1071, 15229, 8410, 31, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Safe Math Library // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } contract YFIPAPRIKAGOLD is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { name = "yfipaprika.finance"; symbol = "YFIG"; decimals = 18; _totalSupply = 2500000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } }
* Constrctor function Initializes contract with initial supply tokens to the creator of the contract/
constructor() public { name = "yfipaprika.finance"; symbol = "YFIG"; decimals = 18; _totalSupply = 2500000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); }
15,218,276
[ 1, 442, 701, 30206, 445, 10188, 3128, 6835, 598, 2172, 14467, 2430, 358, 326, 11784, 434, 326, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 1071, 288, 203, 3639, 508, 273, 315, 93, 74, 625, 438, 566, 7282, 18, 926, 1359, 14432, 203, 3639, 3273, 273, 315, 61, 5236, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 6969, 12648, 12648, 2787, 31, 203, 540, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x4C1Bf22D608E9E871f42c4e377d8a32F8b40372C/sources/contracts/adapters/UniV3LimitedRangeAdapter.sol
@inheritdoc IUniV3Adapter
function removeLiquidity(address to, bytes calldata removeLiquidityData) external override onlyVault returns (uint256, uint256) { require(IVault(vaultAddress).earningsSettled(), "ENS"); require(removeLiquidityData.length > 0, "NEI"); (uint256 amount0, uint256 amount1) = _removeLiquidity(removeLiquidityData); return (amount0, amount1); }
4,333,862
[ 1, 36, 10093, 467, 984, 77, 58, 23, 4216, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1206, 48, 18988, 24237, 12, 2867, 358, 16, 1731, 745, 892, 1206, 48, 18988, 24237, 751, 13, 3903, 3849, 1338, 12003, 1135, 261, 11890, 5034, 16, 2254, 5034, 13, 288, 203, 565, 2583, 12, 8188, 3714, 12, 26983, 1887, 2934, 73, 1303, 899, 694, 88, 1259, 9334, 315, 21951, 8863, 203, 565, 2583, 12, 4479, 48, 18988, 24237, 751, 18, 2469, 405, 374, 16, 315, 5407, 45, 8863, 203, 565, 261, 11890, 5034, 3844, 20, 16, 2254, 5034, 3844, 21, 13, 273, 389, 4479, 48, 18988, 24237, 12, 4479, 48, 18988, 24237, 751, 1769, 203, 565, 327, 261, 8949, 20, 16, 3844, 21, 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 ]
pragma solidity 0.8.4; // SPDX-License-Identifier: MIT import "@openzeppelin/contracts/access/Ownable.sol"; import "./YourToken.sol"; contract Vendor is Ownable { event BuyTokens(address buyer, uint256 amountOfETH, uint256 amountOfTokens); event SellTokens(address seller, uint256 amountOfETH, uint256 amountOfTokens); uint256 public constant tokensPerEth = 100; YourToken public yourToken; constructor(address tokenAddress) { yourToken = YourToken(tokenAddress); } // ToDo: create a payable buyTokens() function: function buyTokens() public payable { require(msg.value > 0, "Send ETH to buy some tokens"); uint256 tknsToTransfer = (msg.value) * tokensPerEth; uint256 vendorBalance = yourToken.balanceOf(address(this)); require(vendorBalance >= tknsToTransfer, "Vendor contract has not enough tokens in its balance"); (bool sent) = yourToken.transfer(msg.sender, tknsToTransfer); require(sent, "Failed to transfer token to user"); emit BuyTokens(msg.sender, msg.value, tknsToTransfer); } // ToDo: create a sellTokens() function: function sellTokens(uint256 amount) public { require(amount > 0, "Specify an amount of tokens to sell"); uint256 ethToSend = amount / tokensPerEth; require(address(this).balance >= ethToSend, "The vendor does not have the liquidity"); uint256 userBal = yourToken.balanceOf(msg.sender); require(userBal >= amount, "Cannot sell more coins than owned"); bool status = yourToken.transferFrom(msg.sender, address(this), amount); require(status, "Tokens did not transfer to the contract"); (status,) = msg.sender.call{value: ethToSend}(""); require(status, "Failed to send eth for sold tokens"); emit SellTokens(msg.sender, ethToSend, amount); } // ToDo: create a withdraw() function that lets the owner withdraw ETH function withdraw() public onlyOwner { uint256 ownerBalance = address(this).balance; require(ownerBalance > 0, "Owner has not balance to withdraw"); (bool sent,) = msg.sender.call{value: ownerBalance}(""); require(sent, "Failed to send user balance back to the owner"); payable(owner()).transfer(ownerBalance); } }
ToDo: create a payable buyTokens() function:
function buyTokens() public payable { require(msg.value > 0, "Send ETH to buy some tokens"); uint256 tknsToTransfer = (msg.value) * tokensPerEth; uint256 vendorBalance = yourToken.balanceOf(address(this)); require(vendorBalance >= tknsToTransfer, "Vendor contract has not enough tokens in its balance"); (bool sent) = yourToken.transfer(msg.sender, tknsToTransfer); require(sent, "Failed to transfer token to user"); emit BuyTokens(msg.sender, msg.value, tknsToTransfer); }
5,436,763
[ 1, 774, 3244, 30, 752, 279, 8843, 429, 30143, 5157, 1435, 445, 30, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 202, 915, 30143, 5157, 1435, 1071, 8843, 429, 288, 203, 3639, 2583, 12, 3576, 18, 1132, 405, 374, 16, 315, 3826, 512, 2455, 358, 30143, 2690, 2430, 8863, 203, 203, 3639, 2254, 5034, 13030, 2387, 774, 5912, 273, 261, 3576, 18, 1132, 13, 380, 2430, 2173, 41, 451, 31, 203, 540, 203, 3639, 2254, 5034, 8556, 13937, 273, 3433, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2583, 12, 10645, 13937, 1545, 13030, 2387, 774, 5912, 16, 315, 14786, 6835, 711, 486, 7304, 2430, 316, 2097, 11013, 8863, 203, 203, 203, 3639, 261, 6430, 3271, 13, 273, 3433, 1345, 18, 13866, 12, 3576, 18, 15330, 16, 13030, 2387, 774, 5912, 1769, 203, 3639, 2583, 12, 7569, 16, 315, 2925, 358, 7412, 1147, 358, 729, 8863, 202, 203, 3639, 3626, 605, 9835, 5157, 12, 3576, 18, 15330, 16, 1234, 18, 1132, 16, 13030, 2387, 774, 5912, 1769, 203, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; /// RK35Z token ERC20 with Extensions ERC223 contract RK40Z { uint256 constant public MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; address public owner; bool public SC_locked = true; bool public tokenCreated = false; uint public DateCreateToken; mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; mapping(address => bool) public frozenAccount; mapping(address => bool) public SmartContract_Allowed; // ERC20 Event event Transfer(address indexed _from, address indexed _to, uint256 _value); event Transfer(address indexed from, address indexed to, uint256 value, bytes indexed data); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event FrozenFunds(address target, bool frozen); event Burn(address indexed from, uint256 value); // Initialize // Constructor is called only once and can not be called again (Ethereum Solidity specification) function RK40Z() public { // Security check in case EVM has future flaw or exploit to call constructor multiple times require(tokenCreated == false); owner = msg.sender; name = "RK40Z"; symbol = "RK40Z"; decimals = 5; totalSupply = 500000000 * 10 ** uint256(decimals); balances[owner] = totalSupply; emit Transfer(owner, owner, totalSupply); tokenCreated = true; // Final sanity check to ensure owner balance is greater than zero require(balances[owner] > 0); // Date Deploy Contract DateCreateToken = now; } modifier onlyOwner() { require(msg.sender == owner); _; } // Function to create date token. function DateCreateToken() public view returns (uint256 _DateCreateToken) { return DateCreateToken; } // Function to access name of token . function name() view public returns (string _name) { return name; } // Function to access symbol of token . function symbol() public view returns (string _symbol) { return symbol; } // Function to access decimals of token . function decimals() public view returns (uint8 _decimals) { return decimals; } // Function to access total supply of tokens . function totalSupply() public view returns (uint256 _totalSupply) { return totalSupply; } // Get balance of the address provided function balanceOf(address _owner) constant public returns (uint256 balance) { return balances[_owner]; } // Get Smart Contract of the address approved function SmartContract_Allowed(address _target) constant public returns (bool _sc_address_allowed) { return SmartContract_Allowed[_target]; } function safeAdd(uint256 x, uint256 y) pure internal returns (uint256 z) { if (x > MAX_UINT256 - y) revert(); return x + y; } function safeSub(uint256 x, uint256 y) pure internal returns (uint256 z) { if (x < y) revert(); return x - y; } function safeMul(uint256 x, uint256 y) pure internal returns (uint256 z) { if (y == 0) return 0; if (x > MAX_UINT256 / y) revert(); return x * y; } // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint256 _value, bytes _data) public returns (bool success) { // Only allow transfer once Locked // Once it is Locked, it is Locked forever and no one can lock again require(!SC_locked); require(!frozenAccount[msg.sender]); require(!frozenAccount[_to]); if (isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . function transfer(address _to, uint256 _value) public returns (bool success) { // Only allow transfer once Locked require(!SC_locked); require(!frozenAccount[msg.sender]); require(!frozenAccount[_to]); //standard function transfer similar to ERC20 transfer with no _data //added due to backwards compatibility reasons bytes memory empty; if (isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } // assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length > 0); } // function that is called when transaction target is an address function transferToAddress(address _to, uint256 _value, bytes _data) private returns (bool success) { if (balanceOf(msg.sender) < _value) revert(); balances[msg.sender] = safeSub(balanceOf(msg.sender), _value); balances[_to] = safeAdd(balanceOf(_to), _value); emit Transfer(msg.sender, _to, _value, _data); return true; } // function that is called when transaction target is a contract function transferToContract(address _to, uint256 _value, bytes _data) private returns (bool success) { require(SmartContract_Allowed[_to]); if (balanceOf(msg.sender) < _value) revert(); balances[msg.sender] = safeSub(balanceOf(msg.sender), _value); balances[_to] = safeAdd(balanceOf(_to), _value); emit Transfer(msg.sender, _to, _value, _data); return true; } // Allow transfers if the owner provided an allowance // Use SafeMath for the main logic function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { // Only allow transfer once Locked // Once it is Locked, it is Locked forever and no one can lock again require(!SC_locked); require(!frozenAccount[_from]); require(!frozenAccount[_to]); // Protect against wrapping uints. require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]); uint256 allowance = allowed[_from][owner]; require(balances[_from] >= _value && allowance >= _value); balances[_to] = safeAdd(balanceOf(_to), _value); balances[_from] = safeSub(balanceOf(_from), _value); if (allowance < MAX_UINT256) { allowed[_from][msg.sender] = safeSub(allowed[_from][msg.sender], _value); } emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { // Only allow transfer once unLocked require(!SC_locked); require(!frozenAccount[msg.sender]); require(!frozenAccount[_spender]); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant public returns (uint256 remaining) { return allowed[_owner][_spender]; } /// Set allowance for other address and notify function approveAndCall(address _spender, uint256 _value) public returns (bool success) { require(!SC_locked); require(!frozenAccount[msg.sender]); require(!frozenAccount[_spender]); if (approve(_spender, _value)) { return true; } } /// Function to activate Ether reception in the smart Contract address only by the Owner function () public payable { if(msg.sender != owner) { revert(); } } // Creator/Owner can Locked/Unlock smart contract function OWN_ChangeState_locked(bool _locked) onlyOwner public { SC_locked = _locked; } /// Destroy tokens amount (Caution!!! the operation is destructive and you can not go back) function OWN_burn(uint256 _value) onlyOwner public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; totalSupply -= _value; emit Burn(msg.sender, _value); return true; } /// Destroy tokens amount from another account (Caution!!! the operation is destructive and you can not go back) function OWN_burnAddress(address _from, uint256 _value) onlyOwner public returns (bool success) { require(balances[_from] >= _value); require(_value <= allowed[_from][owner]); balances[_from] -= _value; allowed[_from][msg.sender] -= _value; totalSupply -= _value; emit Burn(_from, _value); return true; } ///Generate other tokens after starting the program function OWN_mintToken(uint256 mintedAmount) onlyOwner public { //aggiungo i decimali al valore che imposto balances[owner] += mintedAmount; totalSupply += mintedAmount; emit Transfer(0, this, mintedAmount); emit Transfer(this, owner, mintedAmount); } /// Block / Unlock address handling tokens function OWN_freezeAddress(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /// Function to destroy the smart contract function OWN_kill() onlyOwner public { selfdestruct(owner); } /// Function Change Owner function OWN_transferOwnership(address newOwner) onlyOwner public { // function allowed only if the address is not smart contract if (!isContract(newOwner)) { owner = newOwner; } } /// Smart Contract approved function OWN_SmartContract_Allowed(address target, bool _allowed) onlyOwner public { // function allowed only for smart contract if (isContract(target)) { SmartContract_Allowed[target] = _allowed; } } /// Distribution Token from Admin function OWN_DistributeTokenAdmin_Multi(address[] addresses, uint256 _value, bool freeze) onlyOwner public{ for (uint i = 0; i < addresses.length; i++) { //Block / Unlock address handling tokens frozenAccount[addresses[i]] = freeze; emit FrozenFunds(addresses[i], freeze); bytes memory empty; if (isContract(addresses[i])) { transferToContract(addresses[i], _value, empty); } else { transferToAddress(addresses[i], _value, empty); } } } }
Function to access symbol of token .
function symbol() public view returns (string _symbol) { return symbol; }
274,394
[ 1, 2083, 358, 2006, 3273, 434, 1147, 263, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3273, 1435, 1071, 1476, 1135, 261, 1080, 389, 7175, 13, 288, 203, 202, 202, 2463, 3273, 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 ]
/* .'''''''''''.. ..''''''''''''''''.. ..'''''''''''''''.. .;;;;;;;;;;;'. .';;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;,. .;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;,. .;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,. .;;;;;;;;;;;;;;;;;;;;,. ';;;;;;;;'. .';;;;;;;;;;;;;;;;;;;;;;,. .';;;;;;;;;;;;;;;;;;;;;,. ';;;;;,.. .';;;;;;;;;;;;;;;;;;;;;;;,..';;;;;;;;;;;;;;;;;;;;;;,. ...... .';;;;;;;;;;;;;,'''''''''''.,;;;;;;;;;;;;;,'''''''''.. .,;;;;;;;;;;;;;. .,;;;;;;;;;;;;;. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .;;;;;;;;;;;;;,. ..... .;;;;;;;;;;;;;'. ..';;;;;;;;;;;;;'. .',;;;;,'. .';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .';;;;;;;;;;. .';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .;;;;;;;;;;;,. .,;;;;;;;;;;;;;'...........,;;;;;;;;;;;;;;. .;;;;;;;;;;;,. .,;;;;;;;;;;;;,..,;;;;;;;;;;;;;;;;;;;;;;;,. ..;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;;,. .',;;;,,.. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;,. .... ..',;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,. ..',;;;;'. .,;;;;;;;;;;;;;;;;;;;'. ...'.. .';;;;;;;;;;;;;;,,,'. ............... */ // https://github.com/trusttoken/smart-contracts // Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol // SPDX-License-Identifier: MIT // pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * // importANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Dependency file: @openzeppelin/contracts/utils/ReentrancyGuard.sol // pragma solidity ^0.6.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // Dependency file: @openzeppelin/contracts/math/SafeMath.sol // pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Dependency file: @openzeppelin/contracts/utils/Address.sol // pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [// importANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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); } } } } // Dependency file: @openzeppelin/contracts/GSN/Context.sol // pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Dependency file: contracts/truefi/common/Initializable.sol // Copied from https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/v3.0.0/contracts/Initializable.sol // pragma solidity 0.6.10; /** * @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; } // Dependency file: contracts/truefi/common/UpgradeableERC20.sol // pragma solidity 0.6.10; // import {Address} from "@openzeppelin/contracts/utils/Address.sol"; // import {Context} from "@openzeppelin/contracts/GSN/Context.sol"; // import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; // import {Initializable} from "contracts/truefi/common/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Initializable, 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. */ function __ERC20_initialize(string memory name, string memory symbol) internal initializer { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public virtual override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public 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 {} function updateNameAndSymbol(string memory __name, string memory __symbol) internal { _name = __name; _symbol = __symbol; } } // Dependency file: contracts/truefi/common/UpgradeableOwnable.sol // pragma solidity 0.6.10; // import {Context} from "@openzeppelin/contracts/GSN/Context.sol"; // import {Initializable} from "contracts/truefi/common/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract 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() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // Dependency file: contracts/truefi/interface/IYToken.sol // pragma solidity 0.6.10; // import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IYToken is IERC20 { function getPricePerFullShare() external view returns (uint256); } // Dependency file: contracts/truefi/interface/ICurve.sol // pragma solidity 0.6.10; // import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import {IYToken} from "contracts/truefi/interface/IYToken.sol"; interface ICurve { function calc_token_amount(uint256[4] memory amounts, bool deposit) external view returns (uint256); function get_virtual_price() external view returns (uint256); } interface ICurveGauge { function balanceOf(address depositor) external view returns (uint256); function minter() external returns (ICurveMinter); function deposit(uint256 amount) external; function withdraw(uint256 amount) external; } interface ICurveMinter { function mint(address gauge) external; function token() external view returns (IERC20); } interface ICurvePool { function add_liquidity(uint256[4] memory amounts, uint256 min_mint_amount) external; function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_amount, bool donate_dust ) external; function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256); function token() external view returns (IERC20); function curve() external view returns (ICurve); function coins(int128 id) external view returns (IYToken); } // Dependency file: contracts/truefi/interface/ITrueFiPool.sol // pragma solidity 0.6.10; // import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * TruePool is an ERC20 which represents a share of a pool * * This contract can be used to wrap opportunities to be compatible * with TrueFi and allow users to directly opt-in through the TUSD contract * * Each TruePool is also a staking opportunity for TRU */ interface ITrueFiPool is IERC20 { /// @dev pool token (TUSD) function currencyToken() external view returns (IERC20); /// @dev stake token (TRU) function stakeToken() external view returns (IERC20); /** * @dev join pool * 1. Transfer TUSD from sender * 2. Mint pool tokens based on value to sender */ function join(uint256 amount) external; /** * @dev exit pool * 1. Transfer pool tokens from sender * 2. Burn pool tokens * 3. Transfer value of pool tokens in TUSD to sender */ function exit(uint256 amount) external; /** * @dev borrow from pool * 1. Transfer TUSD to sender * 2. Only lending pool should be allowed to call this */ function borrow(uint256 amount, uint256 fee) external; /** * @dev join pool * 1. Transfer TUSD from sender * 2. Only lending pool should be allowed to call this */ function repay(uint256 amount) external; } // Dependency file: contracts/truefi/interface/ITrueLender.sol // pragma solidity 0.6.10; interface ITrueLender { function value() external view returns (uint256); function distribute( address recipient, uint256 numerator, uint256 denominator ) external; } // Dependency file: contracts/truefi/interface/IUniswapRouter.sol // pragma solidity 0.6.10; interface IUniswapRouter { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } // Dependency file: contracts/truefi/Log.sol /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ // pragma solidity 0.6.10; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt(uint256 x) internal pure returns (int128) { require(x <= 0x7FFFFFFFFFFFFFFF); return int128(x << 64); } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2(int128 x) internal pure returns (int128) { require(x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = (msb - 64) << 64; uint256 ux = uint256(x) << uint256(127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256(b); } return int128(result); } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln(int128 x) internal pure returns (int128) { require(x > 0); return int128((uint256(log_2(x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF) >> 128); } } // Dependency file: contracts/truefi/interface/ITruPriceOracle.sol // pragma solidity 0.6.10; interface ITruPriceOracle { function usdToTru(uint256 amount) external view returns (uint256); function truToUsd(uint256 amount) external view returns (uint256); } // Root file: contracts/truefi/TrueFiPool.sol pragma solidity 0.6.10; // import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; // import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; // import {ERC20} from "contracts/truefi/common/UpgradeableERC20.sol"; // import {Ownable} from "contracts/truefi/common/UpgradeableOwnable.sol"; // import {ICurveGauge, ICurveMinter, ICurvePool} from "contracts/truefi/interface/ICurve.sol"; // import {ITrueFiPool} from "contracts/truefi/interface/ITrueFiPool.sol"; // import {ITrueLender} from "contracts/truefi/interface/ITrueLender.sol"; // import {IUniswapRouter} from "contracts/truefi/interface/IUniswapRouter.sol"; // import {ABDKMath64x64} from "contracts/truefi/Log.sol"; // import {ITruPriceOracle} from "contracts/truefi/interface/ITruPriceOracle.sol"; /** * @title TrueFi Pool * @dev Lending pool which uses curve.fi to store idle funds * Earn high interest rates on currency deposits through uncollateralized loans * * Funds deposited in this pool are not fully liquid. Luqidity * Exiting the pool has 2 options: * - withdraw a basket of LoanTokens backing the pool * - take an exit penallty depending on pool liquidity * After exiting, an account will need to wait for LoanTokens to expire and burn them * It is recommended to perform a zap or swap tokens on Uniswap for increased liquidity * * Funds are managed through an external function to save gas on deposits */ contract TrueFiPool is ITrueFiPool, ERC20, ReentrancyGuard, Ownable { using SafeMath for uint256; // ================ WARNING ================== // ===== THIS CONTRACT IS INITIALIZABLE ====== // === STORAGE VARIABLES ARE DECLARED BELOW == // REMOVAL OR REORDER OF VARIABLES WILL RESULT // ========= IN STORAGE CORRUPTION =========== ICurvePool public _curvePool; ICurveGauge public _curveGauge; IERC20 public _currencyToken; ITrueLender public _lender; ICurveMinter public _minter; IUniswapRouter public _uniRouter; // fee for deposits uint256 public joiningFee; // track claimable fees uint256 public claimableFees; mapping(address => uint256) latestJoinBlock; IERC20 public _stakeToken; // cache values during sync for gas optimization bool private inSync; uint256 private yTokenValueCache; uint256 private loansValueCache; // TRU price oracle ITruPriceOracle public _oracle; // fund manager can call functions to help manage pool funds // fund manager can be set to 0 or governance address public fundsManager; // allow pausing of deposits bool public isJoiningPaused; // ======= STORAGE DECLARATION END ============ // curve.fi data uint8 constant N_TOKENS = 4; uint8 constant TUSD_INDEX = 3; /** * @dev Emitted when stake token address * @param token New stake token address */ event StakeTokenChanged(IERC20 token); /** * @dev Emitted oracle was changed * @param newOracle New oracle address */ event OracleChanged(ITruPriceOracle newOracle); /** * @dev Emitted when funds manager is changed * @param newManager New manager address */ event FundsManagerChanged(address newManager); /** * @dev Emitted when fee is changed * @param newFee New fee */ event JoiningFeeChanged(uint256 newFee); /** * @dev Emitted when someone joins the pool * @param staker Account staking * @param deposited Amount deposited * @param minted Amount of pool tokens minted */ event Joined(address indexed staker, uint256 deposited, uint256 minted); /** * @dev Emitted when someone exits the pool * @param staker Account exiting * @param amount Amount unstaking */ event Exited(address indexed staker, uint256 amount); /** * @dev Emitted when funds are flushed into curve.fi * @param currencyAmount Amount of tokens deposited */ event Flushed(uint256 currencyAmount); /** * @dev Emitted when funds are pulled from curve.fi * @param yAmount Amount of pool tokens */ event Pulled(uint256 yAmount); /** * @dev Emitted when funds are borrowed from pool * @param borrower Borrower address * @param amount Amount of funds borrowed from pool * @param fee Fees collected from this transaction */ event Borrow(address borrower, uint256 amount, uint256 fee); /** * @dev Emitted when borrower repays the pool * @param payer Address of borrower * @param amount Amount repaid */ event Repaid(address indexed payer, uint256 amount); /** * @dev Emitted when fees are collected * @param beneficiary Account to receive fees * @param amount Amount of fees collected */ event Collected(address indexed beneficiary, uint256 amount); /** * @dev Emitted when joining is paused or unpaused * @param isJoiningPaused New pausing status */ event JoiningPauseStatusChanged(bool isJoiningPaused); /** * @dev Initialize pool * @param __curvePool curve pool address * @param __curveGauge curve gauge address * @param __currencyToken curve pool underlying token * @param __lender TrueLender address * @param __uniRouter Uniswap router */ function initialize( ICurvePool __curvePool, ICurveGauge __curveGauge, IERC20 __currencyToken, ITrueLender __lender, IUniswapRouter __uniRouter, IERC20 __stakeToken, ITruPriceOracle __oracle ) public initializer { ERC20.__ERC20_initialize("TrueFi LP", "TFI-LP"); Ownable.initialize(); _curvePool = __curvePool; _curveGauge = __curveGauge; _currencyToken = __currencyToken; _lender = __lender; _minter = _curveGauge.minter(); _uniRouter = __uniRouter; _stakeToken = __stakeToken; _oracle = __oracle; joiningFee = 25; } /** * @dev only lender can perform borrowing or repaying */ modifier onlyLender() { require(msg.sender == address(_lender), "TrueFiPool: Caller is not the lender"); _; } /** * @dev pool can only be joined when it's unpaused */ modifier joiningNotPaused() { require(!isJoiningPaused, "TrueFiPool: Joining the pool is paused"); _; } /** * @dev only lender can perform borrowing or repaying */ modifier onlyOwnerOrManager() { require(msg.sender == owner() || msg.sender == fundsManager, "TrueFiPool: Caller is neither owner nor funds manager"); _; } /** * Sync values to avoid making expensive calls multiple times * Will set inSync to true, allowing getter functions to return cached values * Wipes cached values to save gas */ modifier sync() { // sync yTokenValueCache = yTokenValue(); loansValueCache = loansValue(); inSync = true; _; // wipe inSync = false; yTokenValueCache = 0; loansValueCache = 0; } /** * @dev get currency token address * @return currency token address */ function currencyToken() public override view returns (IERC20) { return _currencyToken; } /** * @dev get stake token address * @return stake token address */ function stakeToken() public override view returns (IERC20) { return _stakeToken; } /** * @dev set stake token address * @param token stake token address */ function setStakeToken(IERC20 token) public onlyOwner { _stakeToken = token; emit StakeTokenChanged(token); } /** * @dev set funds manager address */ function setFundsManager(address newFundsManager) public onlyOwner { fundsManager = newFundsManager; emit FundsManagerChanged(newFundsManager); } /** * @dev set oracle token address * @param newOracle new oracle address */ function setOracle(ITruPriceOracle newOracle) public onlyOwner { _oracle = newOracle; emit OracleChanged(newOracle); } /** * @dev Allow pausing of deposits in case of emergency * @param status New deposit status */ function changeJoiningPauseStatus(bool status) external onlyOwnerOrManager { isJoiningPaused = status; emit JoiningPauseStatusChanged(status); } /** * @dev Get total balance of stake tokens * @return Balance of stake tokens in this contract */ function stakeTokenBalance() public view returns (uint256) { return _stakeToken.balanceOf(address(this)); } /** * @dev Get total balance of curve.fi pool tokens * @return Balance of y pool tokens in this contract */ function yTokenBalance() public view returns (uint256) { return _curvePool.token().balanceOf(address(this)).add(_curveGauge.balanceOf(address(this))); } /** * @dev Virtual value of yCRV tokens in the pool * Will return sync value if inSync * @return yTokenValue in USD. */ function yTokenValue() public view returns (uint256) { if (inSync) { return yTokenValueCache; } return yTokenBalance().mul(_curvePool.curve().get_virtual_price()).div(1 ether); } /** * @dev Price of TRU in USD * @return Oracle price of TRU in USD */ function truValue() public view returns (uint256) { uint256 balance = stakeTokenBalance(); if (balance == 0) { return 0; } return _oracle.truToUsd(balance); } /** * @dev Virtual value of liquid assets in the pool * @return Virtual liquid value of pool assets */ function liquidValue() public view returns (uint256) { return currencyBalance().add(yTokenValue()); } /** * @dev Calculate pool value in TUSD * "virtual price" of entire pool - LoanTokens, TUSD, curve y pool tokens * @return pool value in USD */ function poolValue() public view returns (uint256) { // this assumes defaulted loans are worth their full value return liquidValue().add(loansValue()); } /** * @dev Virtual value of loan assets in the pool * Will return cached value if inSync * @return Value of loans in pool */ function loansValue() public view returns (uint256) { if (inSync) { return loansValueCache; } return _lender.value(); } /** * @dev ensure enough curve.fi pool tokens are available * Check if current available amount of TUSD is enough and * withdraw remainder from gauge * @param neededAmount amount required */ function ensureEnoughTokensAreAvailable(uint256 neededAmount) internal { uint256 currentlyAvailableAmount = _curvePool.token().balanceOf(address(this)); if (currentlyAvailableAmount < neededAmount) { _curveGauge.withdraw(neededAmount.sub(currentlyAvailableAmount)); } } /** * @dev set pool join fee * @param fee new fee */ function setJoiningFee(uint256 fee) external onlyOwner { require(fee <= 10000, "TrueFiPool: Fee cannot exceed transaction value"); joiningFee = fee; emit JoiningFeeChanged(fee); } /** * @dev sets all token allowances used to 0 */ function resetApprovals() external onlyOwner { _currencyToken.approve(address(_curvePool), 0); _curvePool.token().approve(address(_curvePool), 0); _curvePool.token().approve(address(_curveGauge), 0); } /** * @dev Join the pool by depositing currency tokens * @param amount amount of currency token to deposit */ function join(uint256 amount) external override joiningNotPaused { uint256 fee = amount.mul(joiningFee).div(10000); uint256 mintedAmount = mint(amount.sub(fee)); claimableFees = claimableFees.add(fee); latestJoinBlock[tx.origin] = block.number; require(_currencyToken.transferFrom(msg.sender, address(this), amount)); emit Joined(msg.sender, amount, mintedAmount); } // prettier-ignore /** * @dev Exit pool * This function will withdraw a basket of currencies backing the pool value * @param amount amount of pool tokens to redeem for underlying tokens */ function exit(uint256 amount) external override nonReentrant { require(block.number != latestJoinBlock[tx.origin], "TrueFiPool: Cannot join and exit in same block"); require(amount <= balanceOf(msg.sender), "TrueFiPool: insufficient funds"); uint256 _totalSupply = totalSupply(); // get share of currency tokens kept in the pool uint256 currencyAmountToTransfer = amount.mul( currencyBalance()).div(_totalSupply); // calculate amount of curve.fi pool tokens uint256 curveLiquidityAmountToTransfer = amount.mul( yTokenBalance()).div(_totalSupply); // calculate amount of stake tokens uint256 stakeTokenAmountToTransfer = amount.mul( stakeTokenBalance()).div(_totalSupply); // burn tokens sent _burn(msg.sender, amount); // withdraw basket of loan tokens _lender.distribute(msg.sender, amount, _totalSupply); // if currency remaining, transfer if (currencyAmountToTransfer > 0) { require(_currencyToken.transfer(msg.sender, currencyAmountToTransfer)); } // if curve tokens remaining, transfer if (curveLiquidityAmountToTransfer > 0) { ensureEnoughTokensAreAvailable(curveLiquidityAmountToTransfer); require(_curvePool.token().transfer(msg.sender, curveLiquidityAmountToTransfer)); } // if stake token remaining, transfer if (stakeTokenAmountToTransfer > 0) { require(_stakeToken.transfer(msg.sender, stakeTokenAmountToTransfer)); } emit Exited(msg.sender, amount); } /** * @dev Exit pool only with liquid tokens * This function will withdraw TUSD but with a small penalty * Uses the sync() modifier to reduce gas costs of using curve * @param amount amount of pool tokens to redeem for underlying tokens */ function liquidExit(uint256 amount) external nonReentrant sync { require(block.number != latestJoinBlock[tx.origin], "TrueFiPool: Cannot join and exit in same block"); require(amount <= balanceOf(msg.sender), "TrueFiPool: Insufficient funds"); uint256 amountToWithdraw = poolValue().mul(amount).div(totalSupply()); amountToWithdraw = amountToWithdraw.mul(liquidExitPenalty(amountToWithdraw)).div(10000); require(amountToWithdraw <= liquidValue(), "TrueFiPool: Not enough liquidity in pool"); // burn tokens sent _burn(msg.sender, amount); if (amountToWithdraw > currencyBalance()) { removeLiquidityFromCurve(amountToWithdraw.sub(currencyBalance())); require(amountToWithdraw <= currencyBalance(), "TrueFiPool: Not enough funds were withdrawn from Curve"); } require(_currencyToken.transfer(msg.sender, amountToWithdraw)); emit Exited(msg.sender, amountToWithdraw); } /** * @dev Penalty (in % * 100) applied if liquid exit is performed with this amount * returns 10000 if no penalty */ function liquidExitPenalty(uint256 amount) public view returns (uint256) { uint256 lv = liquidValue(); uint256 pv = poolValue(); if (amount == pv) { return 10000; } uint256 liquidRatioBefore = lv.mul(10000).div(pv); uint256 liquidRatioAfter = lv.sub(amount).mul(10000).div(pv.sub(amount)); return uint256(10000).sub(averageExitPenalty(liquidRatioAfter, liquidRatioBefore)); } /** * @dev Calculates integral of 5/(x+50)dx times 10000 */ function integrateAtPoint(uint256 x) public pure returns (uint256) { return uint256(ABDKMath64x64.ln(ABDKMath64x64.fromUInt(x.add(50)))).mul(50000).div(2**64); } /** * @dev Calculates average penalty on interval [from; to] * @return average exit penalty */ function averageExitPenalty(uint256 from, uint256 to) public pure returns (uint256) { require(from <= to, "TrueFiPool: To precedes from"); if (from == 10000) { // When all liquid, dont penalize return 0; } if (from == to) { return uint256(50000).div(from.add(50)); } return integrateAtPoint(to).sub(integrateAtPoint(from)).div(to.sub(from)); } /** * @dev Deposit idle funds into curve.fi pool and stake in gauge * Called by owner to help manage funds in pool and save on gas for deposits * @param currencyAmount Amount of funds to deposit into curve * @param minMintAmount Minimum amount to mint */ function flush(uint256 currencyAmount, uint256 minMintAmount) external onlyOwnerOrManager { require(currencyAmount <= currencyBalance(), "TrueFiPool: Insufficient currency balance"); uint256[N_TOKENS] memory amounts = [0, 0, 0, currencyAmount]; // add TUSD to curve _currencyToken.approve(address(_curvePool), currencyAmount); _curvePool.add_liquidity(amounts, minMintAmount); // stake yCurve tokens in gauge uint256 yBalance = _curvePool.token().balanceOf(address(this)); _curvePool.token().approve(address(_curveGauge), yBalance); _curveGauge.deposit(yBalance); emit Flushed(currencyAmount); } /** * @dev Remove liquidity from curve * @param yAmount amount of curve pool tokens * @param minCurrencyAmount minimum amount of tokens to withdraw */ function pull(uint256 yAmount, uint256 minCurrencyAmount) external onlyOwnerOrManager { require(yAmount <= yTokenBalance(), "TrueFiPool: Insufficient Curve liquidity balance"); // unstake in gauge ensureEnoughTokensAreAvailable(yAmount); // remove TUSD from curve _curvePool.token().approve(address(_curvePool), yAmount); _curvePool.remove_liquidity_one_coin(yAmount, TUSD_INDEX, minCurrencyAmount, false); emit Pulled(yAmount); } // prettier-ignore /** * @dev Remove liquidity from curve if necessary and transfer to lender * @param amount amount for lender to withdraw */ function borrow(uint256 amount, uint256 fee) external override nonReentrant onlyLender { // if there is not enough TUSD, withdraw from curve if (amount > currencyBalance()) { removeLiquidityFromCurve(amount.sub(currencyBalance())); require(amount <= currencyBalance(), "TrueFiPool: Not enough funds in pool to cover borrow"); } mint(fee); require(_currencyToken.transfer(msg.sender, amount.sub(fee))); emit Borrow(msg.sender, amount, fee); } function removeLiquidityFromCurve(uint256 amountToWithdraw) internal { // get rough estimate of how much yCRV we should sell uint256 roughCurveTokenAmount = calcTokenAmount(amountToWithdraw).mul(1005).div(1000); require(roughCurveTokenAmount <= yTokenBalance(), "TrueFiPool: Not enough Curve liquidity tokens in pool to cover borrow"); // pull tokens from gauge ensureEnoughTokensAreAvailable(roughCurveTokenAmount); // remove TUSD from curve _curvePool.token().approve(address(_curvePool), roughCurveTokenAmount); uint256 minAmount = roughCurveTokenAmount.mul(_curvePool.curve().get_virtual_price()).mul(999).div(1000).div(1 ether); _curvePool.remove_liquidity_one_coin(roughCurveTokenAmount, TUSD_INDEX, minAmount, false); } /** * @dev repay debt by transferring tokens to the contract * @param currencyAmount amount to repay */ function repay(uint256 currencyAmount) external override onlyLender { require(_currencyToken.transferFrom(msg.sender, address(this), currencyAmount)); emit Repaid(msg.sender, currencyAmount); } /** * @dev Collect CRV tokens minted by staking at gauge */ function collectCrv() external onlyOwnerOrManager { _minter.mint(address(_curveGauge)); } /** * @dev Sell collected CRV on Uniswap * - Selling CRV is managed by the contract owner * - Calculations can be made off-chain and called based on market conditions * - Need to pass path of exact pairs to go through while executing exchange * For example, CRV -> WETH -> TUSD * * @param amountIn see https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensfortokens * @param amountOutMin see https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensfortokens * @param path see https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensfortokens */ function sellCrv( uint256 amountIn, uint256 amountOutMin, address[] calldata path ) public onlyOwnerOrManager { _minter.token().approve(address(_uniRouter), amountIn); _uniRouter.swapExactTokensForTokens(amountIn, amountOutMin, path, address(this), block.timestamp + 1 hours); } /** * @dev Sell collected TRU on Uniswap * - Selling TRU is managed by the contract owner * - Calculations can be made off-chain and called based on market conditions * - Need to pass path of exact pairs to go through while executing exchange * For example, CRV -> WETH -> TUSD * * @param amountIn see https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensfortokens * @param amountOutMin see https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensfortokens * @param path see https://uniswap.org/docs/v2/smart-contracts/router02/#swapexacttokensfortokens */ function sellStakeToken( uint256 amountIn, uint256 amountOutMin, address[] calldata path ) public onlyOwnerOrManager { _stakeToken.approve(address(_uniRouter), amountIn); _uniRouter.swapExactTokensForTokens(amountIn, amountOutMin, path, address(this), block.timestamp + 1 hours); } /** * @dev Claim fees from the pool * @param beneficiary account to send funds to */ function collectFees(address beneficiary) external onlyOwnerOrManager { uint256 amount = claimableFees; claimableFees = 0; if (amount > 0) { require(_currencyToken.transfer(beneficiary, amount)); } emit Collected(beneficiary, amount); } /** * @notice Expected amount of minted Curve.fi yDAI/yUSDC/yUSDT/yTUSD tokens. * Can be used to control slippage * Called in flush() function * @param currencyAmount amount to calculate for * @return expected amount minted given currency amount */ function calcTokenAmount(uint256 currencyAmount) public view returns (uint256) { // prettier-ignore uint256 yTokenAmount = currencyAmount.mul(1e18).div( _curvePool.coins(TUSD_INDEX).getPricePerFullShare()); uint256[N_TOKENS] memory yAmounts = [0, 0, 0, yTokenAmount]; return _curvePool.curve().calc_token_amount(yAmounts, true); } /** * @dev Converts the value of a single yCRV into an underlying asset * @param yAmount amount of curve pool tokens to calculate for * @return Value of one y pool token */ function calcWithdrawOneCoin(uint256 yAmount) public view returns (uint256) { return _curvePool.calc_withdraw_one_coin(yAmount, TUSD_INDEX); } /** * @dev Currency token balance * @return Currency token balance */ function currencyBalance() internal view returns (uint256) { return _currencyToken.balanceOf(address(this)).sub(claimableFees); } /** * @param depositedAmount Amount of currency deposited * @return amount minted from this transaction */ function mint(uint256 depositedAmount) internal returns (uint256) { uint256 mintedAmount = depositedAmount; if (mintedAmount == 0) { return mintedAmount; } // first staker mints same amount deposited if (totalSupply() > 0) { mintedAmount = totalSupply().mul(depositedAmount).div(poolValue()); } // mint pool tokens _mint(msg.sender, mintedAmount); return mintedAmount; } /** * @dev Update name and symbol of this contract */ function updateNameAndSymbol() public { super.updateNameAndSymbol("TrueFi TrueUSD", "tfTUSD"); } }
* @dev Remove liquidity from curve @param yAmount amount of curve pool tokens @param minCurrencyAmount minimum amount of tokens to withdraw/ unstake in gauge remove TUSD from curve
function pull(uint256 yAmount, uint256 minCurrencyAmount) external onlyOwnerOrManager { require(yAmount <= yTokenBalance(), "TrueFiPool: Insufficient Curve liquidity balance"); ensureEnoughTokensAreAvailable(yAmount); _curvePool.token().approve(address(_curvePool), yAmount); _curvePool.remove_liquidity_one_coin(yAmount, TUSD_INDEX, minCurrencyAmount, false); emit Pulled(yAmount); }
399,490
[ 1, 3288, 4501, 372, 24237, 628, 8882, 225, 677, 6275, 3844, 434, 8882, 2845, 2430, 225, 1131, 7623, 6275, 5224, 3844, 434, 2430, 358, 598, 9446, 19, 640, 334, 911, 316, 13335, 1206, 399, 3378, 40, 628, 8882, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6892, 12, 11890, 5034, 677, 6275, 16, 2254, 5034, 1131, 7623, 6275, 13, 3903, 1338, 5541, 1162, 1318, 288, 203, 3639, 2583, 12, 93, 6275, 1648, 677, 1345, 13937, 9334, 315, 5510, 42, 77, 2864, 30, 22085, 11339, 22901, 4501, 372, 24237, 11013, 8863, 203, 203, 3639, 3387, 664, 4966, 5157, 4704, 5268, 12, 93, 6275, 1769, 203, 203, 3639, 389, 16683, 2864, 18, 2316, 7675, 12908, 537, 12, 2867, 24899, 16683, 2864, 3631, 677, 6275, 1769, 203, 3639, 389, 16683, 2864, 18, 4479, 67, 549, 372, 24237, 67, 476, 67, 12645, 12, 93, 6275, 16, 399, 3378, 40, 67, 9199, 16, 1131, 7623, 6275, 16, 629, 1769, 203, 203, 3639, 3626, 453, 332, 1259, 12, 93, 6275, 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 ]
/* * Origin Protocol * https://originprotocol.com * * Released under the MIT license * https://github.com/OriginProtocol/origin-dollar * * Copyright 2020 Origin Protocol, Inc * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // File: @openzeppelin/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/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/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/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: contracts/interfaces/IStrategy.sol pragma solidity 0.5.11; /** * @title Platform interface to integrate with lending platform like Compound, AAVE etc. */ interface IStrategy { /** * @dev Deposit the given asset to Lending platform. * @param _asset asset address * @param _amount Amount to deposit */ function deposit(address _asset, uint256 _amount) external returns (uint256 amountDeposited); /** * @dev Withdraw given asset from Lending platform */ function withdraw( address _recipient, address _asset, uint256 _amount ) external returns (uint256 amountWithdrawn); /** * @dev Returns the current balance of the given asset. */ function checkBalance(address _asset) external view returns (uint256 balance); /** * @dev Returns bool indicating whether strategy supports asset. */ function supportsAsset(address _asset) external view returns (bool); /** * @dev Liquidate all assets in strategy and return them to Vault. */ function liquidate() external; /** * @dev Collect reward tokens from the Strategy. */ function collectRewardToken() external; /** * @dev The address of the reward token for the Strategy. */ function rewardTokenAddress() external pure returns (address); /** * @dev The threshold (denominated in the reward token) over which the * vault will auto harvest on allocate calls. */ function rewardLiquidationThreshold() external pure returns (uint256); } // File: contracts/governance/Governable.sol pragma solidity 0.5.11; /** * @title OUSD Governable Contract * @dev Copy of the openzeppelin Ownable.sol contract with nomenclature change * from owner to governor and renounce methods removed. Does not use * Context.sol like Ownable.sol does for simplification. * @author Origin Protocol Inc */ contract Governable { // Storage position of the owner and pendingOwner of the contract bytes32 private constant governorPosition = 0x7bea13895fa79d2831e0a9e28edede30099005a50d652d8957cf8a607ee6ca4a; //keccak256("OUSD.governor"); bytes32 private constant pendingGovernorPosition = 0x44c4d30b2eaad5130ad70c3ba6972730566f3e6359ab83e800d905c61b1c51db; //keccak256("OUSD.pending.governor"); event PendingGovernorshipTransfer( address indexed previousGovernor, address indexed newGovernor ); event GovernorshipTransferred( address indexed previousGovernor, address indexed newGovernor ); /** * @dev Initializes the contract setting the deployer as the initial Governor. */ constructor() internal { _setGovernor(msg.sender); emit GovernorshipTransferred(address(0), _governor()); } /** * @dev Returns the address of the current Governor. */ function governor() public view returns (address) { return _governor(); } function _governor() internal view returns (address governorOut) { bytes32 position = governorPosition; assembly { governorOut := sload(position) } } function _pendingGovernor() internal view returns (address pendingGovernor) { bytes32 position = pendingGovernorPosition; assembly { pendingGovernor := sload(position) } } /** * @dev Throws if called by any account other than the Governor. */ modifier onlyGovernor() { require(isGovernor(), "Caller is not the Governor"); _; } /** * @dev Returns true if the caller is the current Governor. */ function isGovernor() public view returns (bool) { return msg.sender == _governor(); } function _setGovernor(address newGovernor) internal { bytes32 position = governorPosition; assembly { sstore(position, newGovernor) } } function _setPendingGovernor(address newGovernor) internal { bytes32 position = pendingGovernorPosition; assembly { sstore(position, newGovernor) } } /** * @dev Transfers Governance of the contract to a new account (`newGovernor`). * Can only be called by the current Governor. Must be claimed for this to complete * @param _newGovernor Address of the new Governor */ function transferGovernance(address _newGovernor) external onlyGovernor { _setPendingGovernor(_newGovernor); emit PendingGovernorshipTransfer(_governor(), _newGovernor); } /** * @dev Claim Governance of the contract to a new account (`newGovernor`). * Can only be called by the new Governor. */ function claimGovernance() external { require( msg.sender == _pendingGovernor(), "Only the pending Governor can complete the claim" ); _changeGovernor(msg.sender); } /** * @dev Change Governance of the contract to a new account (`newGovernor`). * @param _newGovernor Address of the new Governor */ function _changeGovernor(address _newGovernor) internal { require(_newGovernor != address(0), "New Governor is address(0)"); emit GovernorshipTransferred(_governor(), _newGovernor); _setGovernor(_newGovernor); } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "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 returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "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 { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } // File: contracts/utils/InitializableERC20Detailed.sol pragma solidity 0.5.11; /** * @dev Optional functions from the ERC20 standard. * Converted from openzeppelin/contracts/token/ERC20/ERC20Detailed.sol */ contract InitializableERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. * @notice To avoid variable shadowing appended `Arg` after arguments name. */ function _initialize( string memory nameArg, string memory symbolArg, uint8 decimalsArg ) internal { _name = nameArg; _symbol = symbolArg; _decimals = decimalsArg; } /** * @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; } } // File: contracts/utils/InitializableToken.sol pragma solidity 0.5.11; contract InitializableToken is ERC20, InitializableERC20Detailed { /** * @dev Initialization function for implementing contract * @notice To avoid variable shadowing appended `Arg` after arguments name. */ function _initialize(string memory _nameArg, string memory _symbolArg) internal { InitializableERC20Detailed._initialize(_nameArg, _symbolArg, 18); } } // File: contracts/utils/StableMath.sol pragma solidity 0.5.11; // Based on StableMath from Stability Labs Pty. Ltd. // https://github.com/mstable/mStable-contracts/blob/master/contracts/shared/StableMath.sol library StableMath { using SafeMath for uint256; /** * @dev Scaling unit for use in specific calculations, * where 1 * 10**18, or 1e18 represents a unit '1' */ uint256 private constant FULL_SCALE = 1e18; /*************************************** Helpers ****************************************/ /** * @dev Adjust the scale of an integer * @param adjustment Amount to adjust by e.g. scaleBy(1e18, -1) == 1e17 */ function scaleBy(uint256 x, int8 adjustment) internal pure returns (uint256) { if (adjustment > 0) { x = x.mul(10**uint256(adjustment)); } else if (adjustment < 0) { x = x.div(10**uint256(adjustment * -1)); } return x; } /*************************************** Precise Arithmetic ****************************************/ /** * @dev Multiplies two precise units, and then truncates by the full scale * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) { return mulTruncateScale(x, y, FULL_SCALE); } /** * @dev Multiplies two precise units, and then truncates by the given scale. For example, * when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18 * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @param scale Scale unit * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncateScale( uint256 x, uint256 y, uint256 scale ) internal pure returns (uint256) { // e.g. assume scale = fullScale // z = 10e18 * 9e17 = 9e36 uint256 z = x.mul(y); // return 9e38 / 1e18 = 9e18 return z.div(scale); } /** * @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit, rounded up to the closest base unit. */ function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e17 * 17268172638 = 138145381104e17 uint256 scaled = x.mul(y); // e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17 uint256 ceil = scaled.add(FULL_SCALE.sub(1)); // e.g. 13814538111.399...e18 / 1e18 = 13814538111 return ceil.div(FULL_SCALE); } /** * @dev Precisely divides two units, by first scaling the left hand operand. Useful * for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17) * @param x Left hand input to division * @param y Right hand input to division * @return Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e18 * 1e18 = 8e36 uint256 z = x.mul(FULL_SCALE); // e.g. 8e36 / 10e18 = 8e17 return z.div(y); } } // File: contracts/token/OUSD.sol pragma solidity 0.5.11; /** * @title OUSD Token Contract * @dev ERC20 compatible contract for OUSD * @dev Implements an elastic supply * @author Origin Protocol Inc */ contract OUSD is Initializable, InitializableToken, Governable { using SafeMath for uint256; using StableMath for uint256; event TotalSupplyUpdated( uint256 totalSupply, uint256 rebasingCredits, uint256 rebasingCreditsPerToken ); uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1 uint256 private _totalSupply; uint256 public rebasingCredits; // Exchange rate between internal credits and OUSD uint256 public rebasingCreditsPerToken; mapping(address => uint256) private _creditBalances; // Allowances denominated in OUSD mapping(address => mapping(address => uint256)) private _allowances; address public vaultAddress = address(0); // Frozen address/credits are non rebasing (value is held in contracts which // do not receive yield unless they explicitly opt in) uint256 public nonRebasingCredits; uint256 public nonRebasingSupply; mapping(address => uint256) public nonRebasingCreditsPerToken; mapping(address => bool) public rebaseOptInList; function initialize( string calldata _nameArg, string calldata _symbolArg, address _vaultAddress ) external onlyGovernor initializer { InitializableToken._initialize(_nameArg, _symbolArg); _totalSupply = 0; rebasingCredits = 0; rebasingCreditsPerToken = 1e18; vaultAddress = _vaultAddress; nonRebasingCredits = 0; nonRebasingSupply = 0; } /** * @dev Verifies that the caller is the Savings Manager contract */ modifier onlyVault() { require(vaultAddress == msg.sender, "Caller is not the Vault"); _; } /** * @return The total supply of OUSD. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param _account Address to query the balance of. * @return A uint256 representing the _amount of base units owned by the * specified address. */ function balanceOf(address _account) public view returns (uint256) { return _creditBalances[_account].divPrecisely(_creditsPerToken(_account)); } /** * @dev Gets the credits balance of the specified address. * @param _account The address to query the balance of. * @return (uint256, uint256) Credit balance and credits per token of the * address */ function creditsBalanceOf(address _account) public view returns (uint256, uint256) { return (_creditBalances[_account], _creditsPerToken(_account)); } /** * @dev Transfer tokens to a specified address. * @param _to the address to transfer to. * @param _value the _amount to be transferred. * @return true on success. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0), "Transfer to zero address"); _executeTransfer(msg.sender, _to, _value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another. * @param _from The address you want to send tokens from. * @param _to The address you want to transfer to. * @param _value The _amount of tokens to be transferred. */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0), "Transfer to zero address"); _allowances[_from][msg.sender] = _allowances[_from][msg.sender].sub( _value ); _executeTransfer(_from, _to, _value); emit Transfer(_from, _to, _value); return true; } /** * @dev Update the count of non rebasing credits in response to a transfer * @param _from The address you want to send tokens from. * @param _to The address you want to transfer to. * @param _value Amount of OUSD to transfer */ function _executeTransfer( address _from, address _to, uint256 _value ) internal { // Credits deducted and credited might be different due to the // differing creditsPerToken used by each account uint256 creditsDeducted = _value.mulTruncate(_creditsPerToken(_from)); uint256 creditsCredited = _value.mulTruncate(_creditsPerToken(_to)); _creditBalances[_from] = _creditBalances[_from].sub( creditsDeducted, "Transfer amount exceeds balance" ); _creditBalances[_to] = _creditBalances[_to].add(creditsCredited); bool isNonRebasingTo = _isNonRebasingAddress(_to); bool isNonRebasingFrom = _isNonRebasingAddress(_from); if (isNonRebasingTo && !isNonRebasingFrom) { // Transfer to non-rebasing account from rebasing account, credits // are removed from the non rebasing tally nonRebasingCredits = nonRebasingCredits.add(creditsCredited); nonRebasingSupply = nonRebasingSupply.add(_value); // Update rebasingCredits by subtracting the deducted amount rebasingCredits = rebasingCredits.sub(creditsDeducted); } else if (!isNonRebasingTo && isNonRebasingFrom) { // Transfer to rebasing account from non-rebasing account // Decreasing non-rebasing credits by the amount that was sent nonRebasingCredits = nonRebasingCredits.sub(creditsDeducted); nonRebasingSupply = nonRebasingSupply.sub(_value); // Update rebasingCredits by adding the credited amount rebasingCredits = rebasingCredits.add(creditsCredited); } else if (isNonRebasingTo && isNonRebasingFrom) { // Transfer between two non rebasing accounts. They may have // different exchange rates so update the count of non rebasing // credits with the difference nonRebasingCredits = nonRebasingCredits + creditsCredited - creditsDeducted; } // Make sure the fixed credits per token get set for to/from accounts if // they have not been if (isNonRebasingTo && nonRebasingCreditsPerToken[_to] == 0) { nonRebasingCreditsPerToken[_to] = rebasingCreditsPerToken; } if (isNonRebasingFrom && nonRebasingCreditsPerToken[_from] == 0) { nonRebasingCreditsPerToken[_from] = rebasingCreditsPerToken; } } /** * @dev Function to check the _amount of tokens that an owner has allowed to a _spender. * @param _owner The address which owns the funds. * @param _spender The address which will spend the funds. * @return The number of tokens still available for the _spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return _allowances[_owner][_spender]; } /** * @dev Approve the passed address to spend the specified _amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param _spender The address which will spend the funds. * @param _value The _amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { _allowances[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Increase the _amount of tokens that an owner has allowed to a _spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param _spender The address which will spend the funds. * @param _addedValue The _amount of tokens to increase the allowance by. */ function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) { _allowances[msg.sender][_spender] = _allowances[msg.sender][_spender] .add(_addedValue); emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]); return true; } /** * @dev Decrease the _amount of tokens that an owner has allowed to a _spender. * @param _spender The address which will spend the funds. * @param _subtractedValue The _amount of tokens to decrease the allowance by. */ function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) { uint256 oldValue = _allowances[msg.sender][_spender]; if (_subtractedValue >= oldValue) { _allowances[msg.sender][_spender] = 0; } else { _allowances[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]); return true; } /** * @dev Mints new tokens, increasing totalSupply. */ function mint(address _account, uint256 _amount) external onlyVault { return _mint(_account, _amount); } /** * @dev Creates `_amount` tokens and assigns them to `_account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address _account, uint256 _amount) internal { require(_account != address(0), "Mint to the zero address"); uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account)); bool isNonRebasingAccount = _isNonRebasingAddress(_account); // If the account is non rebasing and doesn't have a set creditsPerToken // then set it i.e. this is a mint from a fresh contract if (isNonRebasingAccount) { if (nonRebasingCreditsPerToken[_account] == 0) { nonRebasingCreditsPerToken[_account] = rebasingCreditsPerToken; } nonRebasingCredits = nonRebasingCredits.add(creditAmount); nonRebasingSupply = nonRebasingSupply.add(_amount); } else { rebasingCredits = rebasingCredits.add(creditAmount); } _creditBalances[_account] = _creditBalances[_account].add(creditAmount); _totalSupply = _totalSupply.add(_amount); emit Transfer(address(0), _account, _amount); } /** * @dev Burns tokens, decreasing totalSupply. */ function burn(address account, uint256 amount) external onlyVault { return _burn(account, amount); } /** * @dev Destroys `_amount` tokens from `_account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `_account` cannot be the zero address. * - `_account` must have at least `_amount` tokens. */ function _burn(address _account, uint256 _amount) internal { require(_account != address(0), "Burn from the zero address"); bool isNonRebasingAccount = _isNonRebasingAddress(_account); uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account)); uint256 currentCredits = _creditBalances[_account]; // Remove the credits, burning rounding errors if ( currentCredits == creditAmount || currentCredits - 1 == creditAmount ) { // Handle dust from rounding _creditBalances[_account] = 0; } else if (currentCredits > creditAmount) { _creditBalances[_account] = _creditBalances[_account].sub( creditAmount ); } else { revert("Remove exceeds balance"); } _totalSupply = _totalSupply.sub(_amount); if (isNonRebasingAccount) { nonRebasingCredits = nonRebasingCredits.sub(creditAmount); nonRebasingSupply = nonRebasingSupply.sub(_amount); } else { rebasingCredits.sub(creditAmount); } emit Transfer(_account, address(0), _amount); } /** * @dev Get the credits per token for an account. Returns a fixed amount * if the account is non-rebasing. * @param _account Address of the account. */ function _creditsPerToken(address _account) internal view returns (uint256) { if (nonRebasingCreditsPerToken[_account] != 0) { return nonRebasingCreditsPerToken[_account]; } else { return rebasingCreditsPerToken; } } /** * @dev Is an accounts balance non rebasing, i.e. does not alter with rebases * @param _account Address of the account. */ function _isNonRebasingAddress(address _account) internal view returns (bool) { return Address.isContract(_account) && !rebaseOptInList[_account]; } /** * @dev Add a contract address to the non rebasing exception list. I.e. the * address's balance will be part of rebases so the account will be exposed * to upside and downside. */ function rebaseOptIn() public { require(_isNonRebasingAddress(msg.sender), "Account has not opted out"); // Convert balance into the same amount at the current exchange rate uint256 newCreditBalance = _creditBalances[msg.sender] .mul(rebasingCreditsPerToken) .div(_creditsPerToken(msg.sender)); nonRebasingSupply = nonRebasingSupply.sub(balanceOf(msg.sender)); nonRebasingCredits = nonRebasingCredits.sub( _creditBalances[msg.sender] ); _creditBalances[msg.sender] = newCreditBalance; rebaseOptInList[msg.sender] = true; delete nonRebasingCreditsPerToken[msg.sender]; } /** * @dev Remove a contract address to the non rebasing exception list. */ function rebaseOptOut() public { require(!_isNonRebasingAddress(msg.sender), "Account has not opted in"); nonRebasingCredits = nonRebasingCredits.add( _creditBalances[msg.sender] ); nonRebasingSupply = nonRebasingSupply.add(balanceOf(msg.sender)); nonRebasingCreditsPerToken[msg.sender] = rebasingCreditsPerToken; delete rebaseOptInList[msg.sender]; } /** * @dev Modify the supply without minting new tokens. This uses a change in * the exchange rate between "credits" and OUSD tokens to change balances. * @param _newTotalSupply New total supply of OUSD. * @return uint256 representing the new total supply. */ function changeSupply(uint256 _newTotalSupply) external onlyVault returns (uint256) { require(_totalSupply > 0, "Cannot increase 0 supply"); if (_totalSupply == _newTotalSupply) { emit TotalSupplyUpdated( _totalSupply, rebasingCredits, rebasingCreditsPerToken ); return _totalSupply; } _totalSupply = _newTotalSupply; if (_totalSupply > MAX_SUPPLY) _totalSupply = MAX_SUPPLY; rebasingCreditsPerToken = rebasingCredits.divPrecisely( _totalSupply.sub(nonRebasingSupply) ); emit TotalSupplyUpdated( _totalSupply, rebasingCredits, rebasingCreditsPerToken ); return _totalSupply; } } // File: contracts/interfaces/IBasicToken.sol pragma solidity 0.5.11; interface IBasicToken { function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // File: contracts/utils/Helpers.sol pragma solidity 0.5.11; library Helpers { /** * @notice Fetch the `symbol()` from an ERC20 token * @dev Grabs the `symbol()` from a contract * @param _token Address of the ERC20 token * @return string Symbol of the ERC20 token */ function getSymbol(address _token) internal view returns (string memory) { string memory symbol = IBasicToken(_token).symbol(); return symbol; } /** * @notice Fetch the `decimals()` from an ERC20 token * @dev Grabs the `decimals()` from a contract and fails if * the decimal value does not live within a certain range * @param _token Address of the ERC20 token * @return uint256 Decimals of the ERC20 token */ function getDecimals(address _token) internal view returns (uint256) { uint256 decimals = IBasicToken(_token).decimals(); require( decimals >= 4 && decimals <= 18, "Token must have sufficient decimal places" ); return decimals; } } // File: contracts/vault/VaultStorage.sol pragma solidity 0.5.11; /** * @title OUSD VaultStorage Contract * @notice The VaultStorage contract defines the storage for the Vault contracts * @author Origin Protocol Inc */ contract VaultStorage is Initializable, Governable { using SafeMath for uint256; using StableMath for uint256; using SafeMath for int256; using SafeERC20 for IERC20; event AssetSupported(address _asset); event StrategyAdded(address _addr); event StrategyRemoved(address _addr); event Mint(address _addr, uint256 _value); event Redeem(address _addr, uint256 _value); event StrategyWeightsUpdated( address[] _strategyAddresses, uint256[] weights ); event DepositsPaused(); event DepositsUnpaused(); // Assets supported by the Vault, i.e. Stablecoins struct Asset { bool isSupported; } mapping(address => Asset) assets; address[] allAssets; // Strategies supported by the Vault struct Strategy { bool isSupported; uint256 targetWeight; // 18 decimals. 100% = 1e18 } mapping(address => Strategy) strategies; address[] allStrategies; // Address of the Oracle price provider contract address public priceProvider; // Pausing bools bool public rebasePaused = false; bool public depositPaused = true; // Redemption fee in basis points uint256 public redeemFeeBps; // Buffer of assets to keep in Vault to handle (most) withdrawals uint256 public vaultBuffer; // Mints over this amount automatically allocate funds. 18 decimals. uint256 public autoAllocateThreshold; // Mints over this amount automatically rebase. 18 decimals. uint256 public rebaseThreshold; OUSD oUSD; //keccak256("OUSD.vault.governor.admin.impl"); bytes32 constant adminImplPosition = 0xa2bd3d3cf188a41358c8b401076eb59066b09dec5775650c0de4c55187d17bd9; // Address of the contract responsible for post rebase syncs with AMMs address public rebaseHooksAddr = address(0); // Address of Uniswap address public uniswapAddr = address(0); /** * @dev set the implementation for the admin, this needs to be in a base class else we cannot set it * @param newImpl address pf the implementation */ function setAdminImpl(address newImpl) external onlyGovernor { bytes32 position = adminImplPosition; assembly { sstore(position, newImpl) } } } // File: contracts/interfaces/IMinMaxOracle.sol pragma solidity 0.5.11; interface IMinMaxOracle { //Assuming 8 decimals function priceMin(string calldata symbol) external returns (uint256); function priceMax(string calldata symbol) external returns (uint256); } interface IViewMinMaxOracle { function priceMin(string calldata symbol) external view returns (uint256); function priceMax(string calldata symbol) external view returns (uint256); } // File: contracts/interfaces/IRebaseHooks.sol pragma solidity 0.5.11; interface IRebaseHooks { function postRebase(bool sync) external; } // File: contracts/interfaces/IVault.sol pragma solidity 0.5.11; interface IVault { event AssetSupported(address _asset); event StrategyAdded(address _addr); event StrategyRemoved(address _addr); event Mint(address _addr, uint256 _value); event Redeem(address _addr, uint256 _value); event StrategyWeightsUpdated( address[] _strategyAddresses, uint256[] weights ); event DepositsPaused(); event DepositsUnpaused(); // Governable.sol function transferGovernance(address _newGovernor) external; function claimGovernance() external; function governor() external view returns (address); // VaultAdmin.sol function setPriceProvider(address _priceProvider) external; function priceProvider() external view returns (address); function setRedeemFeeBps(uint256 _redeemFeeBps) external; function redeemFeeBps() external view returns (uint256); function setVaultBuffer(uint256 _vaultBuffer) external; function vaultBuffer() external view returns (uint256); function setAutoAllocateThreshold(uint256 _threshold) external; function autoAllocateThreshold() external view returns (uint256); function setRebaseThreshold(uint256 _threshold) external; function rebaseThreshold() external view returns (uint256); function setRebaseHooksAddr(address _address) external; function rebaseHooksAddr() external view returns (address); function setUniswapAddr(address _address) external; function uniswapAddr() external view returns (address); function supportAsset(address _asset) external; function addStrategy(address _addr, uint256 _targetWeight) external; function removeStrategy(address _addr) external; function setStrategyWeights( address[] calldata _strategyAddresses, uint256[] calldata _weights ) external; function pauseRebase() external; function unpauseRebase() external; function rebasePaused() external view returns (bool); function pauseDeposits() external; function unpauseDeposits() external; function depositPaused() external view returns (bool); function transferToken(address _asset, uint256 _amount) external; function harvest() external; function harvest(address _strategyAddr) external; function priceUSDMint(string calldata symbol) external returns (uint256); function priceUSDRedeem(string calldata symbol) external returns (uint256); // VaultCore.sol function mint(address _asset, uint256 _amount) external; function mintMultiple( address[] calldata _assets, uint256[] calldata _amount ) external; function redeem(uint256 _amount) external; function redeemAll() external; function allocate() external; function rebase() external returns (uint256); function checkBalance() external view returns (uint256); function checkBalance(address _asset) external view returns (uint256); function calculateRedeemOutputs(uint256 _amount) external returns (uint256[] memory); function getAssetCount() external view returns (uint256); function getAllAssets() external view returns (address[] memory); function getStrategyCount() external view returns (uint256); function isSupportedAsset(address _asset) external view returns (bool); } // File: contracts/vault/VaultCore.sol pragma solidity 0.5.11; /** * @title OUSD Vault Contract * @notice The Vault contract stores assets. On a deposit, OUSD will be minted and sent to the depositor. On a withdrawal, OUSD will be burned and assets will be sent to the withdrawer. The Vault accepts deposits of interest form yield bearing strategies which will modify the supply of OUSD. * @author Origin Protocol Inc */ contract VaultCore is VaultStorage { uint256 constant MAX_UINT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; /** * @dev Verifies that the rebasing is not paused. */ modifier whenNotRebasePaused() { require(!rebasePaused, "Rebasing paused"); _; } /** * @dev Verifies that the deposits are not paused. */ modifier whenNotDepositPaused() { require(!depositPaused, "Deposits paused"); _; } /** * @dev Deposit a supported asset and mint OUSD. * @param _asset Address of the asset being deposited * @param _amount Amount of the asset being deposited */ function mint(address _asset, uint256 _amount) external whenNotDepositPaused { require(assets[_asset].isSupported, "Asset is not supported"); require(_amount > 0, "Amount must be greater than 0"); uint256 price = IMinMaxOracle(priceProvider).priceMin( Helpers.getSymbol(_asset) ); if (price > 1e8) { price = 1e8; } uint256 priceAdjustedDeposit = _amount.mulTruncateScale( price.scaleBy(int8(10)), // 18-8 because oracles have 8 decimals precision 10**Helpers.getDecimals(_asset) ); // Rebase must happen before any transfers occur. if (priceAdjustedDeposit > rebaseThreshold && !rebasePaused) { rebase(true); } // Transfer the deposited coins to the vault IERC20 asset = IERC20(_asset); asset.safeTransferFrom(msg.sender, address(this), _amount); // Mint matching OUSD oUSD.mint(msg.sender, priceAdjustedDeposit); emit Mint(msg.sender, priceAdjustedDeposit); if (priceAdjustedDeposit >= autoAllocateThreshold) { allocate(); } } /** * @dev Mint for multiple assets in the same call. * @param _assets Addresses of assets being deposited * @param _amounts Amount of each asset at the same index in the _assets * to deposit. */ function mintMultiple( address[] calldata _assets, uint256[] calldata _amounts ) external whenNotDepositPaused { require(_assets.length == _amounts.length, "Parameter length mismatch"); uint256 priceAdjustedTotal = 0; uint256[] memory assetPrices = _getAssetPrices(false); for (uint256 i = 0; i < allAssets.length; i++) { for (uint256 j = 0; j < _assets.length; j++) { if (_assets[j] == allAssets[i]) { if (_amounts[j] > 0) { uint256 assetDecimals = Helpers.getDecimals( allAssets[i] ); uint256 price = assetPrices[i]; if (price > 1e18) { price = 1e18; } priceAdjustedTotal += _amounts[j].mulTruncateScale( price, 10**assetDecimals ); } } } } // Rebase must happen before any transfers occur. if (priceAdjustedTotal > rebaseThreshold && !rebasePaused) { rebase(true); } for (uint256 i = 0; i < _assets.length; i++) { IERC20 asset = IERC20(_assets[i]); asset.safeTransferFrom(msg.sender, address(this), _amounts[i]); } oUSD.mint(msg.sender, priceAdjustedTotal); emit Mint(msg.sender, priceAdjustedTotal); if (priceAdjustedTotal >= autoAllocateThreshold) { allocate(); } } /** * @dev Withdraw a supported asset and burn OUSD. * @param _amount Amount of OUSD to burn */ function redeem(uint256 _amount) public { if (_amount > rebaseThreshold && !rebasePaused) { rebase(false); } _redeem(_amount); } function _redeem(uint256 _amount) internal { require(_amount > 0, "Amount must be greater than 0"); // Calculate redemption outputs uint256[] memory outputs = _calculateRedeemOutputs(_amount); // Send outputs for (uint256 i = 0; i < allAssets.length; i++) { if (outputs[i] == 0) continue; IERC20 asset = IERC20(allAssets[i]); if (asset.balanceOf(address(this)) >= outputs[i]) { // Use Vault funds first if sufficient asset.safeTransfer(msg.sender, outputs[i]); } else { address strategyAddr = _selectWithdrawStrategyAddr( allAssets[i], outputs[i] ); if (strategyAddr != address(0)) { // Nothing in Vault, but something in Strategy, send from there IStrategy strategy = IStrategy(strategyAddr); strategy.withdraw(msg.sender, allAssets[i], outputs[i]); } else { // Cant find funds anywhere revert("Liquidity error"); } } } oUSD.burn(msg.sender, _amount); // Until we can prove that we won't affect the prices of our assets // by withdrawing them, this should be here. // It's possible that a strategy was off on its asset total, perhaps // a reward token sold for more or for less than anticipated. if (_amount > rebaseThreshold && !rebasePaused) { rebase(true); } emit Redeem(msg.sender, _amount); } /** * @notice Withdraw a supported asset and burn all OUSD. */ function redeemAll() external { //unfortunately we have to do balanceOf twice if (oUSD.balanceOf(msg.sender) > rebaseThreshold && !rebasePaused) { rebase(false); } _redeem(oUSD.balanceOf(msg.sender)); } /** * @notice Allocate unallocated funds on Vault to strategies. * @dev Allocate unallocated funds on Vault to strategies. **/ function allocate() public { _allocate(); } /** * @notice Allocate unallocated funds on Vault to strategies. * @dev Allocate unallocated funds on Vault to strategies. **/ function _allocate() internal { uint256 vaultValue = _totalValueInVault(); // Nothing in vault to allocate if (vaultValue == 0) return; uint256 strategiesValue = _totalValueInStrategies(); // We have a method that does the same as this, gas optimisation uint256 totalValue = vaultValue + strategiesValue; // We want to maintain a buffer on the Vault so calculate a percentage // modifier to multiply each amount being allocated by to enforce the // vault buffer uint256 vaultBufferModifier; if (strategiesValue == 0) { // Nothing in Strategies, allocate 100% minus the vault buffer to // strategies vaultBufferModifier = 1e18 - vaultBuffer; } else { vaultBufferModifier = vaultBuffer.mul(totalValue).div(vaultValue); if (1e18 > vaultBufferModifier) { // E.g. 1e18 - (1e17 * 10e18)/5e18 = 8e17 // (5e18 * 8e17) / 1e18 = 4e18 allocated from Vault vaultBufferModifier = 1e18 - vaultBufferModifier; } else { // We need to let the buffer fill return; } } if (vaultBufferModifier == 0) return; // Iterate over all assets in the Vault and allocate the the appropriate // strategy for (uint256 i = 0; i < allAssets.length; i++) { IERC20 asset = IERC20(allAssets[i]); uint256 assetBalance = asset.balanceOf(address(this)); // No balance, nothing to do here if (assetBalance == 0) continue; // Multiply the balance by the vault buffer modifier and truncate // to the scale of the asset decimals uint256 allocateAmount = assetBalance.mulTruncate( vaultBufferModifier ); // Get the target Strategy to maintain weightings address depositStrategyAddr = _selectDepositStrategyAddr( address(asset), allocateAmount ); if (depositStrategyAddr != address(0) && allocateAmount > 0) { IStrategy strategy = IStrategy(depositStrategyAddr); // Transfer asset to Strategy and call deposit method to // mint or take required action asset.safeTransfer(address(strategy), allocateAmount); strategy.deposit(address(asset), allocateAmount); } } // Harvest for all reward tokens above reward liquidation threshold for (uint256 i = 0; i < allStrategies.length; i++) { IStrategy strategy = IStrategy(allStrategies[i]); address rewardTokenAddress = strategy.rewardTokenAddress(); if (rewardTokenAddress != address(0)) { uint256 liquidationThreshold = strategy.rewardLiquidationThreshold(); if (liquidationThreshold == 0) { // No threshold set, always harvest from strategy IVault(address(this)).harvest(allStrategies[i]); } else { // Check balance against liquidation threshold // Note some strategies don't hold the reward token balance // on their contract so the liquidation threshold should be // set to 0 IERC20 rewardToken = IERC20(rewardTokenAddress); uint256 rewardTokenAmount = rewardToken.balanceOf( allStrategies[i] ); if (rewardTokenAmount >= liquidationThreshold) { IVault(address(this)).harvest(allStrategies[i]); } } } } } /** * @dev Calculate the total value of assets held by the Vault and all * strategies and update the supply of oUSD */ function rebase() public whenNotRebasePaused returns (uint256) { rebase(true); } /** * @dev Calculate the total value of assets held by the Vault and all * strategies and update the supply of oUSD */ function rebase(bool sync) internal whenNotRebasePaused returns (uint256) { if (oUSD.totalSupply() == 0) return 0; uint256 oldTotalSupply = oUSD.totalSupply(); uint256 newTotalSupply = _totalValue(); // Only rachet upwards if (newTotalSupply > oldTotalSupply) { oUSD.changeSupply(newTotalSupply); if (rebaseHooksAddr != address(0)) { IRebaseHooks(rebaseHooksAddr).postRebase(sync); } } } /** * @dev Determine the total value of assets held by the vault and its * strategies. * @return uint256 value Total value in USD (1e18) */ function totalValue() external view returns (uint256 value) { value = _totalValue(); } /** * @dev Internal Calculate the total value of the assets held by the * vault and its strategies. * @return uint256 value Total value in USD (1e18) */ function _totalValue() internal view returns (uint256 value) { return _totalValueInVault() + _totalValueInStrategies(); } /** * @dev Internal to calculate total value of all assets held in Vault. * @return uint256 Total value in ETH (1e18) */ function _totalValueInVault() internal view returns (uint256 value) { value = 0; for (uint256 y = 0; y < allAssets.length; y++) { IERC20 asset = IERC20(allAssets[y]); uint256 assetDecimals = Helpers.getDecimals(allAssets[y]); uint256 balance = asset.balanceOf(address(this)); if (balance > 0) { value += balance.scaleBy(int8(18 - assetDecimals)); } } } /** * @dev Internal to calculate total value of all assets held in Strategies. * @return uint256 Total value in ETH (1e18) */ function _totalValueInStrategies() internal view returns (uint256 value) { value = 0; for (uint256 i = 0; i < allStrategies.length; i++) { value += _totalValueInStrategy(allStrategies[i]); } } /** * @dev Internal to calculate total value of all assets held by strategy. * @param _strategyAddr Address of the strategy * @return uint256 Total value in ETH (1e18) */ function _totalValueInStrategy(address _strategyAddr) internal view returns (uint256 value) { value = 0; IStrategy strategy = IStrategy(_strategyAddr); for (uint256 y = 0; y < allAssets.length; y++) { uint256 assetDecimals = Helpers.getDecimals(allAssets[y]); if (strategy.supportsAsset(allAssets[y])) { uint256 balance = strategy.checkBalance(allAssets[y]); if (balance > 0) { value += balance.scaleBy(int8(18 - assetDecimals)); } } } } /** * @dev Calculate difference in percent of asset allocation for a strategy. * @param _strategyAddr Address of the strategy * @return unt256 Difference between current and target. 18 decimals. * NOTE: This is relative value! not the actual percentage */ function _strategyWeightDifference( address _strategyAddr, address _asset, uint256 _modAmount, bool deposit ) internal view returns (uint256 difference) { // Since we are comparing relative weights, we should scale by weight so // that even small weights will be triggered, ie 1% versus 20% uint256 weight = strategies[_strategyAddr].targetWeight; if (weight == 0) return 0; uint256 assetDecimals = Helpers.getDecimals(_asset); difference = MAX_UINT - ( deposit ? _totalValueInStrategy(_strategyAddr).add( _modAmount.scaleBy(int8(18 - assetDecimals)) ) : _totalValueInStrategy(_strategyAddr).sub( _modAmount.scaleBy(int8(18 - assetDecimals)) ) ) .divPrecisely(weight); } /** * @dev Select a strategy for allocating an asset to. * @param _asset Address of asset * @return address Address of the target strategy */ function _selectDepositStrategyAddr(address _asset, uint256 depositAmount) internal view returns (address depositStrategyAddr) { depositStrategyAddr = address(0); uint256 maxDifference = 0; for (uint256 i = 0; i < allStrategies.length; i++) { IStrategy strategy = IStrategy(allStrategies[i]); if (strategy.supportsAsset(_asset)) { uint256 diff = _strategyWeightDifference( allStrategies[i], _asset, depositAmount, true ); if (diff >= maxDifference) { maxDifference = diff; depositStrategyAddr = allStrategies[i]; } } } } /** * @dev Select a strategy for withdrawing an asset from. * @param _asset Address of asset * @return address Address of the target strategy for withdrawal */ function _selectWithdrawStrategyAddr(address _asset, uint256 _amount) internal view returns (address withdrawStrategyAddr) { withdrawStrategyAddr = address(0); uint256 minDifference = MAX_UINT; for (uint256 i = 0; i < allStrategies.length; i++) { IStrategy strategy = IStrategy(allStrategies[i]); if ( strategy.supportsAsset(_asset) && strategy.checkBalance(_asset) > _amount ) { uint256 diff = _strategyWeightDifference( allStrategies[i], _asset, _amount, false ); if (diff <= minDifference) { minDifference = diff; withdrawStrategyAddr = allStrategies[i]; } } } } /** * @notice Get the balance of an asset held in Vault and all strategies. * @param _asset Address of asset * @return uint256 Balance of asset in decimals of asset */ function checkBalance(address _asset) external view returns (uint256) { return _checkBalance(_asset); } /** * @notice Get the balance of an asset held in Vault and all strategies. * @param _asset Address of asset * @return uint256 Balance of asset in decimals of asset */ function _checkBalance(address _asset) internal view returns (uint256 balance) { IERC20 asset = IERC20(_asset); balance = asset.balanceOf(address(this)); for (uint256 i = 0; i < allStrategies.length; i++) { IStrategy strategy = IStrategy(allStrategies[i]); if (strategy.supportsAsset(_asset)) { balance += strategy.checkBalance(_asset); } } } /** * @notice Get the balance of all assets held in Vault and all strategies. * @return uint256 Balance of all assets (1e18) */ function _checkBalance() internal view returns (uint256 balance) { balance = 0; for (uint256 i = 0; i < allAssets.length; i++) { uint256 assetDecimals = Helpers.getDecimals(allAssets[i]); balance += _checkBalance(allAssets[i]).scaleBy( int8(18 - assetDecimals) ); } } /** * @notice Calculate the outputs for a redeem function, i.e. the mix of * coins that will be returned */ function calculateRedeemOutputs(uint256 _amount) external returns (uint256[] memory) { return _calculateRedeemOutputs(_amount); } /** * @notice Calculate the outputs for a redeem function, i.e. the mix of * coins that will be returned. * @return Array of amounts respective to the supported assets */ function _calculateRedeemOutputs(uint256 _amount) internal returns (uint256[] memory outputs) { // We always give out coins in proportion to how many we have, // Now if all coins were the same value, this math would easy, // just take the percentage of each coin, and multiply by the // value to be given out. But if coins are worth more than $1, // then we would end up handing out too many coins. We need to // adjust by the total value of coins. // // To do this, we total up the value of our coins, by their // percentages. Then divide what we would otherwise give out by // this number. // // Let say we have 100 DAI at $1.06 and 200 USDT at $1.00. // So for every 1 DAI we give out, we'll be handing out 2 USDT // Our total output ratio is: 33% * 1.06 + 66% * 1.00 = 1.02 // // So when calculating the output, we take the percentage of // each coin, times the desired output value, divided by the // totalOutputRatio. // // For example, withdrawing: 30 OUSD: // DAI 33% * 30 / 1.02 = 9.80 DAI // USDT = 66 % * 30 / 1.02 = 19.60 USDT // // Checking these numbers: // 9.80 DAI * 1.06 = $10.40 // 19.60 USDT * 1.00 = $19.60 // // And so the user gets $10.40 + $19.60 = $30 worth of value. uint256 assetCount = getAssetCount(); uint256[] memory assetPrices = _getAssetPrices(true); uint256[] memory assetBalances = new uint256[](assetCount); uint256[] memory assetDecimals = new uint256[](assetCount); uint256 totalBalance = 0; uint256 totalOutputRatio = 0; outputs = new uint256[](assetCount); // Calculate redeem fee if (redeemFeeBps > 0) { uint256 redeemFee = _amount.mul(redeemFeeBps).div(10000); _amount = _amount.sub(redeemFee); } // Calculate assets balances and decimals once, // for a large gas savings. for (uint256 i = 0; i < allAssets.length; i++) { uint256 balance = _checkBalance(allAssets[i]); uint256 decimals = Helpers.getDecimals(allAssets[i]); assetBalances[i] = balance; assetDecimals[i] = decimals; totalBalance += balance.scaleBy(int8(18 - decimals)); } // Calculate totalOutputRatio for (uint256 i = 0; i < allAssets.length; i++) { uint256 price = assetPrices[i]; // Never give out more than one // stablecoin per dollar of OUSD if (price < 1e18) { price = 1e18; } uint256 ratio = assetBalances[i] .scaleBy(int8(18 - assetDecimals[i])) .mul(price) .div(totalBalance); totalOutputRatio += ratio; } // Calculate final outputs uint256 factor = _amount.divPrecisely(totalOutputRatio); for (uint256 i = 0; i < allAssets.length; i++) { outputs[i] = assetBalances[i].mul(factor).div(totalBalance); } } /** * @notice Get an array of the supported asset prices in USD. * @return uint256[] Array of asset prices in USD (1e18) */ function _getAssetPrices(bool useMax) internal returns (uint256[] memory assetPrices) { assetPrices = new uint256[](getAssetCount()); IMinMaxOracle oracle = IMinMaxOracle(priceProvider); // Price from Oracle is returned with 8 decimals // _amount is in assetDecimals for (uint256 i = 0; i < allAssets.length; i++) { string memory symbol = Helpers.getSymbol(allAssets[i]); // Get all the USD prices of the asset in 1e18 if (useMax) { assetPrices[i] = oracle.priceMax(symbol).scaleBy(int8(18 - 8)); } else { assetPrices[i] = oracle.priceMin(symbol).scaleBy(int8(18 - 8)); } } } /*************************************** Utils ****************************************/ /** * @dev Return the number of assets suppported by the Vault. */ function getAssetCount() public view returns (uint256) { return allAssets.length; } /** * @dev Return all asset addresses in order */ function getAllAssets() external view returns (address[] memory) { return allAssets; } /** * @dev Return the number of strategies active on the Vault. */ function getStrategyCount() public view returns (uint256) { return allStrategies.length; } function isSupportedAsset(address _asset) external view returns (bool) { return assets[_asset].isSupported; } /** * @dev Falldown to the admin implementation * @notice This is a catch all for all functions not declared in core */ function() external payable { bytes32 slot = adminImplPosition; 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, sload(slot), 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 Internal to calculate total value of all assets held in Strategies. @return uint256 Total value in ETH (1e18)/
function _totalValueInStrategies() internal view returns (uint256 value) { value = 0; for (uint256 i = 0; i < allStrategies.length; i++) { value += _totalValueInStrategy(allStrategies[i]); } }
610,565
[ 1, 3061, 358, 4604, 2078, 460, 434, 777, 7176, 15770, 316, 3978, 15127, 18, 327, 2254, 5034, 10710, 460, 316, 512, 2455, 261, 21, 73, 2643, 13176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 4963, 620, 382, 1585, 15127, 1435, 2713, 1476, 1135, 261, 11890, 5034, 460, 13, 288, 203, 3639, 460, 273, 374, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 777, 1585, 15127, 18, 2469, 31, 277, 27245, 288, 203, 5411, 460, 1011, 389, 4963, 620, 382, 4525, 12, 454, 1585, 15127, 63, 77, 19226, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "../utils/MinterGuard.sol"; import "../interfaces/IDG4610.sol"; import "../interfaces/IDG721BatchReceiver.sol"; import "./ERC4610.sol"; /** * @dev An DG4610Simple token for Godland. * Besides the burn and mint function, we make a customisation that implement a 'batch' * token transfer function in consideration of reducing gas costing in game. * The batch function is mainly refrence IERC1155.safeBatchTransferFrom, and also do the * acceptance checks at the end of the transfer. */ contract DG4610Simple is MinterGuard, ERC4610, IDG4610 { using Strings for uint256; using Address for address; uint256 public tokenIdCounter; string private _uri; /** * @dev Constructor. * @param name_ The name of contract. * @param symbol_ The symbol of contract. */ constructor(string memory name_, string memory symbol_) ERC4610(name_, symbol_) {} function setUri(string calldata uri) external onlyOwner { _uri = uri; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return string(abi.encodePacked(_uri, tokenId.toString(), ".json")); } /** * @dev A batch version of transfer tokens to another account, also whill check acceptance at the end of the transfer * @param from The account will send the token. * @param to The token reciver. * @param ids The token ids that will be sent. * @param data The additional data for transfer handler. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, bytes memory data ) external override { for (uint256 index = 0; index < ids.length; ++index) transferFrom(from, to, ids[index]); _checkOnERC721BatchReceived(from, to, ids, data); } /** * @dev A batch version of transfer tokens to another account, also whill check acceptance at the end of the transfer * @param from The account will send the token. * @param to The token reciver. * @param ids The token ids that will be sent. * @param data The additional data for transfer handler. * @param reserved To clear the reservation or not */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, bytes memory data, bool reserved ) external override { for (uint256 index = 0; index < ids.length; ++index) { uint256 tokenId = ids[index]; address delegator = delegatorOf(tokenId); transferFrom(from, to, tokenId); if (reserved) _setDelegator(delegator, tokenId); } _checkOnERC721BatchReceived(from, to, ids, data); } /** * @dev Mint funtion, only minter role can be callthis function * @param account The account will recive the token. */ function mint(address account) external override onlyMinter returns (uint256 tokenIdStart) { return _mint(account); } function _mint(address account) internal returns (uint256 tokenIdStart) { tokenIdStart = tokenIdCounter; _safeMint(account, tokenIdStart); tokenIdCounter = tokenIdStart + 1; } /** * @dev A batch version of mint funtion * @param account The account will recive the token. * @param amount The count of token that will be minted. */ function mintBatch(address account, uint256 amount) external override onlyMinter returns (uint256 tokenIdStart) { return _mintBatch(account, amount); } function _mintBatch(address account, uint256 amount) internal returns (uint256 tokenIdStart) { tokenIdStart = tokenIdCounter; for (uint256 offset = 0; offset < amount; ++offset) _safeMint(account, tokenIdStart + offset); tokenIdCounter = tokenIdStart + amount; } /** * @dev Burns `tokenId`. See {ERC721-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) external override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } /** * @dev Batch version of burn function */ function burnBatch(uint256[] calldata tokenIds) external override { for (uint256 index = 0; index < tokenIds.length; ++index) { require(_isApprovedOrOwner(_msgSender(), tokenIds[index]), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenIds[index]); } } /** * @dev Burns `tokenId` form a specified account. See {ERC721-_burn}. * This function will ensure it burn token from a specified account. */ function burnFrom(address account, uint256 tokenId) external override { require(ERC4610.ownerOf(tokenId) == account, "not token owner"); require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenId); } /** * @dev Batch version of burnFrom function */ function burnFromBatch(address account, uint256[] calldata tokenIds) external override { for (uint256 index = 0; index < tokenIds.length; ++index) { require(ERC4610.ownerOf(tokenIds[index]) == account, "not token owner"); require(_isApprovedOrOwner(_msgSender(), tokenIds[index]), "ERC721Burnable: caller is not owner nor approved"); _burn(tokenIds[index]); } } /** * @dev make a batch received check */ function _checkOnERC721BatchReceived( address from, address to, uint256[] memory tokenIds, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IDG721BatchReceiver(to).onERC721BatchReceived(msg.sender, from, tokenIds, _data) returns (bytes4 retval) { return retval == IDG721BatchReceiver(to).onERC721BatchReceived.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 See {IERC721Metadata-tokenURI}./
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return string(abi.encodePacked(_uri, tokenId.toString(), ".json")); }
12,968,111
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 2277, 17, 2316, 3098, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1147, 3098, 12, 11890, 5034, 1147, 548, 13, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 2583, 24899, 1808, 12, 2316, 548, 3631, 315, 654, 39, 27, 5340, 2277, 30, 3699, 843, 364, 1661, 19041, 1147, 8863, 203, 3639, 327, 533, 12, 21457, 18, 3015, 4420, 329, 24899, 1650, 16, 1147, 548, 18, 10492, 9334, 3552, 1977, 7923, 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 ]
./partial_match/3/0xE5dD5466314a590680d107B2Dea8114cd694BBfd/sources/Strategy.sol
* Resolve governance address from Vault contract, used to make assertions on protected functions in the Strategy./
function governance() internal view returns (address) { return vault.governance(); }
5,277,470
[ 1, 8460, 314, 1643, 82, 1359, 1758, 628, 17329, 6835, 16, 1399, 358, 1221, 7820, 603, 4750, 4186, 316, 326, 19736, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 915, 314, 1643, 82, 1359, 1435, 2713, 1476, 1135, 261, 2867, 13, 288, 203, 565, 327, 9229, 18, 75, 1643, 82, 1359, 5621, 203, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @airswap/types/contracts/Types.sol /* Copyright 2019 Swap Holdings Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.10; pragma experimental ABIEncoderV2; /** * @title Types: Library of Swap Protocol Types and Hashes */ library Types { bytes constant internal EIP191_HEADER = "\x19\x01"; struct Order { uint256 nonce; // Unique per order and should be sequential uint256 expiry; // Expiry in seconds since 1 January 1970 Party maker; // Party to the trade that sets terms Party taker; // Party to the trade that accepts terms Party affiliate; // Party compensated for facilitating (optional) Signature signature; // Signature of the order } struct Party { address wallet; // Wallet address of the party address token; // Contract address of the token uint256 param; // Value (ERC-20) or ID (ERC-721) bytes4 kind; // Interface ID of the token } struct Signature { address signer; // Address of the wallet used to sign uint8 v; // `v` value of an ECDSA signature bytes32 r; // `r` value of an ECDSA signature bytes32 s; // `s` value of an ECDSA signature bytes1 version; // EIP-191 signature version } bytes32 constant DOMAIN_TYPEHASH = keccak256(abi.encodePacked( "EIP712Domain(", "string name,", "string version,", "address verifyingContract", ")" )); bytes32 constant ORDER_TYPEHASH = keccak256(abi.encodePacked( "Order(", "uint256 nonce,", "uint256 expiry,", "Party maker,", "Party taker,", "Party affiliate", ")", "Party(", "address wallet,", "address token,", "uint256 param,", "bytes4 kind", ")" )); bytes32 constant PARTY_TYPEHASH = keccak256(abi.encodePacked( "Party(", "address wallet,", "address token,", "uint256 param,", "bytes4 kind", ")" )); /** * @notice Hash an order into bytes32 * @dev EIP-191 header and domain separator included * @param _order Order * @param _domainSeparator bytes32 * @return bytes32 returns a keccak256 abi.encodePacked value */ function hashOrder( Order calldata _order, bytes32 _domainSeparator ) external pure returns (bytes32) { return keccak256(abi.encodePacked( EIP191_HEADER, _domainSeparator, keccak256(abi.encode( ORDER_TYPEHASH, _order.nonce, _order.expiry, keccak256(abi.encode( PARTY_TYPEHASH, _order.maker.wallet, _order.maker.token, _order.maker.param, _order.maker.kind )), keccak256(abi.encode( PARTY_TYPEHASH, _order.taker.wallet, _order.taker.token, _order.taker.param, _order.taker.kind )), keccak256(abi.encode( PARTY_TYPEHASH, _order.affiliate.wallet, _order.affiliate.token, _order.affiliate.param, _order.affiliate.kind )) )) )); } /** * @notice Hash domain parameters into bytes32 * @dev Used for signature validation (EIP-712) * @param _name bytes * @param _version bytes * @param _verifyingContract address * @return bytes32 returns a keccak256 abi.encodePacked value */ function hashDomain( bytes calldata _name, bytes calldata _version, address _verifyingContract ) external pure returns (bytes32) { return keccak256(abi.encode( DOMAIN_TYPEHASH, keccak256(_name), keccak256(_version), _verifyingContract )); } } // File: @airswap/swap/contracts/interfaces/ISwap.sol interface ISwap { event Swap( uint256 indexed nonce, uint256 timestamp, address indexed makerWallet, uint256 makerParam, address makerToken, address indexed takerWallet, uint256 takerParam, address takerToken, address affiliateWallet, uint256 affiliateParam, address affiliateToken ); event Cancel( uint256 indexed nonce, address indexed makerWallet ); event Invalidate( uint256 indexed nonce, address indexed makerWallet ); event Authorize( address indexed approverAddress, address indexed delegateAddress, uint256 expiry ); event Revoke( address indexed approverAddress, address indexed delegateAddress ); function delegateApprovals(address, address) external returns (uint256); function makerOrderStatus(address, uint256) external returns (byte); function makerMinimumNonce(address) external returns (uint256); /** * @notice Atomic Token Swap * @param order Types.Order */ function swap( Types.Order calldata order ) external; /** * @notice Cancel one or more open orders by nonce * @param _nonces uint256[] */ function cancel( uint256[] calldata _nonces ) external; /** * @notice Invalidate all orders below a nonce value * @param _minimumNonce uint256 */ function invalidate( uint256 _minimumNonce ) external; /** * @notice Authorize a delegate * @param _delegate address * @param _expiry uint256 */ function authorize( address _delegate, uint256 _expiry ) external; /** * @notice Revoke an authorization * @param _delegate address */ function revoke( address _delegate ) external; } // File: @airswap/tokens/contracts/interfaces/IWETH.sol interface IWETH { function deposit() external payable; function withdraw(uint256) external; 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); } // File: openzeppelin-solidity/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. * * > 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/Wrapper.sol /** * @title Wrapper: Send and receive ether for WETH trades */ contract Wrapper { // Swap contract to settle trades ISwap public swapContract; // WETH contract to wrap ether IWETH public wethContract; uint256 constant MAX_INT = 2**256 - 1; /** * @notice Contract Constructor * @param _swapContract address * @param _wethContract address */ constructor( address _swapContract, address _wethContract ) public { swapContract = ISwap(_swapContract); wethContract = IWETH(_wethContract); // Sets unlimited allowance for the Wrapper contract. wethContract.approve(_swapContract, MAX_INT); } /** * @notice Required when withdrawing from WETH * @dev During unwraps, WETH.withdraw transfers ether to msg.sender (this contract) */ function() external payable { // Ensure the message sender is the WETH contract. if(msg.sender != address(wethContract)) { revert("DO_NOT_SEND_ETHER"); } } /** * @notice Send an Order * @dev Taker must authorize this contract on the swapContract * @dev Taker must approve this contract on the wethContract * @param _order Types.Order */ function swap( Types.Order calldata _order ) external payable { // Ensure message sender is taker wallet. require(_order.taker.wallet == msg.sender, "SENDER_MUST_BE_TAKER"); // The taker is sending ether that must be wrapped. if (_order.taker.token == address(wethContract)) { // Ensure message value is taker param. require(_order.taker.param == msg.value, "VALUE_MUST_BE_SENT"); // Wrap (deposit) the ether. wethContract.deposit.value(msg.value)(); // Transfer from wrapper to taker. wethContract.transfer(_order.taker.wallet, _order.taker.param); } else { // Ensure no unexpected ether is sent. require(msg.value == 0, "VALUE_MUST_BE_ZERO"); } // Perform the swap. swapContract.swap(_order); // The taker is receiving ether that must be unwrapped. if (_order.maker.token == address(wethContract)) { // Transfer from the taker to the wrapper. wethContract.transferFrom(_order.taker.wallet, address(this), _order.maker.param); // Unwrap (withdraw) the ether. wethContract.withdraw(_order.maker.param); // Transfer ether to the user. msg.sender.transfer(_order.maker.param); } } }
* @title Wrapper: Send and receive ether for WETH trades/ Swap contract to settle trades WETH contract to wrap ether
contract Wrapper { ISwap public swapContract; IWETH public wethContract; uint256 constant MAX_INT = 2**256 - 1; constructor( address _swapContract, address _wethContract } ) public { swapContract = ISwap(_swapContract); wethContract = IWETH(_wethContract); wethContract.approve(_swapContract, MAX_INT); } function() external payable { if(msg.sender != address(wethContract)) { revert("DO_NOT_SEND_ETHER"); } } function() external payable { if(msg.sender != address(wethContract)) { revert("DO_NOT_SEND_ETHER"); } } function swap( Types.Order calldata _order ) external payable { require(_order.taker.wallet == msg.sender, "SENDER_MUST_BE_TAKER"); if (_order.taker.token == address(wethContract)) { require(_order.taker.param == msg.value, "VALUE_MUST_BE_SENT"); wethContract.deposit.value(msg.value)(); wethContract.transfer(_order.taker.wallet, _order.taker.param); require(msg.value == 0, "VALUE_MUST_BE_ZERO"); } if (_order.maker.token == address(wethContract)) { wethContract.transferFrom(_order.taker.wallet, address(this), _order.maker.param); wethContract.withdraw(_order.maker.param); msg.sender.transfer(_order.maker.param); } } function swap( Types.Order calldata _order ) external payable { require(_order.taker.wallet == msg.sender, "SENDER_MUST_BE_TAKER"); if (_order.taker.token == address(wethContract)) { require(_order.taker.param == msg.value, "VALUE_MUST_BE_SENT"); wethContract.deposit.value(msg.value)(); wethContract.transfer(_order.taker.wallet, _order.taker.param); require(msg.value == 0, "VALUE_MUST_BE_ZERO"); } if (_order.maker.token == address(wethContract)) { wethContract.transferFrom(_order.taker.wallet, address(this), _order.maker.param); wethContract.withdraw(_order.maker.param); msg.sender.transfer(_order.maker.param); } } } else { swapContract.swap(_order); function swap( Types.Order calldata _order ) external payable { require(_order.taker.wallet == msg.sender, "SENDER_MUST_BE_TAKER"); if (_order.taker.token == address(wethContract)) { require(_order.taker.param == msg.value, "VALUE_MUST_BE_SENT"); wethContract.deposit.value(msg.value)(); wethContract.transfer(_order.taker.wallet, _order.taker.param); require(msg.value == 0, "VALUE_MUST_BE_ZERO"); } if (_order.maker.token == address(wethContract)) { wethContract.transferFrom(_order.taker.wallet, address(this), _order.maker.param); wethContract.withdraw(_order.maker.param); msg.sender.transfer(_order.maker.param); } } }
1,778,084
[ 1, 3611, 30, 2479, 471, 6798, 225, 2437, 364, 678, 1584, 44, 1284, 5489, 19, 12738, 6835, 358, 444, 5929, 1284, 5489, 678, 1584, 44, 6835, 358, 2193, 225, 2437, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 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, 16351, 18735, 288, 203, 203, 225, 4437, 91, 438, 1071, 7720, 8924, 31, 203, 203, 225, 467, 59, 1584, 44, 1071, 341, 546, 8924, 31, 203, 203, 225, 2254, 5034, 5381, 4552, 67, 3217, 273, 576, 636, 5034, 300, 404, 31, 203, 225, 3885, 12, 203, 565, 1758, 389, 22270, 8924, 16, 203, 565, 1758, 389, 91, 546, 8924, 203, 97, 203, 203, 225, 262, 1071, 288, 203, 565, 7720, 8924, 273, 4437, 91, 438, 24899, 22270, 8924, 1769, 203, 565, 341, 546, 8924, 273, 467, 59, 1584, 44, 24899, 91, 546, 8924, 1769, 203, 203, 565, 341, 546, 8924, 18, 12908, 537, 24899, 22270, 8924, 16, 4552, 67, 3217, 1769, 203, 225, 289, 203, 203, 225, 445, 1435, 3903, 8843, 429, 288, 203, 565, 309, 12, 3576, 18, 15330, 480, 1758, 12, 91, 546, 8924, 3719, 288, 203, 1377, 15226, 2932, 3191, 67, 4400, 67, 21675, 67, 1584, 3891, 8863, 203, 565, 289, 203, 225, 289, 203, 203, 225, 445, 1435, 3903, 8843, 429, 288, 203, 565, 309, 12, 3576, 18, 15330, 480, 1758, 12, 91, 546, 8924, 3719, 288, 203, 1377, 15226, 2932, 3191, 67, 4400, 67, 21675, 67, 1584, 3891, 8863, 203, 565, 289, 203, 225, 289, 203, 203, 225, 445, 7720, 12, 203, 565, 7658, 18, 2448, 745, 892, 389, 1019, 203, 225, 262, 3903, 8843, 429, 288, 203, 203, 565, 2583, 24899, 1019, 18, 88, 6388, 18, 19177, 422, 1234, 18, 15330, 16, 203, 1377, 315, 1090, 18556, 67, 49, 5996, 67, 5948, 67, 9833, 27221, 8863, 203, 203, 2 ]
./full_match/43114/0xCb31480736947d8fDa34184271Fe909566cCeC5C/sources/contracts/dcphr.sol
change price per unit
uint256 public cost = .35 ether;
4,558,188
[ 1, 3427, 6205, 1534, 2836, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2254, 5034, 1071, 6991, 273, 263, 4763, 225, 2437, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-01-18 */ pragma solidity 0.6.12; // SPDX-License-Identifier: GPL-3.0-only /** * @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; } } interface IStafiStorage { // 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; } abstract contract StafiBase { // Version of the contract uint8 public version; // The main storage contract where primary persistant storage is maintained IStafiStorage stafiStorage = IStafiStorage(0); /** * @dev Throws if called by any sender that doesn't match a 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 trusted node */ modifier onlyTrustedNode(address _nodeAddress) { require(getBool(keccak256(abi.encodePacked("node.trusted", _nodeAddress))), "Invalid trusted node"); _; } /** * @dev Throws if called by any sender that isn't a registered staking pool */ modifier onlyRegisteredStakingPool(address _stakingPoolAddress) { require(getBool(keccak256(abi.encodePacked("stakingpool.exists", _stakingPoolAddress))), "Invalid staking pool"); _; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(roleHas("owner", msg.sender), "Account is not the owner"); _; } /** * @dev Modifier to scope access to admins */ modifier onlyAdmin() { require(roleHas("admin", msg.sender), "Account is not an admin"); _; } /** * @dev Modifier to scope access to admins */ modifier onlySuperUser() { require(roleHas("owner", msg.sender) || roleHas("admin", msg.sender), "Account is not a super user"); _; } /** * @dev Reverts if the address doesn't have this role */ modifier onlyRole(string memory _role) { require(roleHas(_role, msg.sender), "Account does not match the specified role"); _; } /// @dev Set the main Storage address constructor(address _stafiStorageAddress) public { // Update the contract address stafiStorage = IStafiStorage(_stafiStorageAddress); } /// @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 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(keccak256(abi.encodePacked(contractName)) != keccak256(abi.encodePacked("")), "Contract not found"); // Return return contractName; } /// @dev Storage get methods function getAddress(bytes32 _key) internal view returns (address) { return stafiStorage.getAddress(_key); } function getUint(bytes32 _key) internal view returns (uint256) { return stafiStorage.getUint(_key); } function getString(bytes32 _key) internal view returns (string memory) { return stafiStorage.getString(_key); } function getBytes(bytes32 _key) internal view returns (bytes memory) { return stafiStorage.getBytes(_key); } function getBool(bytes32 _key) internal view returns (bool) { return stafiStorage.getBool(_key); } function getInt(bytes32 _key) internal view returns (int256) { return stafiStorage.getInt(_key); } function getBytes32(bytes32 _key) internal view returns (bytes32) { return stafiStorage.getBytes32(_key); } function getAddressS(string memory _key) internal view returns (address) { return stafiStorage.getAddress(keccak256(abi.encodePacked(_key))); } function getUintS(string memory _key) internal view returns (uint256) { return stafiStorage.getUint(keccak256(abi.encodePacked(_key))); } function getStringS(string memory _key) internal view returns (string memory) { return stafiStorage.getString(keccak256(abi.encodePacked(_key))); } function getBytesS(string memory _key) internal view returns (bytes memory) { return stafiStorage.getBytes(keccak256(abi.encodePacked(_key))); } function getBoolS(string memory _key) internal view returns (bool) { return stafiStorage.getBool(keccak256(abi.encodePacked(_key))); } function getIntS(string memory _key) internal view returns (int256) { return stafiStorage.getInt(keccak256(abi.encodePacked(_key))); } function getBytes32S(string memory _key) internal view returns (bytes32) { return stafiStorage.getBytes32(keccak256(abi.encodePacked(_key))); } /// @dev Storage set methods function setAddress(bytes32 _key, address _value) internal { stafiStorage.setAddress(_key, _value); } function setUint(bytes32 _key, uint256 _value) internal { stafiStorage.setUint(_key, _value); } function setString(bytes32 _key, string memory _value) internal { stafiStorage.setString(_key, _value); } function setBytes(bytes32 _key, bytes memory _value) internal { stafiStorage.setBytes(_key, _value); } function setBool(bytes32 _key, bool _value) internal { stafiStorage.setBool(_key, _value); } function setInt(bytes32 _key, int256 _value) internal { stafiStorage.setInt(_key, _value); } function setBytes32(bytes32 _key, bytes32 _value) internal { stafiStorage.setBytes32(_key, _value); } function setAddressS(string memory _key, address _value) internal { stafiStorage.setAddress(keccak256(abi.encodePacked(_key)), _value); } function setUintS(string memory _key, uint256 _value) internal { stafiStorage.setUint(keccak256(abi.encodePacked(_key)), _value); } function setStringS(string memory _key, string memory _value) internal { stafiStorage.setString(keccak256(abi.encodePacked(_key)), _value); } function setBytesS(string memory _key, bytes memory _value) internal { stafiStorage.setBytes(keccak256(abi.encodePacked(_key)), _value); } function setBoolS(string memory _key, bool _value) internal { stafiStorage.setBool(keccak256(abi.encodePacked(_key)), _value); } function setIntS(string memory _key, int256 _value) internal { stafiStorage.setInt(keccak256(abi.encodePacked(_key)), _value); } function setBytes32S(string memory _key, bytes32 _value) internal { stafiStorage.setBytes32(keccak256(abi.encodePacked(_key)), _value); } /// @dev Storage delete methods function deleteAddress(bytes32 _key) internal { stafiStorage.deleteAddress(_key); } function deleteUint(bytes32 _key) internal { stafiStorage.deleteUint(_key); } function deleteString(bytes32 _key) internal { stafiStorage.deleteString(_key); } function deleteBytes(bytes32 _key) internal { stafiStorage.deleteBytes(_key); } function deleteBool(bytes32 _key) internal { stafiStorage.deleteBool(_key); } function deleteInt(bytes32 _key) internal { stafiStorage.deleteInt(_key); } function deleteBytes32(bytes32 _key) internal { stafiStorage.deleteBytes32(_key); } function deleteAddressS(string memory _key) internal { stafiStorage.deleteAddress(keccak256(abi.encodePacked(_key))); } function deleteUintS(string memory _key) internal { stafiStorage.deleteUint(keccak256(abi.encodePacked(_key))); } function deleteStringS(string memory _key) internal { stafiStorage.deleteString(keccak256(abi.encodePacked(_key))); } function deleteBytesS(string memory _key) internal { stafiStorage.deleteBytes(keccak256(abi.encodePacked(_key))); } function deleteBoolS(string memory _key) internal { stafiStorage.deleteBool(keccak256(abi.encodePacked(_key))); } function deleteIntS(string memory _key) internal { stafiStorage.deleteInt(keccak256(abi.encodePacked(_key))); } function deleteBytes32S(string memory _key) internal { stafiStorage.deleteBytes32(keccak256(abi.encodePacked(_key))); } /** * @dev Check if an address has this role */ function roleHas(string memory _role, address _address) internal view returns (bool) { return getBool(keccak256(abi.encodePacked("access.role", _role, _address))); } } interface IStafiEther { function balanceOf(address _contractAddress) external view returns (uint256); function depositEther() external payable; function withdrawEther(uint256 _amount) external; } interface IStafiEtherWithdrawer { function receiveEtherWithdrawal() external payable; } // ETH are stored here to prevent contract upgrades from affecting balances // The contract must not be upgraded contract StafiEther is StafiBase, IStafiEther { // Libs using SafeMath for uint256; // Contract balances mapping(bytes32 => uint256) balances; // Events event EtherDeposited(bytes32 indexed by, uint256 amount, uint256 time); event EtherWithdrawn(bytes32 indexed by, uint256 amount, uint256 time); // Construct constructor(address _stafiStorageAddress) StafiBase(_stafiStorageAddress) public { version = 1; } // Get a contract's ETH balance by address function balanceOf(address _contractAddress) override public view returns (uint256) { return balances[keccak256(abi.encodePacked(getContractName(_contractAddress)))]; } // Accept an ETH deposit from a network contract function depositEther() override external payable onlyLatestNetworkContract { // Get contract key bytes32 contractKey = keccak256(abi.encodePacked(getContractName(msg.sender))); // Update contract balance balances[contractKey] = balances[contractKey].add(msg.value); // Emit ether deposited event emit EtherDeposited(contractKey, msg.value, now); } // Withdraw an amount of ETH to a network contract function withdrawEther(uint256 _amount) override external onlyLatestNetworkContract { // Get contract key bytes32 contractKey = keccak256(abi.encodePacked(getContractName(msg.sender))); // Check and update contract balance require(balances[contractKey] >= _amount, "Insufficient contract ETH balance"); balances[contractKey] = balances[contractKey].sub(_amount); // Withdraw IStafiEtherWithdrawer withdrawer = IStafiEtherWithdrawer(msg.sender); withdrawer.receiveEtherWithdrawal{value: _amount}(); // Emit ether withdrawn event emit EtherWithdrawn(contractKey, _amount, now); } }
Accept an ETH deposit from a network contract Get contract key Update contract balance Emit ether deposited event
function depositEther() override external payable onlyLatestNetworkContract { bytes32 contractKey = keccak256(abi.encodePacked(getContractName(msg.sender))); balances[contractKey] = balances[contractKey].add(msg.value); emit EtherDeposited(contractKey, msg.value, now); }
2,006,604
[ 1, 5933, 392, 512, 2455, 443, 1724, 628, 279, 2483, 6835, 968, 6835, 498, 2315, 6835, 11013, 16008, 225, 2437, 443, 1724, 329, 871, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 443, 1724, 41, 1136, 1435, 3849, 3903, 8843, 429, 1338, 18650, 3906, 8924, 288, 203, 3639, 1731, 1578, 6835, 653, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 588, 8924, 461, 12, 3576, 18, 15330, 3719, 1769, 203, 3639, 324, 26488, 63, 16351, 653, 65, 273, 324, 26488, 63, 16351, 653, 8009, 1289, 12, 3576, 18, 1132, 1769, 203, 3639, 3626, 512, 1136, 758, 1724, 329, 12, 16351, 653, 16, 1234, 18, 1132, 16, 2037, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-03-19 */ // SPDX-License-Identifier: MIT pragma solidity >=0.8.2; // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.0/contracts/utils/math/SafeMath.sol // CAUTION - only use with Solidity 0.8 + /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * 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; } } } // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.0/contracts/token/ERC20/IERC20.sol /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.0/contracts/utils/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.0/contracts/access/Ownable.sol /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.0/contracts/token/ERC20/ERC20.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 { 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 defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @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 this function is * overloaded; * * 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 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"); _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"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal 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"); _balances[sender] = senderBalance - amount; _balances[recipient] += 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 += amount; _balances[account] += 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); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= 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 { } } /** * @title DEXStream.io Token * @author JP * @dev Implementation of the DEXStream.io Token */ contract DEXStreamToken is ERC20, Ownable { uint256 private _cSBlock; // Claim startblock uint256 private _cEBlock; // Claim endblock uint256 private _cAmount; // Claim amount uint256 private _cCap; // Claim count cap (<1000) uint256 private _cCount; // Current claim count uint256 private _sSBlock; // Sale startblock uint256 private _sEBlock; // Sale endblock uint256 private _sTokensPerEth; // amount of tokers to get per eth uint256 private _sCap; // Sale count cap uint256 private _sCount; // Current sale count /** * @param name Name of the token * @param symbol A symbol to be used as ticker * @param initialSupply Initial token supply */ constructor( string memory name, string memory symbol, uint256 initialSupply ) ERC20(name, symbol) { if (initialSupply > 0) { _mint(owner(), initialSupply); } } function cSBlock() public view virtual returns (uint256) { return _cSBlock; } function cEBlock() public view virtual returns (uint256) { return _cEBlock; } function cAmount()public view virtual returns (uint256) { return _cAmount; } function cCap() public view virtual returns (uint256) { return _cCap; } function cCount() public view virtual returns (uint256) { return _cCount; } function startClaimPeriod(uint256 startBlock, uint256 endBlock, uint256 amount,uint256 cap) public onlyOwner() { _cSBlock = startBlock; _cEBlock = endBlock; _cAmount = amount; _cCap = cap; _cCount = 0; } function claim(address refer) public returns (bool success){ require(_cSBlock <= block.number && block.number <= _cEBlock, "Claim period not active"); require(_cCount < _cCap || _cCap == 0, "All is claimed"); _cCount ++; if(msg.sender != refer && balanceOf(refer) != 0 && refer != 0x0000000000000000000000000000000000000000){ _transfer(address(this), refer, _cAmount); } _transfer(address(this), msg.sender, _cAmount); return true; } function viewClaimPeriod() public view returns(uint256 startBlock, uint256 endBlock, uint256 amount, uint256 cap, uint256 count){ return(_cSBlock, _cEBlock, _cAmount, _cCap, _cCount); } function sSBlock() public view virtual returns (uint256) { return _sSBlock; } function sEBlock() public view virtual returns (uint256) { return _sEBlock; } function sTokensPerEth()public view virtual returns (uint256) { return _sTokensPerEth; } function sCap() public view virtual returns (uint256) { return _sCap; } function sCount() public view virtual returns (uint256) { return _sCount; } function startSale(uint256 startBlock, uint256 endBlock, uint256 tokensPerEth,uint256 cap) public onlyOwner() { _sSBlock = startBlock; _sEBlock = endBlock; _sTokensPerEth = tokensPerEth; _sCap = cap; _sCount = 0; } function buyTokens() public payable returns (bool success){ require(_sSBlock <= block.number && block.number <= _sEBlock, "Sale not active"); require(_sCount < _sCap || _sCap == 0, "Max sale participants reached, sale is over"); uint256 _eth = msg.value; uint256 _tokens; _tokens = _eth * _sTokensPerEth; require(_tokens <= balanceOf(address(this)), "Insufficient tokens avaialble for eth amount, try with less eth"); _sCount ++; _transfer(address(this), msg.sender, _tokens); return true; } function viewSale() public view returns(uint256 startBlock, uint256 endBlock, uint256 tokensPerEth,uint256 cap, uint256 count){ return(_sSBlock, _sEBlock, _sTokensPerEth,_sCap, _sCount); } function withdrawal() public onlyOwner() { address payable _owner = payable(msg.sender); _owner.transfer(address(this).balance); } receive() external payable { } }
Current claim count
uint256 private _cCount;
2,032,349
[ 1, 3935, 7516, 1056, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 3238, 389, 71, 1380, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.17; 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; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library 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; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "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 returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "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 { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } contract Dakota is Context, ERC20, ERC20Detailed { uint8 public constant DECIMALS = 18; uint256 public constant INITIAL_SUPPLY = 10000000000 * (10 ** uint256(DECIMALS)); /** * @dev Constructor that gives _msgSender() all of existing tokens. */ constructor () public ERC20Detailed("DAKOTA", "Dkt", 18) { _mint(_msgSender(), INITIAL_SUPPLY); } }
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of these values are immutable: they can only be set once during construction./
constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; }
7,393,751
[ 1, 2785, 326, 924, 364, 1375, 529, 9191, 1375, 7175, 9191, 471, 1375, 31734, 8338, 4826, 8925, 434, 4259, 924, 854, 11732, 30, 2898, 848, 1338, 506, 444, 3647, 4982, 16171, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 261, 1080, 3778, 508, 16, 533, 3778, 3273, 16, 2254, 28, 15105, 13, 1071, 288, 203, 203, 203, 3639, 389, 529, 273, 508, 31, 203, 203, 203, 3639, 389, 7175, 273, 3273, 31, 203, 203, 203, 3639, 389, 31734, 273, 15105, 31, 203, 203, 203, 565, 289, 203, 203, 203, 203, 203, 203, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x1D3bB909600c6c2F3Ae6014EDb3a9b5F5cf20aA3/sources/browser/OwnablePayable.sol
* Transfers control of the contract to a newOwner @param newOwner The address to transfer ownership to/
function _transferOwnership(address payable newOwner) internal { require(newOwner != address(0), 'Not transferable to nobody'); _owner = newOwner; emit OwnershipTransferred(_owner, newOwner); }
8,115,057
[ 1, 1429, 18881, 3325, 434, 326, 6835, 358, 279, 394, 5541, 225, 394, 5541, 1021, 1758, 358, 7412, 23178, 358, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 389, 13866, 5460, 12565, 12, 2867, 8843, 429, 394, 5541, 13, 2713, 288, 203, 3639, 2583, 12, 2704, 5541, 480, 1758, 12, 20, 3631, 296, 1248, 7412, 429, 358, 290, 947, 973, 8284, 203, 3639, 389, 8443, 273, 394, 5541, 31, 203, 3639, 3626, 14223, 9646, 5310, 1429, 4193, 24899, 8443, 16, 394, 5541, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0xEe7e8Efd95Fa33a0e65677a519B9e35adE044304/sources/browser/comreserve.sol
This can be increased, use info() to see the up to date unlocking time
unlockDate = 1593885600;
8,137,494
[ 1, 2503, 848, 506, 31383, 16, 999, 1123, 1435, 358, 2621, 326, 731, 358, 1509, 7186, 310, 813, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 3639, 7186, 1626, 273, 4711, 11180, 5482, 4313, 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, -100, -100, -100, -100 ]
./full_match/1/0xcf12800894d3fc9c53f243E3B3179Fe99A4ABdf1/sources/contracts/seekrewards.sol
Total withdraw amount
uint256 public totalWithdraw;
9,620,574
[ 1, 5269, 598, 9446, 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, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 2078, 1190, 9446, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; import "./../tokens/RightsBaseToken.sol"; import "./../utils/RDDNControl.sol"; import "./../utils/ManagerRole.sol"; import "./../interfaces/ITokenManager.sol"; import "./../utils/OwnerLinkedIdList.sol"; import "openzeppelin-solidity/math/SafeMath.sol"; import "openzeppelin-solidity/utils/Address.sol"; contract TokenManager is RDDNControl, ITokenManager, MinterRole, ManagerRole { using SafeMath for uint256; using Address for address; /*** STORAGE ***/ // All token contract addresses address[] public contracts; // Mapping from contract address to token ID mapping(address => uint256) internal contractToTokenId; // Mapping from contract address to contract issues mapping (address => bool) internal contractIssues; // Mapping from token ID to owner mapping(uint256 => address) internal tokenOwner; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) internal ownedTokenIds; // Mapping from holder to token Ids OwnerLinkedIdList private heldTokenIdList; /*** CONSTRUCTOR ***/ constructor() public { heldTokenIdList = new OwnerLinkedIdList(); } /*** EXTERNAL FUNCTIONS ***/ /// @dev issue the specified token in Rihgts Distributed Digital Network. /// @param _contractAddress token address. /// @return A boolean that indicates if the token was issued. function issue( address _contractAddress ) whenNotPaused public returns (bool) { require(!_exists(_contractAddress)); uint256 tokenId = contracts.push(_contractAddress).sub(1); contractToTokenId[_contractAddress] = tokenId; contractIssues[_contractAddress] = true; _addTokenTo(msg.sender, tokenId); emit Issue(msg.sender, tokenId); return true; } /// @dev Transfer the specified amount of token to the specified address. /// @param _to Receiver address. /// @param _value Amount of tokens that will be transferred. /// @param _tokenId token identifer. function transfer( address _to, uint256 _value, uint256 _tokenId ) public whenNotPaused returns (bool) { require(_exists(_tokenId)); RightsBaseToken token = RightsBaseToken(contracts[_tokenId]); require(_value <= token.balanceOf(msg.sender)); require(_to != address(0)); if(!_to.isContract()) { token.forceTransferFrom(msg.sender, _to, _value); _handleTokenHolder(msg.sender, _to, _tokenId, _value); } emit Transfer(msg.sender, _to, _value, _tokenId); return true; } /// @dev Transfer the specified amount of token from the specified address /// to the specified address. /// @param _from Sender address. /// @param _to Receiver address. /// @param _value Amount of tokens that will be transferred. /// @param _tokenId token identifer. function transferFrom( address _from, address _to, uint256 _value, uint256 _tokenId ) public whenNotPaused returns (bool) { require(_exists(_tokenId)); RightsBaseToken token = RightsBaseToken(contracts[_tokenId]); require(_value <= token.balanceOf(_from)); require(_to != address(0)); if(!_to.isContract()) { token.transferFrom(_from, _to, _value); _handleTokenHolder(_from, _to, _tokenId, _value); } emit Transfer(_from, _to, _value, _tokenId); return true; } /// @dev Transfer the specified amount of token from the specified address /// to the specified address by managers. /// @param _from Sender address. /// @param _to Receiver address. /// @param _value Amount of tokens that will be transferred. /// @param _tokenId token identifer. function forceTransferFrom( address _from, address _to, uint256 _value, uint256 _tokenId ) public whenNotPaused onlyManager returns (bool) { require(_exists(_tokenId)); RightsBaseToken token = RightsBaseToken(contracts[_tokenId]); require(_value <= token.balanceOf(_from)); require(_to != address(0)); if(!_to.isContract()) { token.forceTransferFrom(_from, _to, _value); _handleTokenHolder(_from, _to, _tokenId, _value); } emit Transfer(_from, _to, _value, _tokenId); return true; } /// @dev Updates the token info of the specified token ID /// @param _tokenId tokenId of the token object /// @param _name Name of the token object /// @param _symbol Symbol of the token object function updateTokenInfo(uint256 _tokenId, string _name, string _symbol) public { require(_exists(_tokenId)); require(ownerOf(_tokenId) == msg.sender); RightsBaseToken token = RightsBaseToken(contracts[_tokenId]); token.update(_name, _symbol); emit Update(msg.sender, _tokenId); } /// @dev Gets contract count. /// @return count of contract. function getContractCount() public constant returns(uint256) { return contracts.length; } /// @dev Gets the contract address of the specified token ID /// @return count of contract. function contractOf(uint256 _tokenId) public constant returns(address) { return contracts[_tokenId]; } /// @dev get tokenId from contract address. /// @param _contractAddress Contract address. /// @return count of contract. function getTokenId(address _contractAddress) public constant returns(uint256) { require(_exists(_contractAddress)); return contractToTokenId[_contractAddress]; } /// @dev Total number of tokens in existence /// @param _tokenId The token Iidentifer function totalSupplyOf(uint256 _tokenId) public view returns (uint256) { require(_exists(_tokenId)); RightsBaseToken token = RightsBaseToken(contracts[_tokenId]); return token.totalSupply(); } /// @dev Returns balance of the `_owner`. /// @param _tokenId The token Iidentifer /// @param _owner The address whose balance will be returned. /// @return balance Balance of the `_owner`. function balanceOf(uint256 _tokenId, address _owner) public constant returns (uint256) { require(_exists(_tokenId)); RightsBaseToken token = RightsBaseToken(contracts[_tokenId]); return token.balanceOf(_owner); } /// @dev Gets the owner of the specified token ID /// @param _tokenId uint256 ID of the token to query the owner of /// @return holders address currently marked as the owner of the given token ID function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /// @dev Gets the token IDs of the requested owner /// @param _owner address owning the objects list to be accessed /// @return uint256 token IDs owned by the requested address function tokensOfOwner(address _owner) public view returns (uint256[]) { return ownedTokenIds[_owner]; } /// @dev Gets the token IDs of the requested owner /// @param _holder address holding the objects list to be accessed /// @return uint256 token IDs held by the requested address function tokensOfHolder(address _holder) public view returns (uint256[]) { return heldTokenIdList.valuesOf(_holder); } /// @dev Decimals of the token /// @param _tokenId token id /// @return decimals function decimalsOf(uint256 _tokenId) public view returns (uint8) { // base money info address baseTokenAddr = contractOf(_tokenId); RightsBaseToken baseToken = RightsBaseToken(baseTokenAddr); return baseToken.decimals(); } /// @dev Gets the token object of the specified token ID /// @param _tokenId the tokenId of the token /// @return tokenId the tokenId of the token /// @return contractAddress the contractAddress of the token /// @return name the name of the token /// @return symbol the symbol of the token /// @return owner the owner of the token /// @return totalSupply the total supply of the token /// @return decimals the decimals of the token function getTokenInfo(uint256 _tokenId) public view returns( uint256 tokenId, address contractAddress, string name, string symbol, address owner, uint256 totalSupply, uint8 decimals ) { require(_exists(_tokenId)); RightsBaseToken token = RightsBaseToken(contracts[_tokenId]); return ( _tokenId, contracts[_tokenId], token.name(), token.symbol(), ownerOf(_tokenId), token.totalSupply(), token.decimals() ); } /// @dev Calculate relative amount of each tokens /// @param _targetTokenId target token id /// @param _baseTokenId base token id /// @param _amount amount function relativeAmountOf( uint256 _targetTokenId, uint256 _baseTokenId, uint256 _amount ) public view returns (uint256) { if (_targetTokenId == _baseTokenId) { return _amount; } else { // use money info uint256 targetDecimals = uint256(decimalsOf(_targetTokenId)); // base money info uint256 baseDecimals = uint256(decimalsOf(_baseTokenId)); if(targetDecimals >= baseDecimals) { return _amount.mul(10 ** (targetDecimals - baseDecimals)); } else { return _amount.div(10 ** (baseDecimals - targetDecimals)); } } } /*** INTERNAL FUNCTIONS ***/ /// @dev Check if it is issued contract address /// @param _tokenId token id. /// @return A boolean that indicates if the token exists. function _exists(uint256 _tokenId) internal view returns (bool) { return tokenOwner[_tokenId] != address(0); } /// @dev Check if it is issued contract address /// @param _contractAddress token address. /// @return A boolean that indicates if the token exists. function _exists(address _contractAddress) internal view returns (bool) { return contractIssues[_contractAddress]; } /// @dev Internal function to add a token ID to the list of a given address /// @param _to address representing the new owner of the given token ID /// @param _tokenId uint256 ID of the token to be added to the tokens list of the given address function _addTokenTo(address _to, uint256 _tokenId) internal { require(!_isRegisteredToken(_tokenId)); ownedTokenIds[_to].push(_tokenId); tokenOwner[_tokenId] = _to; } /// @dev Internal function to add a token ID to the list of a given address /// @param _to address representing the new owner of the given token ID /// @param _tokenId uint256 ID of the token to be added to the tokens list of the given address function _addTokenHolderTo(address _to, uint256 _tokenId) internal { require(!_isRegisteredTokenHolder(_to, _tokenId)); // heldTokensIndex[_to][_tokenId] = holderToTokenIds[_to].push(_tokenId); heldTokenIdList.add(_to, _tokenId); } /// @dev Internal function to remove a token ID from the list of a given address /// @param _from address representing the previous owner of the given token ID /// @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address function _removeTokenHolderFrom(address _from, uint256 _tokenId) internal { require(_isRegisteredTokenHolder(_from, _tokenId)); heldTokenIdList.remove(_from, _tokenId); } /// @dev Internal function to handle token holder list /// @param _from address representing the sender /// @param _to address representing the reciever /// @param _tokenId uint256 ID of the token to be handled /// @param _value uint256 amount of token to be handled function _handleTokenHolder(address _from, address _to, uint256 _tokenId, uint256 _value) internal { if (_from != address(0) && RightsBaseToken(contracts[_tokenId]).balanceOf(_from) == 0 ) { _removeTokenHolderFrom(_from, _tokenId); } if (_to != address(0) && RightsBaseToken(contracts[_tokenId]).balanceOf(_to) == _value) { _addTokenHolderTo(_to, _tokenId); } } /// @dev Returns whether the specified token id registered /// @param _tokenId token identifer. /// @return whether the token registered function _isRegisteredToken(uint256 _tokenId) internal view returns (bool) { return tokenOwner[_tokenId] != address(0); } /// @dev Returns whether the specified token id registered /// @param _to address representing the new owner of the given token ID /// @param _tokenId token identifer. /// @return whether the token registered function _isRegisteredTokenHolder(address _to, uint256 _tokenId) internal view returns (bool) { return heldTokenIdList.exists(_to, _tokenId); } }
@dev Transfer the specified amount of token from the specified address to the specified address. @param _from Sender address. @param _to Receiver address. @param _value Amount of tokens that will be transferred. @param _tokenId token identifer.
function transferFrom( address _from, address _to, uint256 _value, uint256 _tokenId ) public whenNotPaused returns (bool) { require(_exists(_tokenId)); RightsBaseToken token = RightsBaseToken(contracts[_tokenId]); require(_value <= token.balanceOf(_from)); require(_to != address(0)); if(!_to.isContract()) { token.transferFrom(_from, _to, _value); _handleTokenHolder(_from, _to, _tokenId, _value); } emit Transfer(_from, _to, _value, _tokenId); return true; }
12,926,910
[ 1, 5912, 326, 1269, 3844, 434, 1147, 628, 326, 1269, 1758, 358, 326, 1269, 1758, 18, 225, 389, 2080, 225, 15044, 1758, 18, 225, 389, 869, 565, 31020, 1758, 18, 225, 389, 1132, 16811, 434, 2430, 716, 903, 506, 906, 4193, 18, 225, 389, 2316, 548, 225, 1147, 3390, 21549, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 1265, 12, 203, 3639, 1758, 389, 2080, 16, 203, 3639, 1758, 389, 869, 16, 203, 3639, 2254, 5034, 389, 1132, 16, 203, 3639, 2254, 5034, 389, 2316, 548, 203, 565, 262, 1071, 1347, 1248, 28590, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 24899, 1808, 24899, 2316, 548, 10019, 203, 3639, 534, 10730, 2171, 1345, 1147, 273, 534, 10730, 2171, 1345, 12, 16351, 87, 63, 67, 2316, 548, 19226, 203, 203, 3639, 2583, 24899, 1132, 1648, 1147, 18, 12296, 951, 24899, 2080, 10019, 203, 3639, 2583, 24899, 869, 480, 1758, 12, 20, 10019, 203, 203, 3639, 309, 12, 5, 67, 869, 18, 291, 8924, 10756, 288, 203, 5411, 1147, 18, 13866, 1265, 24899, 2080, 16, 389, 869, 16, 389, 1132, 1769, 203, 5411, 389, 4110, 1345, 6064, 24899, 2080, 16, 389, 869, 16, 389, 2316, 548, 16, 389, 1132, 1769, 203, 3639, 289, 203, 203, 3639, 3626, 12279, 24899, 2080, 16, 389, 869, 16, 389, 1132, 16, 389, 2316, 548, 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 ]
./partial_match/1/0x21aa8D3eEe8be2333eD180e9A5A8C0729C9B652c/sources/EnsSubdomainFactory.sol
* @title EnsSubdomainFactory @dev Allows to create and configure a first level subdomain for Ethereum ENS in one call. After deploying this contract, change the owner of the top level domain you want to use to this deployed contract address. For example, transfer the ownership of "startonchain.eth" so anyone can create subdomains like "radek.startonchain.eth"./
contract EnsSubdomainFactory { address public owner; EnsRegistry public registry; EnsResolver public resolver; bool public locked; bytes32 ethNameHash = 0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae; event SubdomainCreated(address indexed creator, address indexed owner, string subdomain, string domain); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event RegistryUpdated(address indexed previousRegistry, address indexed newRegistry); event ResolverUpdated(address indexed previousResolver, address indexed newResolver); event TopLevelDomainTransfersLocked(); constructor(EnsRegistry _registry, EnsResolver _resolver) public { owner = msg.sender; registry = _registry; resolver = _resolver; locked = false; } modifier onlyOwner() { require(msg.sender == owner); _; } function newSubdomain(string _subDomain, string _topLevelDomain, address _owner, address _target) public { bytes32 topLevelNamehash = keccak256(abi.encodePacked(ethNameHash, keccak256(abi.encodePacked(_topLevelDomain)))); require(registry.owner(topLevelNamehash) == address(this), "this contract should own top level domain"); bytes32 subDomainLabelhash = keccak256(abi.encodePacked(_subDomain)); bytes32 subDomainNamehash = keccak256(abi.encodePacked(topLevelNamehash, subDomainLabelhash)); require(registry.owner(subDomainNamehash) == address(0) || registry.owner(subDomainNamehash) == msg.sender, "sub domain already owned"); registry.setSubnodeOwner(topLevelNamehash, subDomainLabelhash, address(this)); registry.setResolver(subDomainNamehash, resolver); resolver.setAddr(subDomainNamehash, _target); registry.setOwner(subDomainNamehash, _owner); emit SubdomainCreated(msg.sender, _owner, _subDomain, _topLevelDomain); } function topLevelDomainOwner(string _topLevelDomain) public view returns(address) { bytes32 namehash = keccak256(abi.encodePacked(ethNameHash, keccak256(abi.encodePacked(_topLevelDomain)))); return registry.owner(namehash); } function subDomainOwner(string _subDomain, string _topLevelDomain) public view returns(address) { bytes32 topLevelNamehash = keccak256(abi.encodePacked(ethNameHash, keccak256(abi.encodePacked(_topLevelDomain)))); bytes32 subDomainNamehash = keccak256(abi.encodePacked(topLevelNamehash, keccak256(abi.encodePacked(_subDomain)))); return registry.owner(subDomainNamehash); } function transferTopLevelDomainOwnership(bytes32 _node, address _owner) public onlyOwner { require(!locked); registry.setOwner(_node, _owner); } function lockTopLevelDomainOwnershipTransfers() public onlyOwner { require(!locked); locked = true; emit TopLevelDomainTransfersLocked(); } function updateRegistry(EnsRegistry _registry) public onlyOwner { require(registry != _registry, "new registry should be different from old"); emit RegistryUpdated(registry, _registry); registry = _registry; } function updateResolver(EnsResolver _resolver) public onlyOwner { require(resolver != _resolver, "new resolver should be different from old"); emit ResolverUpdated(resolver, _resolver); resolver = _resolver; } function transferContractOwnership(address _owner) public onlyOwner { require(_owner != address(0), "cannot transfer to address(0)"); emit OwnershipTransferred(owner, _owner); owner = _owner; } }
2,633,298
[ 1, 664, 87, 1676, 4308, 1733, 225, 25619, 358, 752, 471, 5068, 279, 1122, 1801, 16242, 364, 512, 18664, 379, 512, 3156, 316, 1245, 745, 18, 7360, 7286, 310, 333, 6835, 16, 2549, 326, 3410, 434, 326, 1760, 1801, 2461, 1846, 2545, 358, 999, 358, 333, 19357, 6835, 1758, 18, 2457, 3454, 16, 7412, 326, 23178, 434, 315, 1937, 265, 5639, 18, 546, 6, 1427, 1281, 476, 848, 752, 720, 14180, 3007, 315, 354, 323, 79, 18, 1937, 265, 5639, 18, 546, 9654, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 1374, 87, 1676, 4308, 1733, 288, 203, 202, 2867, 1071, 3410, 31, 203, 565, 1374, 87, 4243, 1071, 4023, 31, 203, 202, 664, 87, 4301, 1071, 5039, 31, 203, 202, 6430, 1071, 8586, 31, 203, 565, 1731, 1578, 13750, 461, 2310, 273, 374, 92, 11180, 71, 31888, 27, 6840, 70, 5877, 7950, 7201, 6028, 28, 24008, 29, 6030, 1611, 6669, 26035, 72, 21, 71, 3707, 71, 8313, 28, 329, 26, 74, 3028, 8148, 20, 69, 20, 31345, 5482, 69, 11180, 7142, 24, 8906, 31, 203, 203, 202, 2575, 2592, 4308, 6119, 12, 2867, 8808, 11784, 16, 1758, 8808, 3410, 16, 533, 16242, 16, 533, 2461, 1769, 203, 202, 2575, 14223, 9646, 5310, 1429, 4193, 12, 2867, 8808, 2416, 5541, 16, 1758, 8808, 394, 5541, 1769, 203, 202, 2575, 5438, 7381, 12, 2867, 8808, 2416, 4243, 16, 1758, 8808, 394, 4243, 1769, 203, 202, 2575, 17183, 7381, 12, 2867, 8808, 2416, 4301, 16, 1758, 8808, 394, 4301, 1769, 203, 202, 2575, 7202, 2355, 3748, 1429, 18881, 8966, 5621, 203, 203, 202, 12316, 12, 664, 87, 4243, 389, 9893, 16, 1374, 87, 4301, 389, 14122, 13, 1071, 288, 203, 202, 202, 8443, 273, 1234, 18, 15330, 31, 203, 202, 202, 9893, 273, 389, 9893, 31, 203, 202, 202, 14122, 273, 389, 14122, 31, 203, 202, 202, 15091, 273, 629, 31, 203, 202, 97, 203, 203, 202, 20597, 1338, 5541, 1435, 288, 203, 202, 225, 2583, 12, 3576, 18, 15330, 422, 3410, 1769, 203, 202, 225, 389, 31, 203, 202, 97, 203, 203, 202, 915, 394, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // ERC721URIStorage allows you to set tokenURI after minting // ERC721Holder ensures that a smart contract can hold NFTs import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; library CollaborativeMinterHolder { struct SalesTransaction { address from; // buyer address to; // recipient of token uint256[] tokenIds; // tokens for sale uint256 value; // price for token bool secondarySale; // check if we have a secondary sale bool revoked; bool executed; bool executing; // check if library is executing transation bool modifying; // check if transaction is being modified uint256 numConfirmations; } modifier onlyOwner(CollaborativeMinter _collaborativeMinter) { // restrict to only owners require(_collaborativeMinter.isOwner(msg.sender),'not an owner'); _; } // restrict only to transactions that exist modifier salesTransactionExists(uint256 _txIndex, SalesTransaction[] storage _salesTransactions) { require(_txIndex < _salesTransactions.length, "sales transaction does not exist"); _; } // restrict only to transactions that are not executed modifier salesTransactionNotExecuted(uint256 _txIndex, SalesTransaction[] storage _salesTransactions) { require(!_salesTransactions[_txIndex].executed, "sales transaction is already executed"); _; } // restrict only to transactions that are not confirmed by caller modifier salesTransactionNotConfirmed(uint256 _txIndex, CollaborativeMinter _collaborativeMinter) { require(!_collaborativeMinter.getConfirmation(_txIndex, msg.sender), "sales transaction is already confirmed"); _; } // restrict only to transactions that are not revoked by original buyer modifier salesTransactionNotRevoked(uint256 _txIndex, SalesTransaction[] storage _salesTransactions) { require(!_salesTransactions[_txIndex].revoked, "sales transaction is already revoked"); _; } // restrict to the sender of the sales transaction modifier onlySalesTransactionSender(uint256 _txIndex, SalesTransaction[] storage _salesTransactions) { require(_salesTransactions[_txIndex].from == msg.sender, "not the sales transaction sender"); _; } // check if token IDs are valid and are owned by contract modifier ownedByContract(uint256[] memory _tokenIds, CollaborativeMinter _collaborativeMinter) { for(uint256 i = 0; i < _tokenIds.length; i++){ require(_tokenIds[i] < _collaborativeMinter.tokenCounter(), "invalid token ID"); require(_collaborativeMinter.isApprovedOrOwner(address(_collaborativeMinter),_tokenIds[i]),"token not owned by contract"); } _; } modifier allOwnedByContract(CollaborativeMinter _collaborativeMinter) { // check if all NFTs are owned by the contract for(uint256 i = 0; i < _collaborativeMinter.tokenCounter(); i++){ require(_collaborativeMinter.isApprovedOrOwner(address(_collaborativeMinter),i),"not all tokens owned by contract"); } _; } function submitSalesTransaction(address _from, address _to, uint256[] memory _tokenIds, uint256 _value, SalesTransaction[] storage _salesTransactions, CollaborativeMinter _collaborativeMinter) ownedByContract(_tokenIds, _collaborativeMinter) public returns (uint256) { // buyer sends sales transaction, returns transaction index uint256 txIndex = _salesTransactions.length; _salesTransactions.push(SalesTransaction({ from: _from, to: _to, tokenIds: _tokenIds, value: _value, secondarySale: false, revoked: false, executed: false, executing: false, modifying: false, numConfirmations: 0 })); return txIndex; } function submitSecondarySalesTransaction(address _from, address _to, uint256[] memory _tokenIds, uint256 _value, SalesTransaction[] storage _salesTransactions) public returns (uint256) { // buyer sends sales transaction, returns transaction index uint256 txIndex = _salesTransactions.length; _salesTransactions.push(SalesTransaction({ from: _from, to: _to, tokenIds: _tokenIds, value: _value, secondarySale: true, revoked: false, executed: false, executing: false, modifying: false, numConfirmations: 0 })); return txIndex; } function approveSalesTransaction(uint256 _txIndex, SalesTransaction[] storage _salesTransactions, CollaborativeMinter _collaborativeMinter) onlyOwner(_collaborativeMinter) salesTransactionExists(_txIndex, _salesTransactions) salesTransactionNotExecuted(_txIndex, _salesTransactions) salesTransactionNotConfirmed(_txIndex, _collaborativeMinter) salesTransactionNotRevoked(_txIndex, _salesTransactions) public returns (bool) { // owner approves sales transaction // update confirmations and number of confirmations _salesTransactions[_txIndex].modifying = true; _collaborativeMinter.setConfirmation(_txIndex, msg.sender, true); _salesTransactions[_txIndex].modifying = false; _salesTransactions[_txIndex].numConfirmations += 1; if(_salesTransactions[_txIndex].numConfirmations == _collaborativeMinter.numberOfOwners()){ // execute if approved by all owners _salesTransactions[_txIndex].executing = true; executeSalesTransaction(_txIndex, _salesTransactions, _collaborativeMinter); _salesTransactions[_txIndex].executing = false; } return true; } function denySalesTransaction(uint256 _txIndex, SalesTransaction[] storage _salesTransactions, CollaborativeMinter _collaborativeMinter) onlyOwner(_collaborativeMinter) salesTransactionExists(_txIndex, _salesTransactions) salesTransactionNotExecuted(_txIndex, _salesTransactions) salesTransactionNotRevoked(_txIndex, _salesTransactions) public returns (bool) { // owner denies sales transaction // update confirmations and number of confirmations require(_collaborativeMinter.getConfirmation(_txIndex,msg.sender), "sales transaction not approved by owner"); _salesTransactions[_txIndex].modifying = true; _collaborativeMinter.setConfirmation(_txIndex, msg.sender, false); _salesTransactions[_txIndex].modifying = false; _salesTransactions[_txIndex].numConfirmations -= 1; return true; } // sender revoke sales transaction to get ETH back function revokeSalesTransaction(uint256 _txIndex, SalesTransaction[] storage _salesTransactions) public salesTransactionExists(_txIndex, _salesTransactions) salesTransactionNotExecuted(_txIndex, _salesTransactions) salesTransactionNotRevoked(_txIndex, _salesTransactions) returns (bool) { require(_salesTransactions[_txIndex].from == msg.sender, "must be account that submitted sales transaction"); uint256 amountToPay = _salesTransactions[_txIndex].value; bool success; (success, ) = _salesTransactions[_txIndex].from.call{value: amountToPay}(""); require(success, "Transfer failed."); _salesTransactions[_txIndex].revoked = true; return true; } function executeSalesTransaction(uint _txIndex, SalesTransaction[] storage _salesTransactions, CollaborativeMinter _collaborativeMinter) internal returns (bool) { uint256[] memory tokens = _salesTransactions[_txIndex].tokenIds; if(_salesTransactions[_txIndex].secondarySale == false) { // initial sale // send ETH to each owner uint256 amountToPay = _salesTransactions[_txIndex].value / _collaborativeMinter.numberOfOwners(); bool success; // pay each owner for(uint256 i = 0; i < _collaborativeMinter.numberOfOwners(); i++){ (success, ) = _collaborativeMinter.owners(i).call{value:amountToPay}(""); require(success, "Transfer failed."); } } else { // secondary sale // apply secondary sale fee and send ETH to each owner uint256 secondarySaleValue = _salesTransactions[_txIndex].value / 10; // 10% goes to owners uint256 amountToPay = secondarySaleValue / _collaborativeMinter.numberOfOwners(); bool success; // pay each owner for(uint256 i = 0; i < _collaborativeMinter.numberOfOwners(); i++){ (success, ) = _collaborativeMinter.owners(i).call{value:amountToPay}(""); require(success, "Transfer failed."); } } // send each NFT from the smart contract to the new owner for(uint256 i = 0; i < tokens.length; i++){ _collaborativeMinter.executingTransfer(_txIndex, address(_collaborativeMinter), _salesTransactions[_txIndex].to, tokens[i]); } _salesTransactions[_txIndex].executed = true; return true; } function safeTransferFrom(address _from, address _to, uint256 _tokenId, uint256 _latestReceived, SalesTransaction[] storage _salesTransactions, CollaborativeMinter _collaborativeMinter) public { require(_collaborativeMinter.isApprovedOrOwner(_from, _tokenId), "ERC721: transfer caller is not owner nor approved"); // create a secondary sales transaction, send NFT to contract, execute secondary sale uint256[] memory tokenIdArray = new uint256[](1); tokenIdArray[0] = _tokenId; uint256 secondarySaleId = submitSecondarySalesTransaction(_from, _to, tokenIdArray, _latestReceived, _salesTransactions); _salesTransactions[secondarySaleId].executing = true; _collaborativeMinter.executingTransfer(secondarySaleId, _from, address(_collaborativeMinter), _tokenId); executeSalesTransaction(secondarySaleId, _salesTransactions, _collaborativeMinter); _salesTransactions[secondarySaleId].executing = false; } } // NFT Smart Contract Constructor contract CollaborativeMinter is ERC721URIStorage, ERC721Holder{ uint256 public tokenCounter; uint256 public currentOwner; // define whose turn it is at the current time with owners index\ uint256 public numberOfOwners; bool public isMerged; // defines whether we have a composite NFT address[] public owners; // keep track of all owners of the NFT mapping(address => bool) public isOwner; // used to check if someone is an owner uint256 public latestReceived; // used to get the msg.value for secondary sales // create structs for use with CollaborativeMinterHolder library using CollaborativeMinterHolder for CollaborativeMinterHolder.SalesTransaction; CollaborativeMinterHolder.SalesTransaction[] public salesTransactions; mapping(uint => mapping(address => bool)) public isConfirmed; constructor (address[] memory _owners) ERC721 ("Collaborative Mint", "COMINT"){ require(_owners.length > 0, "owners required"); tokenCounter = 0; numberOfOwners = _owners.length; currentOwner = 0; // define the first owner to have an active turn isMerged = false; for(uint256 i = 0; i < _owners.length; i++){ // define the owners owners.push(_owners[i]); isOwner[_owners[i]] = true; } } modifier onlyCurrentOwner { // restrict to only the active owner require(msg.sender == owners[currentOwner], "not your turn"); _; } modifier onlyOwner { // restrict to only owners require(isOwner[msg.sender],'not an owner'); _; } modifier isNotMerged() { // check if we have a composite NFT require(!isMerged, "NFT is a completed composite"); _; } modifier hasBeenMinted(){ // check if an NFT has been minted require(tokenCounter > 0, "no NFTs have been minted"); _; } modifier allOwnedByContract() { // check if all NFTs are owned by the contract for(uint256 i = 0; i < tokenCounter; i++) { require(_isApprovedOrOwner(address(this),i),"not all tokens owned by contract"); } _; } modifier currentlyExecuting(uint256 _txIndex) { // check if the transaction is currently executing require(salesTransactions[_txIndex].executing,"transaction must be currently executing"); _; } modifier currentlyModifying(uint256 _txIndex) { // check if the transaction is currently being modified require(salesTransactions[_txIndex].modifying,"transaction must be being modified"); _; } receive() external payable { latestReceived = msg.value; } // NFT minting function where only the current owner can mint. Smart contract holds NFTs upon minting function collaborativeMint(string memory _tokenURI) public onlyCurrentOwner isNotMerged returns (uint256) { uint256 newItemId = tokenCounter; _safeMint(address(this), newItemId); // the owner of the NFT is the holder smart contract _setTokenURI(newItemId, _tokenURI); tokenCounter = tokenCounter + 1; uint256 nextOwnerId = (currentOwner + 1) % owners.length; // set up the next turn by getting the following ID currentOwner = nextOwnerId; // update whose turn it is return newItemId; } // NFT minting function where only the current owner can mint. Smart contract holds NFTs upon minting function _collaborativeMint(string memory _tokenURI) private returns (uint256) { uint256 newItemId = tokenCounter; _safeMint(address(this), newItemId); // the owner of the NFT is the holder smart contract _setTokenURI(newItemId, _tokenURI); tokenCounter = tokenCounter + 1; return newItemId; } // merge all collaborative mints and create a composite NFT function mergeCollaborativeMint(string memory _tokenURI) public onlyOwner hasBeenMinted isNotMerged allOwnedByContract returns (bool) { isMerged = true; // burn all collaborative mints for(uint256 i = 0; i < tokenCounter; i++) { _burn(i); } // create a composite NFT _collaborativeMint(_tokenURI); return true; } function isApprovedOrOwner(address _account, uint256 _tokenId) public view returns (bool) { return _isApprovedOrOwner(_account, _tokenId); } // used to transfer NFTs while a transaction is being executed function executingTransfer(uint256 _txIndex, address _from, address _to, uint256 _tokenId) currentlyExecuting(_txIndex) public returns (bool) { _safeTransfer(_from, _to, _tokenId, ""); return true; } // Override safeTransferFrom to allow for royalties from secondary sales function safeTransferFrom(address _from, address _to, uint256 _tokenId) public virtual override { CollaborativeMinterHolder.safeTransferFrom(_from, _to, _tokenId, latestReceived, salesTransactions, this); } // Override safeTransferFrom to allow for royalties from secondary sales function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory _data) public virtual override { CollaborativeMinterHolder.safeTransferFrom(_from, _to, _tokenId, latestReceived, salesTransactions, this); } // Override transferFrom to allow for royalties from secondary sales function transferFrom(address _from, address _to, uint256 _tokenId) public virtual override { CollaborativeMinterHolder.safeTransferFrom(_from, _to, _tokenId, latestReceived, salesTransactions, this); } // submit a sales transaction function submitSalesTransaction(address _to, uint256[] memory _tokenIds) payable public { CollaborativeMinterHolder.submitSalesTransaction(msg.sender, _to, _tokenIds, msg.value, salesTransactions, this); } function approveSalesTransaction(uint256 _txIndex) public returns (bool) { CollaborativeMinterHolder.approveSalesTransaction(_txIndex, salesTransactions, this); return true; } function denySalesTransaction(uint256 _txIndex) public returns (bool) { CollaborativeMinterHolder.denySalesTransaction(_txIndex, salesTransactions, this); return true; } function revokeSalesTransaction(uint256 _txIndex) public returns (bool) { CollaborativeMinterHolder.revokeSalesTransaction(_txIndex, salesTransactions); return true; } // Retreive the sales transaction data function getSalesTransaction(uint256 _txIndex) public view returns (CollaborativeMinterHolder.SalesTransaction memory) { return salesTransactions[_txIndex]; } function getConfirmation(uint256 _txIndex, address _owner) public view returns (bool) { return isConfirmed[_txIndex][_owner]; } function setConfirmation(uint256 _txIndex, address _owner, bool value) currentlyModifying(_txIndex) public returns (bool) { isConfirmed[_txIndex][_owner] = value; return true; } }
restrict to the sender of the sales transaction
modifier onlySalesTransactionSender(uint256 _txIndex, SalesTransaction[] storage _salesTransactions) { require(_salesTransactions[_txIndex].from == msg.sender, "not the sales transaction sender"); _; }
1,783,551
[ 1, 30604, 358, 326, 5793, 434, 326, 272, 5408, 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, 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, 9606, 1338, 23729, 3342, 12021, 12, 11890, 5034, 389, 978, 1016, 16, 25996, 3342, 8526, 2502, 389, 87, 5408, 14186, 13, 288, 203, 1377, 2583, 24899, 87, 5408, 14186, 63, 67, 978, 1016, 8009, 2080, 422, 1234, 18, 15330, 16, 315, 902, 326, 272, 5408, 2492, 5793, 8863, 203, 1377, 389, 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 ]
./partial_match/3/0x5116a45d89bf8Fbb2c87f9a49A9e348C9B4b79D6/sources/Faucet.sol
_fauceteer(0xF0A6664A0A8E95696BffB121A4fb0B1fC8C93d9E);
_fauceteer(0xF0A6664A0A8E95696BffB121A4fb0B1fC8C93d9E);
5,053,262
[ 1, 67, 507, 5286, 278, 4943, 12, 20, 16275, 20, 37, 6028, 1105, 37, 20, 37, 28, 41, 29, 4313, 10525, 38, 1403, 38, 26009, 37, 24, 19192, 20, 38, 21, 74, 39, 28, 39, 11180, 72, 29, 41, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 389, 507, 5286, 278, 4943, 12, 20, 16275, 20, 37, 6028, 1105, 37, 20, 37, 28, 41, 29, 4313, 10525, 38, 1403, 38, 26009, 37, 24, 19192, 20, 38, 21, 74, 39, 28, 39, 11180, 72, 29, 41, 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 ]
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropiate to concatenate * behavior. */ contract BitMilleCrowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // Amount of wei raised uint256 public weiRaised; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { require(now >= openingTime && now <= closingTime); _; } /** * @dev Reverts if not in crowdsale time range. */ modifier onlyAfterClosing { require(now > closingTime); _; } /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function BitMilleCrowdsale() public { wallet = 0x468E9A02c233C3DBb0A1b7F8bd8F8E9f36cbA952; token = ERC20(0xabb3148a39fb97af1295c5ee03e713d6ed54fd92); openingTime = 1520946000; closingTime = 1523970000; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { uint256 period = 7 days; uint256 perc; if ((now >= openingTime) && (now < openingTime + period)) { perc = 10; } else if ((now >= openingTime + period) && (now < openingTime + period * 2)) { perc = 9; } else if ((now >= openingTime + period * 2) && (now < openingTime + period * 3)) { perc = 8; } else { perc = 7; } return _weiAmount.mul(perc).div(100000); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { return now > closingTime; } function withdrawTokens() public onlyAfterClosing returns (bool) { token.transfer(wallet, token.balanceOf(this)); return true; } }
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. @param _beneficiary Address performing the token purchase @param _tokenAmount Number of tokens to be emitted/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transfer(_beneficiary, _tokenAmount); }
107,936
[ 1, 1830, 434, 2430, 18, 1439, 333, 707, 358, 5612, 326, 4031, 316, 1492, 326, 276, 492, 2377, 5349, 225, 406, 381, 5173, 5571, 471, 9573, 2097, 2430, 18, 225, 389, 70, 4009, 74, 14463, 814, 5267, 14928, 326, 1147, 23701, 225, 389, 2316, 6275, 3588, 434, 2430, 358, 506, 17826, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 26672, 5157, 12, 2867, 389, 70, 4009, 74, 14463, 814, 16, 2254, 5034, 389, 2316, 6275, 13, 2713, 288, 203, 3639, 1147, 18, 13866, 24899, 70, 4009, 74, 14463, 814, 16, 389, 2316, 6275, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0xdB3C43088Cc6Cbcc1cD51eA27F73E4811813f146/sources/contracts/fvz.sol
SPDX-License-Identifier: MIT
contract Token { mapping(address => uint) public balances; mapping(address => mapping(address => uint)) public allowance; uint public totalSupply = 1000000000000 * 10 ** 18; string public name = "Poker Star Tournament Token"; string public symbol = "PSTT"; uint public decimals = 18; event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); constructor() { balances[msg.sender] = totalSupply; } function balanceOf(address owner) public view returns(uint) { return balances[owner]; } function transfer(address to, uint value) public returns(bool) { require(balanceOf(msg.sender) >= value, 'balance too low'); balances[to] += value; balances[msg.sender] -= value; emit Transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) public returns(bool) { require(balanceOf(from) >= value, 'balance too low'); require(allowance[from][msg.sender] >= value, 'allowance too low'); balances[to] += value; balances[from] -= value; emit Transfer(from, to, value); return true; } function approve(address spender, uint value) public returns (bool) { allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } }
4,709,421
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 490, 1285, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3155, 288, 203, 565, 2874, 12, 2867, 516, 2254, 13, 1071, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 1071, 1699, 1359, 31, 203, 565, 2254, 1071, 2078, 3088, 1283, 273, 15088, 9449, 380, 1728, 2826, 6549, 31, 203, 565, 533, 1071, 508, 273, 315, 52, 601, 264, 934, 297, 2974, 30751, 3155, 14432, 203, 565, 533, 1071, 3273, 273, 315, 52, 882, 56, 14432, 203, 565, 2254, 1071, 15105, 273, 6549, 31, 203, 377, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 460, 1769, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 460, 1769, 203, 377, 203, 565, 3885, 1435, 288, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 2078, 3088, 1283, 31, 203, 565, 289, 203, 377, 203, 565, 445, 11013, 951, 12, 2867, 3410, 13, 1071, 1476, 1135, 12, 11890, 13, 288, 203, 3639, 327, 324, 26488, 63, 8443, 15533, 203, 565, 289, 203, 377, 203, 565, 445, 7412, 12, 2867, 358, 16, 2254, 460, 13, 1071, 1135, 12, 6430, 13, 288, 203, 3639, 2583, 12, 12296, 951, 12, 3576, 18, 15330, 13, 1545, 460, 16, 296, 12296, 4885, 4587, 8284, 203, 3639, 324, 26488, 63, 869, 65, 1011, 460, 31, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 3947, 460, 31, 203, 4202, 3626, 12279, 12, 3576, 18, 15330, 16, 358, 16, 460, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 3639, 2 ]
./full_match/1/0x2fB140574f02b3043a7B2342017f7E1A3a4f98Cb/sources/contracts/PoolPositionDynamicSlim.sol
binId changed; update it for contract
binIds[0] = newBinId;
3,849,596
[ 1, 4757, 548, 3550, 31, 1089, 518, 364, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4158, 2673, 63, 20, 65, 273, 394, 9913, 548, 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 ]
./partial_match/1/0x6B83aC391c59FEA54e48517FD5b5B1084f81c50B/sources/BitDividend.sol
These are going to store the popcorn perk taxes, which are reduced. See below
contract BitDividend is IBEP20, Auth { using SafeMath for uint256; string constant _name = "Bit Dividend"; string constant _symbol = "BitDiv"; uint8 constant _decimals = 9; address DEAD = 0x000000000000000000000000000000000000dEaD; address ZERO = 0x0000000000000000000000000000000000000000; address routerAddress = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address RewardToken = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; bool public restrictWhales = true; mapping (address => uint256) _balances; mapping (address => mapping (address => uint256)) _allowances; mapping (address => bool) public isFeeExempt; mapping (address => bool) public isTxLimitExempt; mapping (address => bool) public isDividendExempt; uint256 public liquidityFee = 0; uint256 public marketingFee = 2; uint256 public rewardsFee = 5; uint256 public totalFee = 0; uint256 public totalFeeIfSelling = 0; uint256 public totalFeeForPopcornPerk = 0; uint256 public totalFeeForPopcornPerkIfSelling = 0; address public autoLiquidityReceiver; address public marketingWallet; IDEXRouter public router; address public pair; uint256 public launchedAt; bool public tradingOpen = true; DividendDistributor public dividendDistributor; uint256 distributorGas = 750000; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; bool public swapAndLiquifyByLimitOnly = false; uint256 public swapThreshold = _totalSupply * 5 / 2000; modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor () Auth(msg.sender) { router = IDEXRouter(routerAddress); pair = IDEXFactory(router.factory()).createPair(router.WETH(), address(this)); _allowances[address(this)][address(router)] = uint256(-1); dividendDistributor = new DividendDistributor(address(router)); isFeeExempt[msg.sender] = true; isFeeExempt[address(this)] = true; isTxLimitExempt[msg.sender] = true; isTxLimitExempt[pair] = true; isDividendExempt[pair] = true; isDividendExempt[msg.sender] = true; isDividendExempt[address(this)] = true; isDividendExempt[DEAD] = true; isDividendExempt[ZERO] = true; totalFee = liquidityFee.add(marketingFee).add(rewardsFee); totalFeeIfSelling = totalFee; The normal marketing fee is set above with the total. But take a look below. The marketing fee with popcorn perks is halved. You can divide this be any other number you want. It could be /10 or even removed altogether. totalFeeForPopcornPerk = liquidityFee.add(marketingFee/2).add(rewardsFee); totalFeeForPopcornPerkIfSelling = totalFeeForPopcornPerk; _balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } receive() external payable { } function name() external pure override returns (string memory) { return _name; } function symbol() external pure override returns (string memory) { return _symbol; } function decimals() external pure override returns (uint8) { return _decimals; } function totalSupply() external view override returns (uint256) { return _totalSupply; } function getOwner() external view override returns (address) { return owner; } function getCirculatingSupply() public view returns (uint256) { return _totalSupply.sub(balanceOf(DEAD)).sub(balanceOf(ZERO)); } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function allowance(address holder, address spender) external view override returns (uint256) { return _allowances[holder][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function approveMax(address spender) external returns (bool) { return approve(spender, uint256(-1)); } function claimDividend() external { dividendDistributor.claimDividend(msg.sender); } function launched() internal view returns (bool) { return launchedAt != 0; } function launch() internal { launchedAt = block.number; } function changeTxLimit(uint256 newLimit) external authorized { _maxTxAmount = newLimit; } function checkTxLimit(address sender, uint256 amount) internal view { require(amount <= _maxTxAmount || isTxLimitExempt[sender], "TX Limit Exceeded"); } function changeWalletLimit(uint256 newLimit) external authorized { _walletMax = newLimit; } function changeIsFeeExempt(address holder, bool exempt) external authorized { isFeeExempt[holder] = exempt; } function changeIsTxLimitExempt(address holder, bool exempt) external authorized { isTxLimitExempt[holder] = exempt; } function changeIsDividendExempt(address holder, bool exempt) external authorized { require(holder != address(this) && holder != pair); isDividendExempt[holder] = exempt; if(exempt){ dividendDistributor.setShare(holder, 0); dividendDistributor.setShare(holder, _balances[holder]); } } function changeIsDividendExempt(address holder, bool exempt) external authorized { require(holder != address(this) && holder != pair); isDividendExempt[holder] = exempt; if(exempt){ dividendDistributor.setShare(holder, 0); dividendDistributor.setShare(holder, _balances[holder]); } } }else{ function changeFees(uint256 newLiqFee, uint256 newRewardFee, uint256 newMarketingFee) external authorized { liquidityFee = newLiqFee; rewardsFee = newRewardFee; marketingFee = newMarketingFee; totalFee = liquidityFee.add(marketingFee).add(rewardsFee); totalFeeIfSelling = totalFee; totalFeeForPopcornPerk = liquidityFee.add(marketingFee/2).add(rewardsFee); totalFeeForPopcornPerkIfSelling = totalFeeForPopcornPerk; } function changeFeeReceivers(address newLiquidityReceiver, address newMarketingWallet) external authorized { autoLiquidityReceiver = newLiquidityReceiver; marketingWallet = newMarketingWallet; } function changeSwapBackSettings(bool enableSwapBack, uint256 newSwapBackLimit, bool swapByLimitOnly) external authorized { swapAndLiquifyEnabled = enableSwapBack; swapThreshold = newSwapBackLimit; swapAndLiquifyByLimitOnly = swapByLimitOnly; } function changeDistributionCriteria(uint256 newinPeriod, uint256 newMinDistribution) external authorized { dividendDistributor.setDistributionCriteria(newinPeriod, newMinDistribution); } function changeDistributorSettings(uint256 gas) external authorized { require(gas < 750000); distributorGas = gas; } function setRewardToken(address _rewardToken) external authorized { dividendDistributor.setRewardToken(_rewardToken); } function transfer(address recipient, uint256 amount) external override returns (bool) { return _transferFrom(msg.sender, recipient, amount); } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { if(_allowances[sender][msg.sender] != uint256(-1)){ _allowances[sender][msg.sender] = _allowances[sender][msg.sender].sub(amount, "Insufficient Allowance"); } return _transferFrom(sender, recipient, amount); } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { if(_allowances[sender][msg.sender] != uint256(-1)){ _allowances[sender][msg.sender] = _allowances[sender][msg.sender].sub(amount, "Insufficient Allowance"); } return _transferFrom(sender, recipient, amount); } function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) { } }
4,265,373
[ 1, 29690, 854, 8554, 358, 1707, 326, 1843, 3850, 82, 1534, 79, 5320, 281, 16, 1492, 854, 13162, 18, 2164, 5712, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 6539, 7244, 26746, 353, 467, 5948, 52, 3462, 16, 3123, 288, 203, 377, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 533, 5381, 389, 529, 273, 315, 5775, 21411, 26746, 14432, 203, 565, 533, 5381, 389, 7175, 273, 315, 5775, 7244, 14432, 203, 565, 2254, 28, 5381, 389, 31734, 273, 2468, 31, 203, 203, 565, 1758, 2030, 1880, 273, 374, 92, 12648, 12648, 12648, 12648, 2787, 72, 41, 69, 40, 31, 203, 565, 1758, 18449, 273, 374, 92, 12648, 12648, 12648, 12648, 12648, 31, 203, 565, 1758, 4633, 1887, 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, 565, 1758, 534, 359, 1060, 1345, 273, 374, 92, 3787, 4848, 2046, 39, 25, 41, 2539, 9452, 69, 4700, 23, 37, 69, 6334, 74, 16283, 3030, 40, 74, 27, 39, 3657, 23, 13459, 22, 39, 25, 2733, 31, 203, 203, 203, 565, 1426, 1071, 13108, 2888, 5408, 273, 638, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 389, 70, 26488, 31, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 389, 5965, 6872, 31, 203, 203, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 353, 14667, 424, 5744, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 353, 4188, 3039, 424, 5744, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 353, 7244, 26746, 424, 5744, 2 ]
// File: node_modules\@openzeppelin\contracts\introspection\IERC165.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: node_modules\@openzeppelin\contracts\token\ERC1155\IERC1155.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // File: node_modules\@openzeppelin\contracts\token\ERC1155\IERC1155MetadataURI.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // File: node_modules\@openzeppelin\contracts\token\ERC1155\IERC1155Receiver.sol pragma solidity >=0.6.0 <0.8.0; /** * _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // File: node_modules\@openzeppelin\contracts\utils\Context.sol pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: node_modules\@openzeppelin\contracts\introspection\ERC165.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: 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, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: 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); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin\contracts\token\ERC1155\ERC1155.sol pragma solidity >=0.6.0 <0.8.0; /** * * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using SafeMath for uint256; using Address for address; // Mapping from token ID to account balances mapping (uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping (address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /* * bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e * bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4 * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a * bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6 * * => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^ * 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26 */ bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26; /* * bytes4(keccak256('uri(uint256)')) == 0x0e89341c */ bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c; /** * @dev See {_setURI}. */ constructor (string memory uri_) public { _setURI(uri_); // register the supported interfaces to conform to ERC1155 via ERC165 _registerInterface(_INTERFACE_ID_ERC1155); // register the supported interfaces to conform to ERC1155MetadataURI via ERC165 _registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) external view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch( address[] memory accounts, uint256[] memory ids ) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer"); _balances[id][to] = _balances[id][to].add(amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; _balances[id][from] = _balances[id][from].sub( amount, "ERC1155: insufficient balance for transfer" ); _balances[id][to] = _balances[id][to].add(amount); } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] = _balances[id][account].add(amount); emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]); } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn(address account, uint256 id, uint256 amount) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); _balances[id][account] = _balances[id][account].sub( amount, "ERC1155: burn amount exceeds balance" ); emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][account] = _balances[ids[i]][account].sub( amounts[i], "ERC1155: burn amount exceeds balance" ); } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // File: @openzeppelin\contracts\token\ERC721\IERC721.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: @openzeppelin\contracts\utils\EnumerableSet.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: contracts\TokenSign.sol pragma solidity ^0.6.0; /** * * @dev Implementation of the one and only TokenSign Signature Token. * Written by Ryley Ohlsen & Cody Ohlsen, 03.09.2021. * * See https://eips.ethereum.org/EIPS/eip-1155 * Extends openzeppelin ERC1155.sol; see: https://docs.openzeppelin.com/contracts/3.x/erc1155 */ contract TokenSign is ERC1155 { /** * @dev Emitted when 'owner' signs NFT 'nftAddr', 'nftTokenId' with Signature Token 'sigTokenId'. */ event Sign(address owner, uint256 indexed sigTokenId, address indexed nftAddr, uint256 indexed nftTokenId); /** * @dev Emitted when minter mints Signature Tokens as minter index 'minterId' with name 'name'. */ event Mint(address indexed minter, uint256 indexed minterId, string name, bool isFounder); // Add the openzeppelin library methods using EnumerableSet for EnumerableSet.UintSet; /** * Token types: * uint | description * 0 = PLATINUM * 1 = GOLD * 2 = SILVER * 3 = INK * 4 = DEV * 5 = FOUNDER */ /* * number of each signature token type to mint, per address, only once */ uint256 public constant N_PLATINUM = 3; uint256 public constant N_GOLD = 9; uint256 public constant N_SILVER = 200; // effectively unlimited ink tokens, minter can do whatever they please uint256 public constant N_INK = 1000; // devs receive a dev signature token to commemorate every minting, run the front end uint256 public constant N_DEV = 1; // special first year - minter receives single founder signature token uint256 public constant N_FOUNDER = 1; // token ids per set uint256 private constant TOKEN_IDS_PER_SET = 6; bool public foundingEventActive = true; uint256 public birthTime; uint256 private constant SECONDS_IN_YEAR = 31556952; // error messages string private constant DUPLICATE_MINT_ERROR = "DUPLICATE MINT ERROR: Minting only allowed once per address"; string private constant END_FOUNDERS_ERROR = "END FOUNDERS ERROR: The founder's event lasts 1 year"; string private constant FOUNDERS_ALREADY_OVER = "FOUNDERS OVER: The founder's event is already over"; string private constant OWNERSHIP_ERROR = "OWNERSHIP ERROR: Only the owner of an ERC-721 may sign it"; string private constant ALREADY_SIGNED_ERROR = "ALREADY SIGNED ERROR: An ERC-721 may only be signed once by each Signature Token ID"; // util constants uint256 private constant N_BURN = 1; // next token id to mint uint256 public nextTokenId = 0; // map of ERC-721 addresses to ERC-721 tokenId to EnumerableSet of signatureTokenIds that have signed the ERC-721 mapping(address => mapping(uint256 => EnumerableSet.UintSet)) private signatures; // map of minter address to bool representing if an address has minted mapping(address => bool) public hasMinted; // dev address address public devs; constructor() public ERC1155("https://api.tokensign.app/item/{id}.json") { birthTime = block.timestamp; // record who the devs are devs = msg.sender; // mint first signatures ever to the devs mint("TokenSign Creators"); } /** * Mint your signature tokens! * @param name: Minter's name. Whatever the minter wants it to be. Can never be changed. */ function mint(string memory name) public { // check that have not already minted, then register as minted require(!hasMinted[msg.sender], DUPLICATE_MINT_ERROR); hasMinted[msg.sender] = true; uint256 tmpId = nextTokenId; // build up for batch mint if (foundingEventActive) { uint256[] memory ids = new uint256[](TOKEN_IDS_PER_SET-1); uint256[] memory amounts = new uint256[](TOKEN_IDS_PER_SET-1); ids[0] = tmpId; amounts[0] = N_PLATINUM; ids[1] = tmpId+1; amounts[1] = N_GOLD; ids[2] = tmpId+2; amounts[2] = N_SILVER; ids[3] = tmpId+3; amounts[3] = N_INK; ids[4] = tmpId+5; // intentional! amounts[4] = N_FOUNDER; _mintBatch(msg.sender, ids, amounts, ""); } else { uint256[] memory ids = new uint256[](TOKEN_IDS_PER_SET-2); uint256[] memory amounts = new uint256[](TOKEN_IDS_PER_SET-2); ids[0] = tmpId; amounts[0] = N_PLATINUM; ids[1] = tmpId+1; amounts[1] = N_GOLD; ids[2] = tmpId+2; amounts[2] = N_SILVER; ids[3] = tmpId+3; amounts[3] = N_INK; _mintBatch(msg.sender, ids, amounts, ""); } _mint(devs, tmpId+4, N_DEV, ""); // emit Mint event emit Mint(msg.sender, nextTokenId.div(TOKEN_IDS_PER_SET), name, foundingEventActive); nextTokenId += TOKEN_IDS_PER_SET; } /** * Anyone can call to end the founder event after the first year has passed */ function endFounderEvent() external { require(birthTime + SECONDS_IN_YEAR < block.timestamp, END_FOUNDERS_ERROR); require(foundingEventActive, FOUNDERS_ALREADY_OVER); foundingEventActive = false; } /** * Call sign to sign any ERC-721 owned by msg.sender with a signature token, * while also burning your signature token. * * @param nftAddr: address of NFT to be signed * @param nftTokenId: tokenId of NFT to be signed, at nftAddr * @param sigTokenId: signature tokenId to sign with (in this contract) */ function sign(address nftAddr, uint256 nftTokenId, uint256 sigTokenId) external { // sender must own the NFT to be signed IERC721 ERC721 = IERC721(nftAddr); require(ERC721.ownerOf(nftTokenId) == msg.sender, OWNERSHIP_ERROR); // burn the signature token _burn(msg.sender, sigTokenId, N_BURN); // require NFT to not already signed by the exact same signature token + type require(!signatures[nftAddr][nftTokenId].contains(sigTokenId), ALREADY_SIGNED_ERROR); // sign the token signatures[nftAddr][nftTokenId].add(sigTokenId); // emit Sign event emit Sign(msg.sender, sigTokenId, nftAddr, nftTokenId); } // ALL FUNCTIONS AFTER THIS POINT ARE READ-ONLY /** * Returns number of signatures currently on a given ERC-721 NFT * * @param nftAddr: address of ERC-721 NFT to be queried * @param nftTokenId: tokenId of ERC-721 NFT to be queried, at nftAddr * @return uint256 quantity of signatures on the queried ERC-721 NFT */ function nftSignatureQuantity(address nftAddr, uint256 nftTokenId) external view returns (uint256) { return signatures[nftAddr][nftTokenId].length(); } /** * Returns the signature token ID that signed at a specific index for a given ERC-721 NFT * * @param nftAddr: address of ERC-721 NFT to be queried * @param nftTokenId: tokenId of ERC-721 NFT to be queried, at nftAddr * @param index: index of signature token ID to return * @return uint256 signature token id at queried index */ function nftSignatureIdAtIndex(address nftAddr, uint256 nftTokenId, uint256 index) external view returns (uint256) { return signatures[nftAddr][nftTokenId].at(index); } }
* @dev See {IERC1155-safeBatchTransferFrom}./
function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; _balances[id][from] = _balances[id][from].sub( amount, "ERC1155: insufficient balance for transfer" ); _balances[id][to] = _balances[id][to].add(amount); } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); }
11,817,094
[ 1, 9704, 288, 45, 654, 39, 2499, 2539, 17, 4626, 4497, 5912, 1265, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 445, 4183, 4497, 5912, 1265, 12, 203, 5411, 1758, 628, 16, 203, 5411, 1758, 358, 16, 203, 5411, 2254, 5034, 8526, 3778, 3258, 16, 203, 5411, 2254, 5034, 8526, 3778, 30980, 16, 203, 5411, 1731, 3778, 501, 203, 3639, 262, 203, 5411, 1071, 203, 5411, 5024, 203, 5411, 3849, 203, 3639, 288, 203, 5411, 2583, 12, 2232, 18, 2469, 422, 30980, 18, 2469, 16, 315, 654, 39, 2499, 2539, 30, 3258, 471, 30980, 769, 13484, 8863, 203, 5411, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 2499, 2539, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 5411, 2583, 12, 203, 7734, 628, 422, 389, 3576, 12021, 1435, 747, 353, 31639, 1290, 1595, 12, 2080, 16, 389, 3576, 12021, 1435, 3631, 203, 7734, 315, 654, 39, 2499, 2539, 30, 7412, 4894, 353, 486, 3410, 12517, 20412, 6, 203, 5411, 11272, 203, 203, 5411, 1758, 3726, 273, 389, 3576, 12021, 5621, 203, 203, 5411, 389, 5771, 1345, 5912, 12, 9497, 16, 628, 16, 358, 16, 3258, 16, 30980, 16, 501, 1769, 203, 203, 5411, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 3258, 18, 2469, 31, 965, 77, 13, 288, 203, 7734, 2254, 5034, 612, 273, 3258, 63, 77, 15533, 203, 7734, 2254, 5034, 3844, 273, 30980, 63, 77, 15533, 203, 203, 7734, 389, 70, 26488, 63, 350, 6362, 2080, 65, 273, 389, 70, 26488, 63, 350, 6362, 2080, 8009, 1717, 12, 203, 10792, 3844, 16, 203, 10792, 315, 654, 39, 2499, 2539, 30, 2763, 11339, 11013, 364, 7412, 6, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-03-14 */ /** *Submitted for verification at Etherscan.io on 2022-02-14 */ /** *Submitted for verification at Etherscan.io on 2022-01-25 */ // SPDX-License-Identifier: MIT pragma solidity ^0.5.6; // import "@openzeppelin/contracts/ownership/Ownable.sol"; // import '@openzeppelin/contracts/token/ERC721/ERC721Holder.sol'; 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; } } contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract IERC721Receiver { function onERC721Received( address operator, address from, uint256 tokenId, bytes memory data ) public returns (bytes4); } contract ERC721Holder is IERC721Receiver { function onERC721Received( address, address, uint256, bytes memory ) public returns (bytes4) { return this.onERC721Received.selector; } } interface IMintable { // Required read methods function getApproved(uint256 tokenId) external returns (address operator); function tokenURI(uint256 tokenId) external returns (string memory); // Required write methods function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function burn(uint256 tokenId) external; function mint(string calldata _tokenURI, uint256 _royality) external; function safeTransferFrom( address from, address to, uint256 tokenId ) external; function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; function transferFrom( address from, address to, uint256 tokenId ) external; } interface IBrokerV2 { function bid( uint256 tokenID, address _mintableToken, uint256 amount ) external payable; function collect(uint256 tokenID, address _mintableToken) external; function buy(uint256 tokenID, address _mintableToken) external payable; function putOnSale( uint256 _tokenID, uint256 _startingPrice, uint256 _auctionType, uint256 _buyPrice, uint256 _startingTime, uint256 _closingTime, address _mintableToken, address _erc20Token ) external; function updatePrice( uint256 tokenID, address _mintableToken, uint256 _newPrice, address _erc20Token ) external; function putSaleOff(uint256 tokenID, address _mintableToken) external; function makeAnOffer( uint256 tokenID, address _mintableToken, address _erc20Token, uint256 amount ) external payable; function accpetOffer( uint256 tokenID, address _mintableToken, address _erc20Token ) external payable; function revertOffer( address _mintableToken, uint256 tokenID, address _erc20Token ) external payable; function revertAll(address _mintableToken, uint256 tokenID) external; } interface IERC20 { function approve(address spender, uint256 value) external; function decreaseApproval(address _spender, uint256 _subtractedValue) external; function increaseApproval(address spender, uint256 addedValue) external; function transfer(address to, uint256 value) external; function transferFrom( address from, address to, uint256 value ) external; function increaseAllowance(address spender, uint256 addedValue) external; function decreaseAllowance(address spender, uint256 subtractedValue) external; function balanceOf(address who) external view returns (uint256); } /** * @title AdminManager * @author Yogesh Singh * @notice You can use this contract to execute function on behalf of superUser * @dev Mediator contract to allow muliple user to perform ERC721 action using contracts address only */ contract AdminManager is Ownable, ERC721Holder { address[] public admins; struct FunctionNames { string approve; string transfer; string burn; string mint; string safeTransferFrom; string transferFrom; string putOnSale; string buy; string bid; string collect; string updatePrice; string putSaleOff; string makeAnOffer; string accpetOffer; string revertOffer; string revertAll; string erc20Approve; string erc20DecreaseApproval; string erc20IncreaseApproval; string erc20Transfer; string erc20TransferFrom; string erc20IncreaseAllowance; string erc20DecreaseAllowance; } FunctionNames functionNames = FunctionNames( "ERC721:approve", "ERC721:transfer", "ERC721:burn", "ERC721:mint", "ERC721:safeTransferFrom", "ERC721:transferFrom", "Broker:putOnSale", "Broker:buy", "Broker:bid", "Broker:collect", "Broker:updatePrice", "Broker:putSaleOff", "Broker:makeAnOffer", "Broker:accpetOffer", "Broker:revertOffer", "Broker:revertAll", "ERC20:approve", "ERC20:decreaseApproval", "ERC20:increaseApproval", "ERC20:transfer", "ERC20:transferFrom", "ERC20:increaseAllowance", "ERC20:decreaseAllowance" ); IBrokerV2 broker; event NFTBurned( address indexed collection, uint256 indexed tokenId, address indexed admin, uint256 time, string tokenURI ); event AdminRemoved(address admin, uint256 time); event AdminAdded(address admin, uint256 time); event AdminActionPerformed( address indexed admin, address indexed contractAddress, string indexed functionName, address collectionAddress, uint256 tokenId ); constructor(address _broker) public { transferOwnership(msg.sender); broker = IBrokerV2(_broker); } /** * @notice This function is used to check address of admin exist or not in list of admin * @dev Fuction take address type argument * @param _sender The account address of _sender or admin */ function adminExist(address _sender) public view returns (bool) { for (uint256 i = 0; i < admins.length; i++) { if (_sender == admins[i]) { return true; } } return false; } modifier adminOnly() { require(adminExist(msg.sender), "AdminManager: admin only."); _; } modifier adminAndOwnerOnly() { require( adminExist(msg.sender) || isOwner(), "AdminManager: admin and owner only." ); _; } /** * @notice This function is used to add address of admins * @dev Fuction take address type argument * @param admin The account address of admin */ function addAdmin(address admin) public onlyOwner { if (!adminExist(admin)) { admins.push(admin); } else { revert("admin already in list"); } emit AdminAdded(admin, block.timestamp); } /** * @notice This function is used to get list of all address of admins * @dev This Fuction is not take any argument * @return This Fuction return list of address[] */ function getAdmins() public view returns (address[] memory) { return admins; } /** * @notice This function is used to get list of all address of admins * @dev This Fuction is not take any argument * @param admin The account address of admin */ function removeAdmin(address admin) public onlyOwner { for (uint256 i = 0; i < admins.length; i++) { if (admins[i] == admin) { admins[admins.length - 1] = admins[i]; admins.pop(); break; } } emit AdminRemoved(admin, block.timestamp); } /** * @notice This function is used to burn the apporved NFTToken to certain admin address which was allowed by super admin the owner of Admin Manager * @dev This Fuction is take two arguments address of contract and tokenId of NFT * @param collection tokenId The contract address of NFT contract and tokenId of NFT */ function burnNFT(address collection, uint256 tokenId) public adminAndOwnerOnly { IMintable NFTToken = IMintable(collection); string memory tokenURI = NFTToken.tokenURI(tokenId); require( NFTToken.getApproved(tokenId) == address(this), "Token not apporove for burn" ); NFTToken.burn(tokenId); emit NFTBurned( collection, tokenId, msg.sender, block.timestamp, tokenURI ); } // NFT methods for admin to manage by this contract URL function erc721Approve( address _ERC721Address, address _to, uint256 _tokenId ) public adminAndOwnerOnly { IMintable erc721 = IMintable(_ERC721Address); emit AdminActionPerformed( msg.sender, _ERC721Address, functionNames.approve, _ERC721Address, _tokenId ); return erc721.approve(_to, _tokenId); } function erc721Transfer( address _ERC721Address, address _to, uint256 _tokenId ) public adminAndOwnerOnly { IMintable erc721 = IMintable(_ERC721Address); emit AdminActionPerformed( msg.sender, _ERC721Address, functionNames.transfer, _ERC721Address, _tokenId ); return erc721.transfer(_to, _tokenId); } function erc721Burn(address _ERC721Address, uint256 tokenId) public adminAndOwnerOnly { IMintable erc721 = IMintable(_ERC721Address); emit AdminActionPerformed( msg.sender, _ERC721Address, functionNames.burn, _ERC721Address, tokenId ); return erc721.burn(tokenId); } function erc721Mint( address _ERC721Address, string memory tokenURI, uint256 _royality ) public adminAndOwnerOnly { IMintable erc721 = IMintable(_ERC721Address); emit AdminActionPerformed( msg.sender, _ERC721Address, functionNames.mint, _ERC721Address, 0 ); return erc721.mint(tokenURI, _royality); } function erc721SafeTransferFrom( address _ERC721Address, address from, address to, uint256 tokenId ) public adminAndOwnerOnly { IMintable erc721 = IMintable(_ERC721Address); emit AdminActionPerformed( msg.sender, _ERC721Address, functionNames.safeTransferFrom, _ERC721Address, tokenId ); return erc721.safeTransferFrom(from, to, tokenId); } function erc721SafeTransferFrom( address _ERC721Address, address from, address to, uint256 tokenId, bytes memory _data ) public adminAndOwnerOnly { IMintable erc721 = IMintable(_ERC721Address); emit AdminActionPerformed( msg.sender, _ERC721Address, functionNames.safeTransferFrom, _ERC721Address, tokenId ); return erc721.safeTransferFrom(from, to, tokenId, _data); } function erc721TransferFrom( address _ERC721Address, address from, address to, uint256 tokenId ) public adminAndOwnerOnly { IMintable erc721 = IMintable(_ERC721Address); emit AdminActionPerformed( msg.sender, _ERC721Address, functionNames.transferFrom, _ERC721Address, tokenId ); return erc721.transferFrom(from, to, tokenId); } // Broker functions function bid( uint256 tokenID, address _mintableToken, uint256 amount ) public payable adminAndOwnerOnly { broker.bid.value(msg.value)(tokenID, _mintableToken, amount); emit AdminActionPerformed( msg.sender, address(broker), functionNames.bid, _mintableToken, tokenID ); } function collect(uint256 tokenID, address _mintableToken) public adminAndOwnerOnly { broker.collect(tokenID, _mintableToken); emit AdminActionPerformed( msg.sender, address(broker), functionNames.collect, _mintableToken, tokenID ); } function buy(uint256 tokenID, address _mintableToken) public payable adminAndOwnerOnly { broker.buy.value(msg.value)(tokenID, _mintableToken); emit AdminActionPerformed( msg.sender, address(broker), functionNames.buy, _mintableToken, tokenID ); } function putOnSale( uint256 _tokenID, uint256 _startingPrice, uint256 _auctionType, uint256 _buyPrice, uint256 _startingTime, uint256 _closingTime, address _mintableToken, address _erc20Token ) public adminAndOwnerOnly { broker.putOnSale( _tokenID, _startingPrice, _auctionType, _buyPrice, _startingTime, _closingTime, _mintableToken, _erc20Token ); emit AdminActionPerformed( msg.sender, address(broker), functionNames.putOnSale, _mintableToken, _tokenID ); } function updatePrice( uint256 tokenID, address _mintableToken, uint256 _newPrice, address _erc20Token ) public adminAndOwnerOnly { broker.updatePrice(tokenID, _mintableToken, _newPrice, _erc20Token); emit AdminActionPerformed( msg.sender, address(broker), functionNames.updatePrice, _mintableToken, tokenID ); } function putSaleOff(uint256 tokenID, address _mintableToken) public adminAndOwnerOnly { broker.putSaleOff(tokenID, _mintableToken); emit AdminActionPerformed( msg.sender, address(broker), functionNames.putSaleOff, _mintableToken, tokenID ); } function makeAnOffer( uint256 tokenID, address _mintableToken, address _erc20Token, uint256 amount ) public payable adminAndOwnerOnly { broker.makeAnOffer(tokenID, _mintableToken, _erc20Token, amount); emit AdminActionPerformed( msg.sender, address(broker), functionNames.makeAnOffer, _mintableToken, tokenID ); } function accpetOffer( uint256 tokenID, address _mintableToken, address _erc20Token ) public payable adminAndOwnerOnly { broker.accpetOffer(tokenID, _mintableToken, _erc20Token); emit AdminActionPerformed( msg.sender, address(broker), functionNames.accpetOffer, _mintableToken, tokenID ); } function revertOffer( uint256 tokenID, address _mintableToken, address _erc20Token ) public payable adminAndOwnerOnly { broker.revertOffer(_mintableToken,tokenID, _erc20Token); emit AdminActionPerformed( msg.sender, address(broker), functionNames.revertOffer, _mintableToken, tokenID ); } function revertAll(uint256 tokenID, address _mintableToken) public adminAndOwnerOnly { broker.revertAll(_mintableToken,tokenID); emit AdminActionPerformed( msg.sender, address(broker), functionNames.revertAll, _mintableToken, tokenID ); } // ERC20 methods function erc20Approve( address _erc20, address spender, uint256 value ) public adminAndOwnerOnly { IERC20 erc20 = IERC20(_erc20); erc20.approve(spender, value); emit AdminActionPerformed( msg.sender, _erc20, functionNames.erc20Approve, spender, value ); } function erc20DecreaseApproval( address _erc20, address _spender, uint256 _subtractedValue ) public adminAndOwnerOnly { IERC20 erc20 = IERC20(_erc20); erc20.decreaseApproval(_spender, _subtractedValue); emit AdminActionPerformed( msg.sender, _erc20, functionNames.erc20DecreaseAllowance, _spender, _subtractedValue ); } function erc20IncreaseApproval( address _erc20, address spender, uint256 addedValue ) public adminAndOwnerOnly { IERC20 erc20 = IERC20(_erc20); erc20.increaseApproval(spender, addedValue); emit AdminActionPerformed( msg.sender, _erc20, functionNames.erc20IncreaseApproval, spender, addedValue ); } function erc20Transfer( address _erc20, address to, uint256 value ) public adminAndOwnerOnly { IERC20 erc20 = IERC20(_erc20); erc20.transfer(to, value); emit AdminActionPerformed( msg.sender, _erc20, functionNames.erc20Transfer, to, value ); } function erc20TransferFrom( address _erc20, address from, address to, uint256 value ) public adminAndOwnerOnly { IERC20 erc20 = IERC20(_erc20); erc20.transferFrom(from, to, value); emit AdminActionPerformed( msg.sender, _erc20, functionNames.erc20TransferFrom, to, value ); } function erc20IncreaseAllowance( address _erc20, address spender, uint256 addedValue ) public adminAndOwnerOnly { IERC20 erc20 = IERC20(_erc20); erc20.increaseAllowance(spender, addedValue); emit AdminActionPerformed( msg.sender, _erc20, functionNames.erc20IncreaseAllowance, spender, addedValue ); } function erc20DecreaseAllowance( address _erc20, address spender, uint256 subtractedValue ) public adminAndOwnerOnly { IERC20 erc20 = IERC20(_erc20); erc20.decreaseAllowance(spender, subtractedValue); emit AdminActionPerformed( msg.sender, _erc20, functionNames.erc20DecreaseAllowance, spender, subtractedValue ); } // Fallback function function() external payable {} function withdraw() public onlyOwner { msg.sender.transfer(address(this).balance); } function withdrawERC20(address _erc20Token) public onlyOwner { IERC20 erc20Token = IERC20(_erc20Token); erc20Token.transfer(msg.sender, erc20Token.balanceOf(address(this))); } }
* @notice This function is used to add address of admins @dev Fuction take address type argument @param admin The account address of admin/
function addAdmin(address admin) public onlyOwner { if (!adminExist(admin)) { admins.push(admin); revert("admin already in list"); } emit AdminAdded(admin, block.timestamp); }
5,854,279
[ 1, 2503, 445, 353, 1399, 358, 527, 1758, 434, 31116, 225, 478, 4062, 4862, 1758, 618, 1237, 225, 3981, 1021, 2236, 1758, 434, 3981, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 4446, 12, 2867, 3981, 13, 1071, 1338, 5541, 288, 203, 3639, 309, 16051, 3666, 4786, 12, 3666, 3719, 288, 203, 5411, 31116, 18, 6206, 12, 3666, 1769, 203, 5411, 15226, 2932, 3666, 1818, 316, 666, 8863, 203, 3639, 289, 203, 203, 3639, 3626, 7807, 8602, 12, 3666, 16, 1203, 18, 5508, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.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; } /** * Magnetics token smart contract. */ contract MagneticsToken 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 Magnetics 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 MagneticsToken (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 "Magnetics"; } /** * Get symbol of this token. * * @return symbol of this token */ function symbol () public pure returns (string result) { return "KLIX"; } /** * 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; } /** * Burn given number of tokens belonging to message sender. * * @param _value number of tokens to burn * @return true on success, false on error */ function burnTokens (uint256 _value) public returns (bool success) { if (_value > accounts [msg.sender]) return false; else if (_value > 0) { accounts [msg.sender] = safeSub (accounts [msg.sender], _value); tokenCount = safeSub (tokenCount, _value); Transfer (msg.sender, address (0), _value); return true; } else return true; } /** * 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 (); }
* Get symbol of this token. @return symbol of this token/
function symbol () public pure returns (string result) { return "KLIX"; }
12,205,714
[ 1, 967, 3273, 434, 333, 1147, 18, 327, 3273, 434, 333, 1147, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 3273, 1832, 1071, 16618, 1135, 261, 1080, 563, 13, 288, 203, 565, 327, 315, 47, 2053, 60, 14432, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x67141005b5B81293b94B5c6541d54Bf5C9A44F62/sources/contracts/crypto-bugs-short.sol
Updates the internal state, this is done before the transfer to prevent re-entrancy bugs.
amountsWithdrew[msg.sender] += transferring;
736,821
[ 1, 5121, 326, 2713, 919, 16, 333, 353, 2731, 1865, 326, 7412, 358, 5309, 283, 17, 8230, 12514, 22398, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 30980, 1190, 72, 16052, 63, 3576, 18, 15330, 65, 1011, 906, 74, 20245, 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/1/0x6397B894b1C68951Bb7164979bf8a95CCebA540b/sources/contracts/FixedVesting.sol
* @dev Insert new vestings @param _datetime Vesting datetime @param _ratio_d2 Vesting ratio in percent (decimal 2)/
function _newVesting( uint128[] calldata _datetime, uint128[] calldata _ratio_d2 ) private { require(_datetime.length == _ratio_d2.length, "!good"); uint128 vestingSize = vestingLength; for(uint128 i=0; i<_datetime.length; i++){ if(i != _datetime.length-1) require(_datetime[i] < _datetime[i+1], "!good"); vestingSize += 1; vesting[vestingSize] = Detail(_datetime[i], _ratio_d2[i]); } vestingLength = vestingSize; }
8,336,689
[ 1, 4600, 394, 331, 395, 899, 225, 389, 6585, 776, 10100, 3314, 225, 389, 9847, 67, 72, 22, 776, 10100, 7169, 316, 5551, 261, 12586, 576, 13176, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2704, 58, 10100, 12, 203, 3639, 2254, 10392, 8526, 745, 892, 389, 6585, 16, 203, 3639, 2254, 10392, 8526, 745, 892, 389, 9847, 67, 72, 22, 203, 565, 262, 3238, 288, 203, 3639, 2583, 24899, 6585, 18, 2469, 422, 389, 9847, 67, 72, 22, 18, 2469, 16, 17528, 19747, 8863, 203, 203, 3639, 2254, 10392, 331, 10100, 1225, 273, 331, 10100, 1782, 31, 203, 3639, 364, 12, 11890, 10392, 277, 33, 20, 31, 277, 32, 67, 6585, 18, 2469, 31, 277, 27245, 95, 203, 5411, 309, 12, 77, 480, 389, 6585, 18, 2469, 17, 21, 13, 2583, 24899, 6585, 63, 77, 65, 411, 389, 6585, 63, 77, 15, 21, 6487, 17528, 19747, 8863, 203, 5411, 331, 10100, 1225, 1011, 404, 31, 203, 5411, 331, 10100, 63, 90, 10100, 1225, 65, 273, 27931, 24899, 6585, 63, 77, 6487, 389, 9847, 67, 72, 22, 63, 77, 19226, 203, 3639, 289, 203, 203, 3639, 331, 10100, 1782, 273, 331, 10100, 1225, 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 ]
./full_match/1/0x9eE4530EE122E82c700Ef355CC9b8F11079AE636/sources/contracts/incentives/YieldDistributorAdapter.sol
reserve internal asset -> variable yield distributors
mapping(address => address) private _reserveToVDistributor;
3,217,611
[ 1, 455, 6527, 2713, 3310, 317, 2190, 2824, 1015, 665, 13595, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 12, 2867, 516, 1758, 13, 3238, 389, 455, 6527, 774, 58, 1669, 19293, 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 ]